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
raise explicit ActionNotFoundError when LLM calls non-existent action
Nick Sweetingd6a8d86f269e
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 4e1075728..8922ff545 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -852,7 +852,12 @@ class Agent(Generic[Context, AgentStructuredOutput]):prefix = f'❌ Result failed {self.state.consecutive_failures + 1}/{self.settings.max_failures} times:\n 'self.state.consecutive_failures += 1- if isinstance(error, (ValidationError, ValueError)):+ from browser_use.agent.views import ActionNotFoundError++ if isinstance(error, ActionNotFoundError):+ # For ActionNotFoundError, the message is already clear and complete+ self.logger.error(f'{prefix}{error_msg}')+ elif isinstance(error, (ValidationError, ValueError)):self.logger.error(f'{prefix}{error_msg}')if 'Max token limit reached' in error_msg:# cut tokens from history@@ -937,18 +942,43 @@ class Agent(Generic[Context, AgentStructuredOutput]):async def get_next_action(self, input_messages: list[BaseMessage]) -> AgentOutput:"""Get next action from LLM based on current state"""- response = await self.llm.ainvoke(input_messages, output_format=self.AgentOutput)- parsed = response.completion-- # 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]+ try:+ response = await self.llm.ainvoke(input_messages, output_format=self.AgentOutput)+ parsed = response.completion++ # 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]++ if not (hasattr(self.state, 'paused') and (self.state.paused or self.state.stopped)):+ log_response(parsed, self.controller.registry.registry, self.logger)++ self._log_next_action_summary(parsed)+ return parsed+ except ValidationError as e:+ # Extract available actions from the registry+ available_actions = list(self.controller.registry.registry.actions.keys())++ # Try to extract the action that was attempted from the error+ attempted_action = None+ error_str = str(e)++ # Look for patterns like {"action_name": {...}} in the error+ import re++ action_pattern = r'\{["\']?(\w+)["\']?\s*:'+ matches = re.findall(action_pattern, error_str)+ if matches:+ # Get the first non-standard field name that might be an action+ for match in matches:+ if match not in ['thinking', 'evaluation_previous_goal', 'memory', 'next_goal', 'action']:+ attempted_action = match+ break- if not (hasattr(self.state, 'paused') and (self.state.paused or self.state.stopped)):- log_response(parsed, self.controller.registry.registry, self.logger)+ # Raise our custom error+ from browser_use.agent.views import ActionNotFoundError- self._log_next_action_summary(parsed)- return parsed+ raise ActionNotFoundError(attempted_action, available_actions) from edef _log_agent_run(self) -> None:"""Log the agent run"""diff --git a/browser_use/agent/views.py b/browser_use/agent/views.pyindex 379dc7486..9843f16d4 100644--- a/browser_use/agent/views.py+++ b/browser_use/agent/views.py@@ -494,6 +494,21 @@ class AgentHistoryList(BaseModel, Generic[AgentStructuredOutput]):return None+class ActionNotFoundError(ValueError):+ """Raised when an unknown action is attempted"""++ def __init__(self, attempted_action: str | None, available_actions: list[str]):+ self.attempted_action = attempted_action+ self.available_actions = sorted(available_actions)++ if attempted_action:+ message = f"Unknown action '{attempted_action}' in model response. Available actions are: {', '.join(self.available_actions)}"+ else:+ message = f'Failed to parse action from model response. Available actions are: {", ".join(self.available_actions)}'++ super().__init__(message)++class AgentError:"""Container for agent error handling"""@@ -505,6 +520,9 @@ class AgentError:def format_error(error: Exception, include_trace: bool = False) -> str:"""Format error message based on error type and optionally include trace"""message = ''+ if isinstance(error, ActionNotFoundError):+ # For ActionNotFoundError, use the message as-is+ return str(error)if isinstance(error, ValidationError):return f'{AgentError.VALIDATION_ERROR}\nDetails: {str(error)}'if isinstance(error, RateLimitError):