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
Refactor agent service tool calling and message handling
Magnus Müllerbdb59feab26c
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 417508290..e97989b73 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -158,6 +158,9 @@ class Agent(Generic[Context]):planner_interval=planner_interval,)+ # Initialize state+ self.state = injected_agent_state or AgentState()+# Action setupself._setup_action_models()self._set_browser_use_version_and_source()@@ -165,25 +168,18 @@ class Agent(Generic[Context]):# Model setupself._set_model_names()- self.tool_calling_method = self.set_tool_calling_method(self.settings.tool_calling_method)-- # Initialize state- self.state = injected_agent_state or AgentState()# for models without tool calling, add available actions to context- available_actions = controller.registry.get_prompt_description()- if self.model_name == 'deepseek-reasoner' or self.model_name.startswith('deepseek-r1'):- # add to context that we are using deepseek- if message_context:- message_context += f'\n\nAvailable actions: {available_actions}'- else:- message_context = f'Available actions: {available_actions}'+ self.available_actions = self.controller.registry.get_prompt_description()++ self.tool_calling_method = self._set_tool_calling_method()+ self.settings.message_context = self._set_message_context()# Initialize message manager with stateself._message_manager = MessageManager(task=task,system_message=self.settings.system_prompt_class(- available_actions,+ self.available_actions,max_actions_per_step=self.settings.max_actions_per_step,).get_system_message(),settings=MessageManagerSettings(@@ -222,6 +218,14 @@ class Agent(Generic[Context]):if self.settings.save_conversation_path:logger.info(f'Saving conversation to {self.settings.save_conversation_path}')+ def _set_message_context(self) -> str | None:+ if self.tool_calling_method == 'raw':+ if self.settings.message_context:+ self.settings.message_context += f'\n\nAvailable actions: {self.available_actions}'+ else:+ self.settings.message_context = f'Available actions: {self.available_actions}'+ return self.settings.message_context+def _set_browser_use_version_and_source(self) -> None:"""Get the version and source of the browser-use package (git or pip in a nutshell)"""try:@@ -282,9 +286,12 @@ class Agent(Generic[Context]):self.DoneActionModel = self.controller.registry.create_action_model(include_actions=['done'])self.DoneAgentOutput = AgentOutput.type_with_custom_actions(self.DoneActionModel)- def set_tool_calling_method(self, tool_calling_method: Optional[ToolCallingMethod]) -> Optional[ToolCallingMethod]:+ def _set_tool_calling_method(self) -> Optional[ToolCallingMethod]:+ tool_calling_method = self.settings.tool_calling_methodif tool_calling_method == 'auto':- if self.chat_model_library == 'ChatGoogleGenerativeAI':+ if self.model_name == 'deepseek-reasoner' or self.model_name.startswith('deepseek-r1'):+ return 'raw'+ elif self.chat_model_library == 'ChatGoogleGenerativeAI':return Noneelif self.chat_model_library == 'ChatOpenAI':return 'function_calling'@@ -478,20 +485,29 @@ class Agent(Generic[Context]):"""Remove think tags from text"""return re.sub(self.THINK_TAGS, '', text)+ def _convert_input_messages(self, input_messages: list[BaseMessage]) -> list[BaseMessage]:+ """Convert input messages to the correct format"""+ if self.model_name == 'deepseek-reasoner' or self.model_name.startswith('deepseek-r1'):+ return convert_input_messages(input_messages, self.model_name)+ else:+ return input_messages+@time_execution_async('--get_next_action (agent)')async def get_next_action(self, input_messages: list[BaseMessage]) -> AgentOutput:"""Get next action from LLM based on current state"""- if self.model_name == 'deepseek-reasoner' or self.model_name.startswith('deepseek-r1'):- converted_input_messages = convert_input_messages(input_messages, self.model_name)- output = self.llm.invoke(converted_input_messages)- output.content = self._remove_think_tags(str(output.content))+ input_messages = self._convert_input_messages(input_messages)++ if self.tool_calling_method == 'raw':+ output = self.llm.invoke(input_messages)# TODO: currently invoke does not return reasoning_content, we should override invoke+ output.content = self._remove_think_tags(str(output.content))try:parsed_json = extract_json_from_model_output(output.content)parsed = self.AgentOutput(**parsed_json)except (ValueError, ValidationError) as e:logger.warning(f'Failed to parse model output: {output} {str(e)}')raise ValueError('Could not parse response.')+elif self.tool_calling_method is None:structured_llm = self.llm.with_structured_output(self.AgentOutput, include_raw=True)response: dict[str, Any] = await structured_llm.ainvoke(input_messages) # type: ignorediff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 17a6f2493..732ae4f6a 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -22,7 +22,7 @@ from browser_use.dom.history_tree_processor.service import ()from browser_use.dom.views import SelectorMap-ToolCallingMethod = Literal['function_calling', 'auto']+ToolCallingMethod = Literal['function_calling', 'json_mode', 'raw', 'auto']class AgentSettings(BaseModel):