Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

Corrections based on test failures

Will28156ecba8b2
diff --git a/browser_use/llm/openrouter/chat.py b/browser_use/llm/openrouter/chat.py
index bb8b91278..871fe007e 100644
--- a/browser_use/llm/openrouter/chat.py
+++ b/browser_use/llm/openrouter/chat.py
@@ -149,11 +149,41 @@ class ChatOpenRouter(BaseChatModel):
else:
# Create a JSON schema for structured output
- response_format = {
- 'name': 'agent_output',
- 'strict': True,
- 'schema': SchemaOptimizer.create_optimized_json_schema(output_format),
- }
+ schema = 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)
# Return structured response
response = await self.get_client().chat.completions.create(
@@ -173,12 +203,24 @@ class ChatOpenRouter(BaseChatModel):
usage = self._get_usage(response)
- parsed = output_format.model_validate_json(response.choices[0].message.content)
-
- return ChatInvokeCompletion(
- completion=parsed,
- usage=usage,
- )
+ 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
except RateLimitError as e:
error_message = e.response.json().get('error', {})