Skip to content

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

include kimi-2

Magnus Müller3cf6e1046b38
diff --git a/browser_use/llm/openai/chat.py b/browser_use/llm/openai/chat.py
index ecf05b654..7cddca24b 100644
--- a/browser_use/llm/openai/chat.py
+++ b/browser_use/llm/openai/chat.py
@@ -42,6 +42,12 @@ class ChatOpenAI(BaseChatModel):
top_p: float | None = None
add_schema_to_system_prompt: bool = False # Add JSON schema to system prompt instead of using response_format
dont_force_structured_output: bool = False # If True, the model will not be forced to output a structured output
+ remove_min_items_from_schema: bool = (
+ False # If True, remove minItems from JSON schema (for compatibility with some providers)
+ )
+ remove_defaults_from_schema: bool = (
+ False # If True, remove default values from JSON schema (for compatibility with some providers)
+ )
# Client initialization parameters
api_key: str | None = None
@@ -206,7 +212,11 @@ class ChatOpenAI(BaseChatModel):
response_format: JSONSchema = {
'name': 'agent_output',
'strict': True,
- 'schema': SchemaOptimizer.create_optimized_json_schema(output_format),
+ 'schema': SchemaOptimizer.create_optimized_json_schema(
+ output_format,
+ remove_min_items=self.remove_min_items_from_schema,
+ remove_defaults=self.remove_defaults_from_schema,
+ ),
}
# Add JSON schema to system prompt if requested
diff --git a/browser_use/llm/schema.py b/browser_use/llm/schema.py
index 8467e09d4..5477cc4b7 100644
--- a/browser_use/llm/schema.py
+++ b/browser_use/llm/schema.py
@@ -9,13 +9,20 @@ from pydantic import BaseModel
class SchemaOptimizer:
@staticmethod
- def create_optimized_json_schema(model: type[BaseModel]) -> dict[str, Any]:
+ def create_optimized_json_schema(
+ model: type[BaseModel],
+ *,
+ remove_min_items: bool = False,
+ remove_defaults: bool = False,
+ ) -> 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
+ remove_min_items: If True, remove minItems from the schema
+ remove_defaults: If True, remove default values from the schema
Returns:
Optimized schema with all $refs resolved and strict mode compatibility
@@ -26,12 +33,9 @@ class SchemaOptimizer:
# 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,
- *,
- in_properties: bool = False, # NEW: track context
- ) -> Any:
+ # Create optimized schema with flattening
+ # Pass flags to optimize_schema via closure
+ def optimize_schema(obj: Any, defs_lookup: dict[str, Any] | None = None, *, in_properties: bool = False) -> Any:
"""Apply all optimization techniques including flattening all $ref/$defs"""
if isinstance(obj, dict):
optimized: dict[str, Any] = {}
@@ -65,6 +69,12 @@ class SchemaOptimizer:
referenced_def = defs_lookup[ref_path]
flattened_ref = optimize_schema(referenced_def, defs_lookup)
+ # Skip minItems/min_items and default if requested (check BEFORE processing)
+ elif key in ('minItems', 'min_items') and remove_min_items:
+ continue # Skip minItems/min_items
+ elif key == 'default' and remove_defaults:
+ continue # Skip default values
+
# 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]
@@ -78,7 +88,17 @@ class SchemaOptimizer:
)
# Keep essential validation fields
- elif key in ['type', 'required', 'minimum', 'maximum', 'minItems', 'maxItems', 'pattern', 'default']:
+ elif key in [
+ 'type',
+ 'required',
+ 'minimum',
+ 'maximum',
+ 'minItems',
+ 'min_items',
+ 'maxItems',
+ 'pattern',
+ 'default',
+ ]:
optimized[key] = value if not isinstance(value, (dict, list)) else optimize_schema(value, defs_lookup)
# Recursively process all other fields
@@ -111,7 +131,6 @@ class SchemaOptimizer:
return [optimize_schema(item, defs_lookup, in_properties=in_properties) 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)
@@ -140,6 +159,29 @@ class SchemaOptimizer:
ensure_additional_properties_false(optimized_schema)
SchemaOptimizer._make_strict_compatible(optimized_schema)
+ # Final pass to remove minItems/min_items and default values if requested
+ if remove_min_items or remove_defaults:
+
+ def remove_forbidden_fields(obj: Any) -> None:
+ """Recursively remove minItems/min_items and default values"""
+ if isinstance(obj, dict):
+ # Remove forbidden keys
+ if remove_min_items:
+ obj.pop('minItems', None)
+ obj.pop('min_items', None)
+ if remove_defaults:
+ obj.pop('default', None)
+ # Recursively process all values
+ for value in obj.values():
+ if isinstance(value, (dict, list)):
+ remove_forbidden_fields(value)
+ elif isinstance(obj, list):
+ for item in obj:
+ if isinstance(item, (dict, list)):
+ remove_forbidden_fields(item)
+
+ remove_forbidden_fields(optimized_schema)
+
return optimized_schema
@staticmethod
diff --git a/examples/models/moonshot.py b/examples/models/moonshot.py
new file mode 100644
index 000000000..b88842c89
--- /dev/null
+++ b/examples/models/moonshot.py
@@ -0,0 +1,38 @@
+import asyncio
+import os
+
+from dotenv import load_dotenv
+
+from browser_use import Agent, ChatOpenAI
+
+load_dotenv()
+
+# Get API key from environment variable
+api_key = os.getenv('MOONSHOT_API_KEY')
+if api_key is None:
+ print('Make sure you have MOONSHOT_API_KEY set in your .env file')
+ print('Get your API key from https://platform.moonshot.ai/console/api-keys ')
+ exit(1)
+
+# Configure Moonshot AI model
+llm = ChatOpenAI(
+ model='kimi-k2-thinking',
+ base_url='https://api.moonshot.ai/v1',
+ api_key=api_key,
+ add_schema_to_system_prompt=True,
+ remove_min_items_from_schema=True, # Moonshot doesn't support minItems in JSON schema
+ remove_defaults_from_schema=True, # Moonshot doesn't allow default values with anyOf
+)
+
+
+async def main():
+ agent = Agent(
+ task='Search for the latest news about AI and summarize the top 3 articles',
+ llm=llm,
+ flash_mode=True,
+ )
+ await agent.run()
+
+
+if __name__ == '__main__':
+ asyncio.run(main())