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
implemented proper functions for reducing token count in json schema
Gregor Žunič8635ccbdec50
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 830e78572..2caf88d46 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -209,80 +209,6 @@ class AgentOutput(BaseModel):model_.__doc__ = 'AgentOutput model with custom actions'return model_- @staticmethod- def create_ultra_compact_schema(- custom_actions: type[ActionModel], keep_titles: bool = True, keep_descriptions: bool = True, max_desc_length: int = 40- ) -> dict:- """Create compact JSON schema while preserving ALL action definitions.-- Args:- custom_actions: The action model type to include- keep_titles: Whether to preserve title fields- keep_descriptions: Whether to preserve description fields- max_desc_length: Maximum description length before truncation-- Returns:- Compact JSON schema dict with all action definitions preserved- """- # Create the full model first- model_ = AgentOutput.type_with_custom_actions(custom_actions)- original_schema = model_.model_json_schema()-- def compact_minimize(obj):- """Recursively minimize schema while preserving ALL action definitions"""- if isinstance(obj, dict):- filtered = {}-- # Only remove truly unnecessary fields - KEEP $defs for action definitions- skip_fields = ['additionalProperties']-- for k, v in obj.items():- if k in skip_fields:- continue-- if k == 'title' and keep_titles:- # Keep titles but truncate if very long- title = str(v)- filtered[k] = title[:30] + '...' if len(title) > 30 else title-- elif k == 'description' and keep_descriptions:- # Keep descriptions but truncate- desc = str(v)- filtered[k] = desc[: max_desc_length - 3] + '...' if len(desc) > max_desc_length else desc-- elif k == '$defs':- # PRESERVE $defs - this contains all action definitions- filtered[k] = compact_minimize(v)-- elif k == '$ref':- # PRESERVE $ref - needed to reference action definitions- filtered[k] = v-- elif k == 'anyOf' and isinstance(v, list):- # Keep all anyOf items including $ref- filtered[k] = [compact_minimize(item) for item in v]-- elif k in ['properties', 'items']:- filtered[k] = compact_minimize(v)-- elif k in ['type', 'required', 'minimum', 'maximum', 'minItems', 'maxItems', 'pattern', 'default']:- # Keep essential validation fields- filtered[k] = v if not isinstance(v, (dict, list)) else compact_minimize(v)-- else:- # Recursively process other fields- filtered[k] = compact_minimize(v) if isinstance(v, (dict, list)) else v-- return filtered-- elif isinstance(obj, list):- return [compact_minimize(item) for item in obj]- return obj-- result = compact_minimize(original_schema)- # Ensure we return a dict (original_schema is always a dict)- return result if isinstance(result, dict) else {}-class AgentHistory(BaseModel):"""History item for agent actions"""diff --git a/browser_use/controller/tests/test_custom_structured_ouput.py b/browser_use/controller/tests/test_custom_structured_ouput.pyindex 69a883302..4ab432f2b 100644--- a/browser_use/controller/tests/test_custom_structured_ouput.py+++ b/browser_use/controller/tests/test_custom_structured_ouput.py@@ -1,133 +1,90 @@import json+import osimport tiktokenfrom browser_use.agent.views import AgentOutputfrom browser_use.controller.service import Controller+from browser_use.llm.utils import create_optimized_json_schema-def create_maximum_optimized_schema():- """Create the most optimized schema by flattening all $ref/$defs while preserving FULL descriptions and ALL action definitions"""+def test_optimized_schema():+ """Test the optimized schema generation and save to file."""- # 1. Create controller and get all registered actions+ # Create controller and get all registered actionscontroller = Controller()ActionModel = controller.registry.create_action_model()- # 2. Generate original schema+ # Create the agent output model with custom actionsagent_output_model = AgentOutput.type_with_custom_actions(ActionModel)- original_schema = agent_output_model.model_json_schema()-- # 3. Extract $defs for reference resolution, then flatten everything- defs_lookup = original_schema.get('$defs', {})-- def optimize_schema(obj, defs_lookup=None):- """Apply all optimization techniques including flattening all $ref/$defs and preserving full descriptions"""- if isinstance(obj, dict):- optimized = {}-- # 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-- # Add additionalProperties: false for object types (tighten unknown keys)- elif key == 'type' and value == 'object':- optimized[key] = value- # Add additionalProperties: false to prevent stray fields- if 'additionalProperties' not in obj:- optimized['additionalProperties'] = False-- # 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)+ # Get original schema for comparison+ original_schema = agent_output_model.model_json_schema()- # 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)+ # Create the optimized schema+ optimized_schema = create_optimized_json_schema(agent_output_model)- # Recursively process all other fields- else:- optimized[key] = optimize_schema(value, defs_lookup) if isinstance(value, (dict, list)) else value+ # Create tmp directory if it doesn't exist+ os.makedirs('./tmp', exist_ok=True)- return optimized+ # Save optimized schema+ with open('./tmp/optimized_schema.json', 'w') as f:+ json.dump(optimized_schema, f, separators=(',', ':'), indent=2)- elif isinstance(obj, list):- return [optimize_schema(item, defs_lookup) for item in obj]- return obj+ print('✅ Optimized schema generated and saved to ./tmp/optimized_schema.json')- # 4. Create optimized schema with flattening- optimized_schema = optimize_schema(original_schema, defs_lookup)+ # Compare token counts of both+ try:+ enc = tiktoken.encoding_for_model('gpt-4o')+ except KeyError:+ enc = tiktoken.get_encoding('cl100k_base')- # 5. Calculate token counts- enc = tiktoken.encoding_for_model('gpt-4o')original_tokens = len(enc.encode(json.dumps(original_schema)))optimized_tokens = len(enc.encode(json.dumps(optimized_schema, separators=(',', ':'))))- # 6. Verify all action definitions preserved (now flattened/inlined)- original_actions = len(original_schema.get('$defs', {}) if isinstance(original_schema, dict) else {})- # Count anyOf items in optimized schema as these are the flattened action definitions- optimized_actions = 0- if isinstance(optimized_schema, dict) and 'properties' in optimized_schema:- action_prop = optimized_schema['properties'].get('action', {})- if 'items' in action_prop and 'anyOf' in action_prop['items']:- optimized_actions = len(action_prop['items']['anyOf'])+ savings = original_tokens - optimized_tokens+ savings_percentage = (savings / original_tokens * 100) if original_tokens > 0 else 0- # 7. Save both schemas- with open('./tmp/original_schema.json', 'w') as f:- json.dump(original_schema, f)+ print('\n📊 Token Count Comparison:')+ print(f' Original schema: {original_tokens:,} tokens')+ print(f' Optimized schema: {optimized_tokens:,} tokens')+ print(f' Token savings: {savings:,} tokens ({savings_percentage:.1f}% reduction)')- with open('./tmp/optimized_schema.json', 'w') as f:- json.dump(optimized_schema, f, separators=(',', ':'), indent=2)+ # Count tokens per action in optimized schema+ print('\n🔍 Tokens per Action in Optimized Schema:')- # 8. Print results- print('📊 Schema Optimization Results (Flattened):')- print(f' Original: {original_tokens:,} tokens')- print(f' Flattened: {optimized_tokens:,} tokens')- print(- f' Reduction: {original_tokens - optimized_tokens:,} tokens ({((original_tokens - optimized_tokens) / original_tokens * 100):.1f}%)'- )- print(f' Action definitions: {optimized_actions}/{original_actions} flattened ✅')- print(' Titles removed: ✅')- print(' FULL descriptions preserved: ✅ (action descriptions now included)')- print(' $defs removed: ✅')- print(' $refs resolved: ✅')- print('')- print('💾 Files saved:')- print(' Original: ./tmp/original_schema.json')- print(' Flattened: ./tmp/optimized_schema.json')-- return optimized_schema+ if 'properties' in optimized_schema and 'action' in optimized_schema['properties']:+ action_prop = optimized_schema['properties']['action']+ if 'items' in action_prop and 'anyOf' in action_prop['items']:+ actions = action_prop['items']['anyOf']++ total_action_tokens = 0+ for i, action in enumerate(actions):+ action_json = json.dumps(action, separators=(',', ':'))+ action_tokens = len(enc.encode(action_json))+ total_action_tokens += action_tokens++ # Try to get action name from the schema+ action_name = 'Unknown'+ if 'properties' in action:+ # Get the first property that's not common ones like 'index', 'reasoning'+ for prop_name in action['properties'].keys():+ if prop_name not in ['index', 'reasoning']:+ action_name = prop_name+ break++ print(f' Action {i + 1} ({action_name}): {action_tokens:,} tokens')++ print('\n📈 Summary:')+ print(f' Total actions: {len(actions)}')+ print(f' Total action tokens: {total_action_tokens:,} tokens')+ print(f' Average tokens per action: {total_action_tokens // len(actions):,} tokens')+ print(f' Action tokens as % of total: {(total_action_tokens / optimized_tokens * 100):.1f}%')+ else:+ print(' No actions found in expected schema structure')+ else:+ print(' No action property found in optimized schema')if __name__ == '__main__':- create_maximum_optimized_schema()+ test_optimized_schema()diff --git a/browser_use/llm/utils.py b/browser_use/llm/utils.pynew file mode 100644index 000000000..b23f6a9af--- /dev/null+++ b/browser_use/llm/utils.py@@ -0,0 +1,118 @@+"""+Utilities for creating optimized Pydantic schemas for LLM usage.+"""++from typing import Any, cast++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, defs_lookup=None):+ """Apply all optimization techniques including flattening all $ref/$defs"""+ if isinstance(obj, dict):+ optimized = {}++ # 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++ # Add additionalProperties: false for object types (tighten unknown keys)+ elif key == 'type' and value == 'object':+ optimized[key] = value+ # Add additionalProperties: false to prevent stray fields+ if 'additionalProperties' not in obj:+ optimized['additionalProperties'] = False++ # 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++ return optimized++ elif isinstance(obj, list):+ return [optimize_schema(item, defs_lookup) for item in obj]+ return obj++ # Create optimized schema with flattening+ optimized_schema = optimize_schema(original_schema, defs_lookup)++ _make_strict_compatible(optimized_schema)++ # Ensure we return a Dict[str, Any] since original_schema is always a dict+ return cast(dict[str, Any], optimized_schema)+++# Ensure strict mode compatibility: ALL properties must be required+def _make_strict_compatible(schema):+ """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)