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
Merge branch 'main' of https://github.com/browser-use/browser-use into ollama-failed-parsing-error
Daniele Roccaforte1c7d543bfd6f
diff --cc browser_use/agent/service.pyindex 13fd367ce,cfe2a5092..a29d341f2--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@@ -449,101 -536,25 +536,54 @@@ class Agent(Generic[Context])else:structured_llm = self.llm.with_structured_output(self.AgentOutput, include_raw=True, method=self.tool_calling_method)response: dict[str, Any] = await structured_llm.ainvoke(input_messages) # type: ignore- parsed: AgentOutput | None = response['parsed']- if not parsed:- try:- parsed_json = extract_json_from_model_output(response["raw"].content)- parsed = self.AgentOutput(**parsed_json)- except:- logger.warning(f'Failed to parse model output: {response["raw"].content} {str(e)}')- raise ValueError('Could not parse response.')-- if parsed is None:- raise ValueError('Could not parse response.')++ # Handle tool call responses+ if response.get('parsing_error') and 'raw' in response:+ raw_msg = response['raw']+ if hasattr(raw_msg, 'tool_calls') and raw_msg.tool_calls:+ # Convert tool calls to AgentOutput format++ tool_call = raw_msg.tool_calls[0] # Take first tool call++ # Create current state+ tool_call_name = tool_call['name']+ tool_call_args = tool_call['args']++ current_state = {+ 'page_summary': 'Processing tool call',+ 'evaluation_previous_goal': 'Executing action',+ 'memory': 'Using tool call',+ 'next_goal': f'Execute {tool_call_name}'+ }++ # Create action from tool call+ action = {tool_call_name: tool_call_args}++ parsed = self.AgentOutput(+ current_state=current_state,+ action=[self.ActionModel(**action)]+ )+ else:+ parsed = None+ else:+ parsed = response['parsed']+- if parsed is None:- raise ValueError('Could not parse response.')-- # cut the number of actions to max_actions_per_step- parsed.action = parsed.action[: self.max_actions_per_step]- self._log_response(parsed)- self.n_steps += 1-- return parsed++ if not parsed:++ try:++ parsed_json = extract_json_from_model_output(response["raw"].content)++ parsed = self.AgentOutput(**parsed_json)++ except:++ logger.warning(f'Failed to parse model output: {response["raw"].content} {str(e)}')++ raise ValueError('Could not parse response.')+- def _log_response(self, response: AgentOutput) -> None:- """Log the model's response"""- if 'Success' in response.current_state.evaluation_previous_goal:- emoji = '👍'- elif 'Failed' in response.current_state.evaluation_previous_goal:- emoji = '⚠'- else:- emoji = '🤷'- logger.debug(f'🤖 {emoji} Page summary: {response.current_state.page_summary}')- logger.info(f'{emoji} Eval: {response.current_state.evaluation_previous_goal}')- logger.info(f'🧠 Memory: {response.current_state.memory}')- logger.info(f'🎯 Next goal: {response.current_state.next_goal}')- for i, action in enumerate(response.action):- logger.info(f'🛠️ Action {i + 1}/{len(response.action)}: {action.model_dump_json(exclude_unset=True)}')-- def _save_conversation(self, input_messages: list[BaseMessage], response: Any) -> None:- """Save conversation history to file if path is specified"""- if not self.save_conversation_path:- return- # create folders if not exists- os.makedirs(os.path.dirname(self.save_conversation_path), exist_ok=True)-- with open(- self.save_conversation_path + f'_{self.n_steps}.txt',- 'w',- encoding=self.save_conversation_path_encoding,- ) as f:- self._write_messages_to_file(f, input_messages)- self._write_response_to_file(f, response)-- def _write_messages_to_file(self, f: Any, messages: list[BaseMessage]) -> None:- """Write messages to conversation file"""- for message in messages:- f.write(f' {message.__class__.__name__} \n')-- if isinstance(message.content, list):- for item in message.content:- if isinstance(item, dict) and item.get('type') == 'text':- f.write(item['text'].strip() + '\n')- elif isinstance(message.content, str):- try:- content = json.loads(message.content)- f.write(json.dumps(content, indent=2) + '\n')- except json.JSONDecodeError:- f.write(message.content.strip() + '\n')+ # cut the number of actions to max_actions_per_step if needed+ if len(parsed.action) > self.settings.max_actions_per_step:+ parsed.action = parsed.action[: self.settings.max_actions_per_step]- f.write('\n')+ log_response(parsed)- def _write_response_to_file(self, f: Any, response: Any) -> None:- """Write model response to conversation file"""- f.write(' RESPONSE\n')- f.write(json.dumps(json.loads(response.model_dump_json(exclude_unset=True)), indent=2))+ return parseddef _log_agent_run(self) -> None:"""Log the agent run"""