Skip to content

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

wip

Gregor Žunič11cef6eb1c61
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index 2caf88d46..830e78572 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -209,6 +209,80 @@ 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.py
new file mode 100644
index 000000000..69a883302
--- /dev/null
+++ b/browser_use/controller/tests/test_custom_structured_ouput.py
@@ -0,0 +1,133 @@
+import json
+
+import tiktoken
+
+from browser_use.agent.views import AgentOutput
+from browser_use.controller.service import Controller
+
+
+def create_maximum_optimized_schema():
+ """Create the most optimized schema by flattening all $ref/$defs while preserving FULL descriptions and ALL action definitions"""
+
+ # 1. Create controller and get all registered actions
+ controller = Controller()
+ ActionModel = controller.registry.create_action_model()
+
+ # 2. Generate original schema
+ agent_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)
+
+ # 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
+
+ # 4. Create optimized schema with flattening
+ optimized_schema = optimize_schema(original_schema, defs_lookup)
+
+ # 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'])
+
+ # 7. Save both schemas
+ with open('./tmp/original_schema.json', 'w') as f:
+ json.dump(original_schema, f)
+
+ with open('./tmp/optimized_schema.json', 'w') as f:
+ json.dump(optimized_schema, f, separators=(',', ':'), indent=2)
+
+ # 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 __name__ == '__main__':
+ create_maximum_optimized_schema()