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č0691500c6ae2
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index 7116caf1d..984274169 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -49,6 +49,7 @@ from browser_use.agent.views import (
AgentSettings,
AgentState,
AgentStepInfo,
+ AgentStructuredOutput,
BrowserStateHistory,
StepMetadata,
)
@@ -102,10 +103,11 @@ def log_response(response: AgentOutput, registry=None, logger=None) -> None:
Context = TypeVar('Context')
+
AgentHookFunc = Callable[['Agent'], Awaitable[None]]
-class Agent(Generic[Context]):
+class Agent(Generic[Context, AgentStructuredOutput]):
browser_session: BrowserSession | None = None
_logger: logging.Logger | None = None
@@ -137,6 +139,7 @@ class Agent(Generic[Context]):
) = None,
register_external_agent_status_raise_error_callback: Callable[[], Awaitable[bool]] | None = None,
# Agent settings
+ output_model_schema: type[AgentStructuredOutput] | None = None,
use_vision: bool = True,
use_vision_for_planner: bool = False,
save_conversation_path: str | Path | None = None,
@@ -209,6 +212,12 @@ class Agent(Generic[Context]):
self.controller = (
controller if controller is not None else Controller(display_files_in_done_text=display_files_in_done_text)
)
+
+ # Structured output
+ self.output_model_schema = output_model_schema
+ if self.output_model_schema is not None:
+ self.controller.use_structured_output_action(self.output_model_schema)
+
self.sensitive_data = sensitive_data
self.settings = AgentSettings(
@@ -1078,7 +1087,7 @@ class Agent(Generic[Context]):
max_steps: int = 100,
on_step_start: AgentHookFunc | None = None,
on_step_end: AgentHookFunc | None = None,
- ) -> AgentHistoryList:
+ ) -> AgentHistoryList[AgentStructuredOutput]:
"""Execute the task with maximum number of steps"""
loop = asyncio.get_event_loop()
@@ -1187,6 +1196,9 @@ class Agent(Generic[Context]):
self.logger.info(f'❌ {agent_run_error}')
+ if self.state.history.structured_output() is not None and self.output_model_schema is not None:
+ self.state.history._output_model_schema = self.output_model_schema
+
return self.state.history
except KeyboardInterrupt:
diff --git a/browser_use/agent/views.py b/browser_use/agent/views.py
index 2caf88d46..80d5403c3 100644
--- a/browser_use/agent/views.py
+++ b/browser_use/agent/views.py
@@ -4,10 +4,11 @@ import json
import traceback
from dataclasses import dataclass
from pathlib import Path
-from typing import Any
+from typing import Any, Generic
from openai import RateLimitError
from pydantic import BaseModel, ConfigDict, Field, ValidationError, create_model, model_validator
+from typing_extensions import TypeVar
from uuid_extensions import uuid7str
from browser_use.agent.message_manager.views import MessageManagerState
@@ -257,11 +258,16 @@ class AgentHistory(BaseModel):
}
-class AgentHistoryList(BaseModel):
+AgentStructuredOutput = TypeVar('AgentStructuredOutput', bound=BaseModel)
+
+
+class AgentHistoryList(BaseModel, Generic[AgentStructuredOutput]):
"""List of AgentHistory messages, i.e. the history of the agent's actions and thoughts."""
history: list[AgentHistory]
+ _output_model_schema: type[AgentStructuredOutput] | None = None
+
def total_duration_seconds(self) -> float:
"""Get total duration of all steps in seconds"""
total = 0.0
@@ -456,6 +462,18 @@ class AgentHistoryList(BaseModel):
"""Get the number of steps in the history"""
return len(self.history)
+ def structured_output(self) -> AgentStructuredOutput | None:
+ """Get the structured output from the history
+
+ Returns:
+ The structured output if both final_result and _output_model_schema are available,
+ otherwise None
+ """
+ if self.final_result() is not None and self._output_model_schema is not None:
+ return self._output_model_schema.model_validate_strings(self.final_result())
+
+ return None
+
class AgentError:
"""Container for agent error handling"""
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index de0973b68..dc0c85fa6 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -23,6 +23,7 @@ from browser_use.controller.views import (
ScrollAction,
SearchGoogleAction,
SendKeysAction,
+ StructuredOutputAction,
SwitchTabAction,
)
from browser_use.filesystem.file_system import FileSystem
@@ -64,12 +65,14 @@ async def retry_async_function(
Context = TypeVar('Context')
+T = TypeVar('T', bound=BaseModel)
+
class Controller(Generic[Context]):
def __init__(
self,
exclude_actions: list[str] = [],
- output_model: type[BaseModel] | None = None,
+ output_model: type[T] | None = None,
display_files_in_done_text: bool = True,
):
self.registry = Registry[Context](exclude_actions)
@@ -77,82 +80,7 @@ class Controller(Generic[Context]):
"""Register all default browser actions"""
- if output_model is not None:
- # Create a new model that extends the output model with success parameter
- class ExtendedOutputModel(BaseModel): # type: ignore
- success: bool = True
- data: output_model # type: ignore
-
- # This is for the eval service if we create the basemodel dynamically
- ExtendedOutputModel.model_rebuild()
-
- @self.registry.action(
- 'Complete task - with return text and if the task is finished (success=True) or not yet completely finished (success=False), because last step is reached',
- param_model=ExtendedOutputModel,
- )
- async def done(params: ExtendedOutputModel):
- # Exclude success from the output JSON since it's an internal parameter
- output_dict = params.data.model_dump()
-
- # Enums are not serializable, convert to string
- for key, value in output_dict.items():
- if isinstance(value, enum.Enum):
- output_dict[key] = value.value
-
- return ActionResult(
- is_done=True,
- success=params.success,
- extracted_content=json.dumps(output_dict),
- long_term_memory=f'Task completed. Success Status: {params.success}',
- )
- else:
-
- @self.registry.action(
- 'Complete task - provide a summary of results for the user. Set success=True if task completed successfully, false otherwise. Text should be your response to the user summarizing results. Include files you would like to display to the user in files_to_display.',
- param_model=DoneAction,
- )
- async def done(params: DoneAction, file_system: FileSystem):
- user_message = params.text
-
- len_text = len(params.text)
- len_max_memory = 100
- memory = f'Task completed: {params.success} - {params.text[:len_max_memory]}'
- if len_text > len_max_memory:
- memory += f' - {len_text - len_max_memory} more characters'
-
- attachments = []
- if params.files_to_display:
- if self.display_files_in_done_text:
- file_msg = ''
- for file_name in params.files_to_display:
- if file_name == 'todo.md':
- continue
- file_content = file_system.display_file(file_name)
- if file_content:
- file_msg += f'\n\n{file_name}:\n{file_content}'
- attachments.append(file_name)
- if file_msg:
- user_message += '\n\nAttachments:'
- user_message += file_msg
- else:
- logger.warning('Agent wanted to display files but none were found')
- else:
- for file_name in params.files_to_display:
- if file_name == 'todo.md':
- continue
- file_content = file_system.display_file(file_name)
- if file_content:
- attachments.append(file_name)
-
- attachments = [str(file_system.get_dir() / file_name) for file_name in attachments]
-
- return ActionResult(
- is_done=True,
- success=params.success,
- extracted_content=user_message,
- long_term_memory=memory,
- attachments=attachments,
- )
+ self._register_done_action(output_model)
# Basic Navigation Actions
@self.registry.action(
@@ -968,6 +896,83 @@ Explain the content of the page and that the requested information is not availa
long_term_memory=f"Inputted text '{text}' into cell",
)
+ # Custom done action for structured output
+ def _register_done_action(self, output_model: type[T] | None, display_files_in_done_text: bool = True):
+ if output_model is not None:
+ self.display_files_in_done_text = display_files_in_done_text
+
+ @self.registry.action(
+ 'Complete task - with return text and if the task is finished (success=True) or not yet completely finished (success=False), because last step is reached',
+ param_model=StructuredOutputAction[output_model],
+ )
+ async def done(params: StructuredOutputAction[output_model]):
+ # Exclude success from the output JSON since it's an internal parameter
+ output_dict = params.data.model_dump()
+
+ # Enums are not serializable, convert to string
+ for key, value in output_dict.items():
+ if isinstance(value, enum.Enum):
+ output_dict[key] = value.value
+
+ return ActionResult(
+ is_done=True,
+ success=params.success,
+ extracted_content=json.dumps(output_dict),
+ long_term_memory=f'Task completed. Success Status: {params.success}',
+ )
+
+ else:
+
+ @self.registry.action(
+ 'Complete task - provide a summary of results for the user. Set success=True if task completed successfully, false otherwise. Text should be your response to the user summarizing results. Include files you would like to display to the user in files_to_display.',
+ param_model=DoneAction,
+ )
+ async def done(params: DoneAction, file_system: FileSystem):
+ user_message = params.text
+
+ len_text = len(params.text)
+ len_max_memory = 100
+ memory = f'Task completed: {params.success} - {params.text[:len_max_memory]}'
+ if len_text > len_max_memory:
+ memory += f' - {len_text - len_max_memory} more characters'
+
+ attachments = []
+ if params.files_to_display:
+ if self.display_files_in_done_text:
+ file_msg = ''
+ for file_name in params.files_to_display:
+ if file_name == 'todo.md':
+ continue
+ file_content = file_system.display_file(file_name)
+ if file_content:
+ file_msg += f'\n\n{file_name}:\n{file_content}'
+ attachments.append(file_name)
+ if file_msg:
+ user_message += '\n\nAttachments:'
+ user_message += file_msg
+ else:
+ logger.warning('Agent wanted to display files but none were found')
+ else:
+ for file_name in params.files_to_display:
+ if file_name == 'todo.md':
+ continue
+ file_content = file_system.display_file(file_name)
+ if file_content:
+ attachments.append(file_name)
+
+ attachments = [str(file_system.get_dir() / file_name) for file_name in attachments]
+
+ return ActionResult(
+ is_done=True,
+ success=params.success,
+ extracted_content=user_message,
+ long_term_memory=memory,
+ attachments=attachments,
+ )
+
+ def use_structured_output_action(self, output_model: type[T]):
+ self._register_done_action(output_model)
+
# Register ---------------------------------------------------------------
def action(self, description: str, **kwargs):
diff --git a/browser_use/controller/tests/test_controller_structured_output.py b/browser_use/controller/tests/test_controller_structured_output.py
new file mode 100644
index 000000000..d4661201d
--- /dev/null
+++ b/browser_use/controller/tests/test_controller_structured_output.py
@@ -0,0 +1,46 @@
+import asyncio
+
+from pydantic import BaseModel
+
+from browser_use.agent.service import Agent
+from browser_use.agent.views import AgentOutput
+from browser_use.controller.service import Controller
+from browser_use.llm.openai.chat import ChatOpenAI
+from browser_use.llm.schema import SchemaOptimizer
+
+
+class OutputModel(BaseModel):
+ """Test output model"""
+
+ name: str
+ age: int
+
+
+async def test_optimized_schema():
+ """Test the optimized schema generation and save to file."""
+
+ # Create controller and get all registered actions
+ controller = Controller()
+ ActionModel = controller.registry.create_action_model()
+
+ # Create the agent output model with custom actions
+ agent_output_model = AgentOutput.type_with_custom_actions(ActionModel)
+
+ # Get original schema for comparison
+ original_schema = agent_output_model.model_json_schema()
+
+ # Create the optimized schema
+ optimized_schema = SchemaOptimizer.create_optimized_json_schema(agent_output_model)
+
+ agent = Agent(
+ task='What is the capital of France?',
+ llm=ChatOpenAI(model='gpt-4o'),
+ controller=controller,
+ )
+
+ output = await agent.run()
+ x = output.structured_output
+
+
+if __name__ == '__main__':
+ asyncio.run(test_optimized_schema())
diff --git a/browser_use/controller/views.py b/browser_use/controller/views.py
index 42641352e..73c81ca7e 100644
--- a/browser_use/controller/views.py
+++ b/browser_use/controller/views.py
@@ -1,3 +1,5 @@
+from typing import Generic, TypeVar
+
from pydantic import BaseModel, ConfigDict, Field
@@ -27,6 +29,14 @@ class DoneAction(BaseModel):
files_to_display: list[str] | None = []
+T = TypeVar('T', bound=BaseModel)
+
+
+class StructuredOutputAction(BaseModel, Generic[T]):
+ success: bool = True
+ data: T
+
+
class SwitchTabAction(BaseModel):
page_id: int