Skip to content

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

optimized schema for all models

Gregor Žunič5d9fca7c4bf9
diff --git a/browser_use/controller/tests/test_custom_structured_ouput.py b/browser_use/controller/tests/test_custom_structured_ouput.py
index 4ab432f2b..d3f31b68d 100644
--- a/browser_use/controller/tests/test_custom_structured_ouput.py
+++ b/browser_use/controller/tests/test_custom_structured_ouput.py
@@ -5,7 +5,7 @@ import tiktoken
from browser_use.agent.views import AgentOutput
from browser_use.controller.service import Controller
-from browser_use.llm.utils import create_optimized_json_schema
+from browser_use.llm.schema import SchemaOptimizer
def test_optimized_schema():
@@ -22,7 +22,7 @@ def test_optimized_schema():
original_schema = agent_output_model.model_json_schema()
# Create the optimized schema
- optimized_schema = create_optimized_json_schema(agent_output_model)
+ optimized_schema = SchemaOptimizer.create_optimized_json_schema(agent_output_model)
# Create tmp directory if it doesn't exist
os.makedirs('./tmp', exist_ok=True)
diff --git a/browser_use/llm/anthropic/chat.py b/browser_use/llm/anthropic/chat.py
index 110189781..e3a45cb89 100644
--- a/browser_use/llm/anthropic/chat.py
+++ b/browser_use/llm/anthropic/chat.py
@@ -23,6 +23,7 @@ from browser_use.llm.anthropic.serializer import AnthropicMessageSerializer
from browser_use.llm.base import BaseChatModel
from browser_use.llm.exceptions import ModelProviderError, ModelRateLimitError
from browser_use.llm.messages import BaseMessage
+from browser_use.llm.schema import SchemaOptimizer
from browser_use.llm.views import ChatInvokeCompletion, ChatInvokeUsage
T = TypeVar('T', bound=BaseModel)
@@ -155,7 +156,7 @@ class ChatAnthropic(BaseChatModel):
# Use tool calling for structured output
# Create a tool that represents the output format
tool_name = output_format.__name__
- schema = output_format.model_json_schema()
+ schema = SchemaOptimizer.create_optimized_json_schema(output_format)
# Remove title from schema if present (Anthropic doesn't like it in parameters)
if 'title' in schema:
diff --git a/browser_use/llm/google/chat.py b/browser_use/llm/google/chat.py
index 68755ab78..4a9495a0a 100644
--- a/browser_use/llm/google/chat.py
+++ b/browser_use/llm/google/chat.py
@@ -12,6 +12,7 @@ from browser_use.llm.base import BaseChatModel
from browser_use.llm.exceptions import ModelProviderError
from browser_use.llm.google.serializer import GoogleMessageSerializer
from browser_use.llm.messages import BaseMessage
+from browser_use.llm.schema import SchemaOptimizer
from browser_use.llm.views import ChatInvokeCompletion, ChatInvokeUsage
T = TypeVar('T', bound=BaseModel)
@@ -201,7 +202,10 @@ class ChatGoogle(BaseChatModel):
# Return structured response
config['response_mime_type'] = 'application/json'
# Convert Pydantic model to Gemini-compatible schema
- config['response_schema'] = self._pydantic_to_gemini_schema(output_format)
+ optimized_schema = SchemaOptimizer.create_optimized_json_schema(output_format)
+
+ gemini_schema = self._fix_gemini_schema(optimized_schema)
+ config['response_schema'] = gemini_schema
response = await self.get_client().aio.models.generate_content(
model=self.model,
@@ -305,14 +309,13 @@ class ChatGoogle(BaseChatModel):
model=self.name,
) from e
- def _pydantic_to_gemini_schema(self, model_class: type[BaseModel]) -> dict[str, Any]:
+ def _fix_gemini_schema(self, schema: dict[str, Any]) -> dict[str, Any]:
"""
Convert a Pydantic model to a Gemini-compatible schema.
This function removes unsupported properties like 'additionalProperties' and resolves
$ref references that Gemini doesn't support.
"""
- schema = model_class.model_json_schema()
# Handle $defs and $ref resolution
if '$defs' in schema:
diff --git a/browser_use/llm/groq/chat.py b/browser_use/llm/groq/chat.py
index d5822c808..196c6cdb8 100644
--- a/browser_use/llm/groq/chat.py
+++ b/browser_use/llm/groq/chat.py
@@ -24,6 +24,7 @@ from browser_use.llm.exceptions import ModelProviderError, ModelRateLimitError
from browser_use.llm.groq.parser import try_parse_groq_failed_generation
from browser_use.llm.groq.serializer import GroqMessageSerializer
from browser_use.llm.messages import BaseMessage
+from browser_use.llm.schema import SchemaOptimizer
from browser_use.llm.views import ChatInvokeUsage
GroqVerifiedModels = Literal[
@@ -106,7 +107,8 @@ class ChatGroq(BaseChatModel):
)
else:
- schema = output_format.model_json_schema()
+ schema = SchemaOptimizer.create_optimized_json_schema(output_format)
+
schema['additionalProperties'] = False
# Return structured response
diff --git a/browser_use/llm/openai/chat.py b/browser_use/llm/openai/chat.py
index c09d48a8c..fb4f83083 100644
--- a/browser_use/llm/openai/chat.py
+++ b/browser_use/llm/openai/chat.py
@@ -13,7 +13,7 @@ from browser_use.llm.base import BaseChatModel
from browser_use.llm.exceptions import ModelProviderError
from browser_use.llm.messages import BaseMessage
from browser_use.llm.openai.serializer import OpenAIMessageSerializer
-from browser_use.llm.utils import create_optimized_json_schema
+from browser_use.llm.schema import SchemaOptimizer
from browser_use.llm.views import ChatInvokeCompletion, ChatInvokeUsage
T = TypeVar('T', bound=BaseModel)
@@ -148,7 +148,7 @@ class ChatOpenAI(BaseChatModel):
response_format: JSONSchema = {
'name': 'agent_output',
'strict': True,
- 'schema': create_optimized_json_schema(output_format),
+ 'schema': SchemaOptimizer.create_optimized_json_schema(output_format),
}
# Return structured response
diff --git a/browser_use/llm/schema.py b/browser_use/llm/schema.py
new file mode 100644
index 000000000..764d5d831
--- /dev/null
+++ b/browser_use/llm/schema.py
@@ -0,0 +1,143 @@
+"""
+Utilities for creating optimized Pydantic schemas for LLM usage.
+"""
+
+from typing import Any
+
+from pydantic import BaseModel
+
+
+class SchemaOptimizer:
+ @staticmethod
+ def create_optimized_json_schema(model: type[BaseModel]) -> dict[str, Any]:
+ """
+ Create the most optimized schema by flattening all $ref/$defs while preserving
+ FULL descriptions and ALL action definitions. Also ensures OpenAI strict mode compatibility.
+
+ Args:
+ model: The Pydantic model to optimize
+
+ Returns:
+ Optimized schema with all $refs resolved and strict mode compatibility
+ """
+ # Generate original schema
+ original_schema = model.model_json_schema()
+
+ # Extract $defs for reference resolution, then flatten everything
+ defs_lookup = original_schema.get('$defs', {})
+
+ def optimize_schema(obj: Any, defs_lookup: dict[str, Any] | None = None) -> Any:
+ """Apply all optimization techniques including flattening all $ref/$defs"""
+ if isinstance(obj, dict):
+ optimized: dict[str, Any] = {}
+
+ # Skip unnecessary fields AND $defs (we'll inline everything)
+ skip_fields = ['additionalProperties', '$defs']
+
+ for key, value in obj.items():
+ if key in skip_fields:
+ continue
+
+ # Skip titles completely
+ if key == 'title':
+ continue
+
+ # Preserve FULL descriptions without truncation
+ elif key == 'description':
+ optimized[key] = value
+
+ # Handle type field
+ elif key == 'type':
+ optimized[key] = value
+
+ # FLATTEN: Resolve $ref by inlining the actual definition
+ elif key == '$ref' and defs_lookup:
+ ref_path = value.split('/')[-1] # Get the definition name from "#/$defs/SomeName"
+ if ref_path in defs_lookup:
+ # Get the referenced definition and flatten it
+ referenced_def = defs_lookup[ref_path]
+ flattened_ref = optimize_schema(referenced_def, defs_lookup)
+
+ # IMPORTANT: Preserve any description that was alongside the $ref
+ if isinstance(obj, dict) and 'description' in obj:
+ if isinstance(flattened_ref, dict):
+ flattened_ref = flattened_ref.copy()
+ flattened_ref['description'] = obj['description']
+
+ return flattened_ref
+
+ # Keep all anyOf structures (action unions) and resolve any $refs within
+ elif key == 'anyOf' and isinstance(value, list):
+ optimized[key] = [optimize_schema(item, defs_lookup) for item in value]
+
+ # Recursively optimize nested structures
+ elif key in ['properties', 'items']:
+ optimized[key] = optimize_schema(value, defs_lookup)
+
+ # Keep essential validation fields
+ elif key in ['type', 'required', 'minimum', 'maximum', 'minItems', 'maxItems', 'pattern', 'default']:
+ optimized[key] = value if not isinstance(value, (dict, list)) else optimize_schema(value, defs_lookup)
+
+ # Recursively process all other fields
+ else:
+ optimized[key] = optimize_schema(value, defs_lookup) if isinstance(value, (dict, list)) else value
+
+ # CRITICAL: Add additionalProperties: false to ALL objects for OpenAI strict mode
+ if optimized.get('type') == 'object':
+ optimized['additionalProperties'] = False
+
+ return optimized
+
+ elif isinstance(obj, list):
+ return [optimize_schema(item, defs_lookup) for item in obj]
+ return obj
+
+ # Create optimized schema with flattening
+ optimized_result = optimize_schema(original_schema, defs_lookup)
+
+ # Ensure we have a dictionary (should always be the case for schema root)
+ if not isinstance(optimized_result, dict):
+ raise ValueError('Optimized schema result is not a dictionary')
+
+ optimized_schema: dict[str, Any] = optimized_result
+
+ # Additional pass to ensure ALL objects have additionalProperties: false
+ def ensure_additional_properties_false(obj: Any) -> None:
+ """Ensure all objects have additionalProperties: false"""
+ if isinstance(obj, dict):
+ # If it's an object type, ensure additionalProperties is false
+ if obj.get('type') == 'object':
+ obj['additionalProperties'] = False
+
+ # Recursively apply to all values
+ for value in obj.values():
+ if isinstance(value, (dict, list)):
+ ensure_additional_properties_false(value)
+ elif isinstance(obj, list):
+ for item in obj:
+ if isinstance(item, (dict, list)):
+ ensure_additional_properties_false(item)
+
+ ensure_additional_properties_false(optimized_schema)
+ SchemaOptimizer._make_strict_compatible(optimized_schema)
+
+ return optimized_schema
+
+ @staticmethod
+ def _make_strict_compatible(schema: dict[str, Any] | list[Any]) -> None:
+ """Ensure all properties are required for OpenAI strict mode"""
+ if isinstance(schema, dict):
+ # First recursively apply to nested objects
+ for key, value in schema.items():
+ if isinstance(value, (dict, list)) and key != 'required':
+ SchemaOptimizer._make_strict_compatible(value)
+
+ # Then update required for this level
+ if 'properties' in schema and 'type' in schema and schema['type'] == 'object':
+ # Add all properties to required array
+ all_props = list(schema['properties'].keys())
+ schema['required'] = all_props # Set all properties as required
+
+ elif isinstance(schema, list):
+ for item in schema:
+ SchemaOptimizer._make_strict_compatible(item)
diff --git a/browser_use/llm/utils.py b/browser_use/llm/utils.py
deleted file mode 100644
index 627ef5723..000000000
--- a/browser_use/llm/utils.py
+++ /dev/null
@@ -1,141 +0,0 @@
-"""
-Utilities for creating optimized Pydantic schemas for LLM usage.
-"""
-
-from typing import Any
-
-from pydantic import BaseModel
-
-
-def create_optimized_json_schema(model: type[BaseModel]) -> dict[str, Any]:
- """
- Create the most optimized schema by flattening all $ref/$defs while preserving
- FULL descriptions and ALL action definitions. Also ensures OpenAI strict mode compatibility.
-
- Args:
- model: The Pydantic model to optimize
-
- Returns:
- Optimized schema with all $refs resolved and strict mode compatibility
- """
- # Generate original schema
- original_schema = model.model_json_schema()
-
- # Extract $defs for reference resolution, then flatten everything
- defs_lookup = original_schema.get('$defs', {})
-
- def optimize_schema(obj: Any, defs_lookup: dict[str, Any] | None = None) -> Any:
- """Apply all optimization techniques including flattening all $ref/$defs"""
- if isinstance(obj, dict):
- optimized: dict[str, Any] = {}
-
- # Skip unnecessary fields AND $defs (we'll inline everything)
- skip_fields = ['additionalProperties', '$defs']
-
- for key, value in obj.items():
- if key in skip_fields:
- continue
-
- # Skip titles completely
- if key == 'title':
- continue
-
- # Preserve FULL descriptions without truncation
- elif key == 'description':
- optimized[key] = value
-
- # Handle type field
- elif key == 'type':
- optimized[key] = value
-
- # FLATTEN: Resolve $ref by inlining the actual definition
- elif key == '$ref' and defs_lookup:
- ref_path = value.split('/')[-1] # Get the definition name from "#/$defs/SomeName"
- if ref_path in defs_lookup:
- # Get the referenced definition and flatten it
- referenced_def = defs_lookup[ref_path]
- flattened_ref = optimize_schema(referenced_def, defs_lookup)
-
- # IMPORTANT: Preserve any description that was alongside the $ref
- if isinstance(obj, dict) and 'description' in obj:
- if isinstance(flattened_ref, dict):
- flattened_ref = flattened_ref.copy()
- flattened_ref['description'] = obj['description']
-
- return flattened_ref
-
- # Keep all anyOf structures (action unions) and resolve any $refs within
- elif key == 'anyOf' and isinstance(value, list):
- optimized[key] = [optimize_schema(item, defs_lookup) for item in value]
-
- # Recursively optimize nested structures
- elif key in ['properties', 'items']:
- optimized[key] = optimize_schema(value, defs_lookup)
-
- # Keep essential validation fields
- elif key in ['type', 'required', 'minimum', 'maximum', 'minItems', 'maxItems', 'pattern', 'default']:
- optimized[key] = value if not isinstance(value, (dict, list)) else optimize_schema(value, defs_lookup)
-
- # Recursively process all other fields
- else:
- optimized[key] = optimize_schema(value, defs_lookup) if isinstance(value, (dict, list)) else value
-
- # CRITICAL: Add additionalProperties: false to ALL objects for OpenAI strict mode
- if optimized.get('type') == 'object':
- optimized['additionalProperties'] = False
-
- return optimized
-
- elif isinstance(obj, list):
- return [optimize_schema(item, defs_lookup) for item in obj]
- return obj
-
- # Create optimized schema with flattening
- optimized_result = optimize_schema(original_schema, defs_lookup)
-
- # Ensure we have a dictionary (should always be the case for schema root)
- if not isinstance(optimized_result, dict):
- raise ValueError('Optimized schema result is not a dictionary')
-
- optimized_schema: dict[str, Any] = optimized_result
-
- # Additional pass to ensure ALL objects have additionalProperties: false
- def ensure_additional_properties_false(obj: Any) -> None:
- """Ensure all objects have additionalProperties: false"""
- if isinstance(obj, dict):
- # If it's an object type, ensure additionalProperties is false
- if obj.get('type') == 'object':
- obj['additionalProperties'] = False
-
- # Recursively apply to all values
- for value in obj.values():
- if isinstance(value, (dict, list)):
- ensure_additional_properties_false(value)
- elif isinstance(obj, list):
- for item in obj:
- if isinstance(item, (dict, list)):
- ensure_additional_properties_false(item)
-
- ensure_additional_properties_false(optimized_schema)
- _make_strict_compatible(optimized_schema)
-
- return optimized_schema
-
-
-def _make_strict_compatible(schema: dict[str, Any] | list[Any]) -> None:
- """Ensure all properties are required for OpenAI strict mode"""
- if isinstance(schema, dict):
- # First recursively apply to nested objects
- for key, value in schema.items():
- if isinstance(value, (dict, list)) and key != 'required':
- _make_strict_compatible(value)
-
- # Then update required for this level
- if 'properties' in schema and 'type' in schema and schema['type'] == 'object':
- # Add all properties to required array
- all_props = list(schema['properties'].keys())
- schema['required'] = all_props # Set all properties as required
-
- elif isinstance(schema, list):
- for item in schema:
- _make_strict_compatible(item)