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
Implement centralized LLM error handling in utils.py and update agent service to utilize this new functionality, improving error management and code clarity.
Magnus Müller3a9788c1d502
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.pyindex 7f64350a6..0f30191ce 100644--- a/browser_use/agent/service.py+++ b/browser_use/agent/service.py@@ -20,7 +20,6 @@ from dotenv import load_dotenvfrom browser_use.browser.session import DEFAULT_BROWSER_PROFILEload_dotenv()-from langchain_core.language_models.chat_models import BaseChatModelfrom langchain_core.messages import (BaseMessage,@@ -69,7 +68,7 @@ from browser_use.telemetry.service import ProductTelemetryfrom browser_use.telemetry.views import (AgentTelemetryEvent,)-from browser_use.utils import time_execution_async, time_execution_sync+from browser_use.utils import handle_llm_error, time_execution_async, time_execution_synclogger = logging.getLogger(__name__)@@ -1121,15 +1120,7 @@ class Agent(Generic[Context]):parsed: AgentOutput | None = response['parsed']except Exception as e:- logger.error(f'Failed to invoke model: {str(e)}')- # groq parser sometimes fails to parse the response, so we try to parse the raw response- if hasattr(e, 'body') and e.body and 'error' in e.body and 'failed_generation' in e.body['error']:- raw = e.body['error']['failed_generation'] # type: ignore- response = {'raw': raw, 'parsed': None}- parsed = None- logger.debug(f'Failed to do tool call, trying to parse raw response: {raw}')- else:- raise LLMException(401, 'LLM API call failed') from e+ response, raw = handle_llm_error(e)else:try:@@ -1139,14 +1130,7 @@ class Agent(Generic[Context]):)response: dict[str, Any] = await structured_llm.ainvoke(input_messages) # type: ignoreexcept Exception as e:- if hasattr(e, 'body') and e.body and 'error' in e.body and 'failed_generation' in e.body['error']:- raw = e.body['error']['failed_generation'] # type: ignore- response = {'raw': raw, 'parsed': None}- parsed = None- logger.debug(f'Failed to do tool call, trying to parse raw response: {raw}')- else:- logger.error(f'Failed to invoke model: {str(e)}')- raise LLMException(401, 'LLM API call failed') from e+ response, raw = handle_llm_error(e)# Handle tool call responsesif response.get('parsing_error') and 'raw' in response:diff --git a/browser_use/utils.py b/browser_use/utils.pyindex 6d01dc9f3..3617d4ae9 100644--- a/browser_use/utils.py+++ b/browser_use/utils.py@@ -13,6 +13,17 @@ from urllib.parse import urlparselogger = logging.getLogger(__name__)+# Import error types - these may need to be adjusted based on actual import paths+try:+ from openai import BadRequestError as OpenAIBadRequestError+except ImportError:+ OpenAIBadRequestError = None++try:+ from groq import BadRequestError as GroqBadRequestError+except ImportError:+ GroqBadRequestError = None+# Global flag to prevent duplicate exit messages_exiting = False@@ -491,3 +502,61 @@ def merge_dicts(a: dict, b: dict, path: tuple[str, ...] = ()):else:a[key] = b[key]return a+++class LLMException(Exception):+ """Custom exception for LLM-related errors."""++ def __init__(self, code: int, message: str):+ self.code = code+ self.message = message+ super().__init__(message)+++def handle_llm_error(e: Exception) -> tuple[dict[str, Any], Any | None]:+ """+ Handle LLM API errors and extract failed generation data when available.++ Args:+ e: The exception that occurred during LLM API call++ Returns:+ Tuple containing:+ - response: Dict with 'raw' and 'parsed' keys+ - parsed: Parsed data (None if extraction was needed)++ Raises:+ LLMException: If the error is not a recognized type with failed generation data+ """+ # Handle OpenAI BadRequestError with failed_generation+ if (+ OpenAIBadRequestError+ and isinstance(e, OpenAIBadRequestError)+ and hasattr(e, 'body')+ and e.body+ and 'failed_generation' in e.body+ ):+ raw = e.body['failed_generation']+ response = {'raw': raw, 'parsed': None}+ parsed = None+ logger.debug(f'Failed to do tool call, trying to parse raw response: {raw}')+ return response, parsed++ # Handle Groq BadRequestError with failed_generation+ if (+ GroqBadRequestError+ and isinstance(e, GroqBadRequestError)+ and hasattr(e, 'body')+ and e.body+ and 'error' in e.body+ and 'failed_generation' in e.body['error']+ ):+ raw = e.body['error']['failed_generation'] # type: ignore+ response = {'raw': raw, 'parsed': None}+ parsed = None+ logger.debug(f'Failed to do tool call, trying to parse raw response: {raw}')+ return response, parsed++ # If it's not a recognized error type, log and raise+ logger.error(f'Failed to invoke model: {str(e)}')+ raise LLMException(401, 'LLM API call failed') from e