Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
feat: use json schema format in ChatOpenRouter
Will Bonde6162bed81eca
diff --git a/browser_use/llm/openrouter/chat.py b/browser_use/llm/openrouter/chat.pyindex d624bf332..a282ef6aa 100644--- a/browser_use/llm/openrouter/chat.py+++ b/browser_use/llm/openrouter/chat.py@@ -5,6 +5,10 @@ from typing import Any, TypeVar, overloadimport httpxfrom openai import APIConnectionError, APIStatusError, AsyncOpenAI, RateLimitErrorfrom openai.types.chat.chat_completion import ChatCompletion+from openai.types.shared_params.response_format_json_schema import (+ JSONSchema,+ ResponseFormatJSONSchema,+)from pydantic import BaseModelfrom browser_use.llm.base import BaseChatModel@@ -152,46 +156,21 @@ class ChatOpenRouter(BaseChatModel):# Create a JSON schema for structured outputschema = SchemaOptimizer.create_optimized_json_schema(output_format)- # Create a more explicit instruction based on the schema fields- schema_fields = list(schema.get("properties", {}).keys())- fields_str = ", ".join(schema_fields)-- # Construct instructions about the required format- json_instruction = (- f"Please provide your response as a JSON object with these fields: {fields_str}. "- f"For example: {{"- )-- # Add example values for each field- for field in schema_fields:- json_instruction += f'"{field}": "<{field}_value>", '-- # Remove trailing comma and space and close the example- json_instruction = json_instruction.rstrip(", ") + "}."-- # Add the instructions to system or user message- has_system = any(msg['role'] == 'system' for msg in openrouter_messages)-- if has_system:- # Append to the first system message- for msg in openrouter_messages:- if msg['role'] == 'system':- msg['content'] += f" {json_instruction}"- break- else:- # If no system message, add a new system message with the instructions- system_message = {- 'role': 'system',- 'content': f"You are a helpful assistant. {json_instruction}"- }- openrouter_messages.insert(0, system_message)+ response_format_schema: JSONSchema = {+ 'name': 'agent_output',+ 'strict': True,+ 'schema': schema,+ }# Return structured responseresponse = await self.get_client().chat.completions.create(model=self.model,messages=openrouter_messages,temperature=self.temperature,- response_format={"type": "json_object"},+ response_format=ResponseFormatJSONSchema(+ json_schema=response_format_schema,+ type='json_schema',+ ),extra_headers=extra_headers,)@@ -201,27 +180,16 @@ class ChatOpenRouter(BaseChatModel):status_code=500,model=self.name,)-usage = self._get_usage(response)- try:- # Try to parse the JSON response- parsed = output_format.model_validate_json(response.choices[0].message.content)- return ChatInvokeCompletion(- completion=parsed,- usage=usage,- )- except Exception as e:- # If parsing fails, provide a more detailed error- error_msg = (- f"Failed to parse response as {output_format.__name__}: {str(e)}. "- f"Response content: {response.choices[0].message.content}"- )- raise ModelProviderError(- message=error_msg,- status_code=500,- model=self.name,- ) from e+ parsed = output_format.model_validate_json(+ response.choices[0].message.content+ )++ return ChatInvokeCompletion(+ completion=parsed,+ usage=usage,+ )except RateLimitError as e:error_message = e.response.json().get('error', {})diff --git a/browser_use/llm/tests/test_chat_models.py b/browser_use/llm/tests/test_chat_models.pyindex d48c9dc46..3aed45ba0 100644--- a/browser_use/llm/tests/test_chat_models.py+++ b/browser_use/llm/tests/test_chat_models.py@@ -3,6 +3,8 @@ import osimport pytestfrom pydantic import BaseModel+from browser_use.agent.views import AgentOutput+from browser_use.controller.service import Controllerfrom browser_use.llm import ChatAnthropic, ChatGoogle, ChatGroq, ChatOpenAI, ChatOpenRouterfrom browser_use.llm.messages import ContentPartTextParam@@ -231,11 +233,11 @@ class TestChatModels:assert self.EXPECTED_GERMANY_CAPITAL in completion.lower()@pytest.mark.asyncio- async def test_openrouter_ainvoke_structured(self):- """Test structured output from OpenRouter"""- # Skip if no API key- if not os.getenv('OPENROUTER_API_KEY'):- pytest.skip('OPENROUTER_API_KEY not set')+ async def test_openrouter_ainvoke_structured(self):+ """Test structured output from OpenRouter"""+ # Skip if no API key+ if not os.getenv('OPENROUTER_API_KEY'):+ pytest.skip('OPENROUTER_API_KEY not set')chat = ChatOpenRouter(model='openai/gpt-4o-mini',@@ -245,6 +247,37 @@ class TestChatModels:response = await chat.ainvoke(self.STRUCTURED_MESSAGES, output_format=CapitalResponse)completion = response.completion- assert isinstance(completion, CapitalResponse)- assert completion.country.lower() == self.EXPECTED_FRANCE_COUNTRY- assert completion.capital.lower() == self.EXPECTED_FRANCE_CAPITAL\ No newline at end of file+ assert isinstance(completion, CapitalResponse)+ assert completion.country.lower() == self.EXPECTED_FRANCE_COUNTRY+ assert completion.capital.lower() == self.EXPECTED_FRANCE_CAPITAL++ @pytest.mark.asyncio+ async def test_openrouter_agent_output(self):+ """Ensure AgentOutput is parsed correctly using ChatOpenRouter."""+ controller = Controller()+ ActionModel = controller.registry.create_action_model()+ AgentOutputModel = AgentOutput.type_with_custom_actions(ActionModel)++ json_response = (+ '{"evaluation_previous_goal":"ok","memory":"m","next_goal":"done","action":[{"done":{"text":"ok","success":true}}]}'+ )++ class FakeCompletions:+ async def create(self, *args, **kwargs):+ return type('Resp', (), {+ 'choices': [type('C', (), {'message': type('M', (), {'content': json_response})})],+ 'usage': None,+ })()++ class FakeClient:+ def __init__(self):+ self.chat = type('Chat', (), {'completions': FakeCompletions()})()++ chat = ChatOpenRouter(model='test', api_key='test')+ chat.get_client = lambda: FakeClient() # type: ignore[assignment]++ messages = [self.UserMessage(content='test')]+ response = await chat.ainvoke(messages, output_format=AgentOutputModel)+ completion = response.completion++ assert isinstance(completion, AgentOutputModel)