Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

Merge branch 'main' into verify_setup_llm

Nick Sweetingf7ece592c97a
diff --cc browser_use/agent/service.py
index 788307316,1ac928202..ab5e1754e
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@@ -59,9 -65,8 +64,8 @@@ from browser_use.telemetry.service impo
from browser_use.telemetry.views import (
AgentTelemetryEvent,
)
-from browser_use.utils import check_env_variables, time_execution_async, time_execution_sync
+from browser_use.utils import time_execution_async, time_execution_sync
- load_dotenv()
logger = logging.getLogger(__name__)
SKIP_LLM_API_KEY_VERIFICATION = os.environ.get('SKIP_LLM_API_KEY_VERIFICATION', 'false').lower()[0] in 'ty1'
@@@ -228,13 -231,16 +232,13 @@@ class Agent(Generic[Context])
f'{" +tools" if self.tool_calling_method == "function_calling" else ""}'
f'{" +rawtools" if self.tool_calling_method == "raw" else ""}'
f'{" +vision" if self.settings.use_vision else ""}'
- f'{" +memory" if self.enable_memory else ""}, '
- f'planner_model={self.planner_model_name}'
+ f'{" +memory" if self.enable_memory else ""}'
+ f' extraction_model={getattr(self.settings.page_extraction_llm, "model_name", None)}'
+ f'{f" planner_model={self.planner_model_name}" if self.planner_model_name else ""}'
f'{" +reasoning" if self.settings.is_planner_reasoning else ""}'
- f'{" +vision" if self.settings.use_vision_for_planner else ""}, '
- f'extraction_model={getattr(self.settings.page_extraction_llm, "model_name", None)} '
+ f'{" +vision" if self.settings.use_vision_for_planner else ""} '
)
- # Verify we can connect to the LLM
- self._verify_llm_connection()
-
# Initialize available actions for system prompt (only non-filtered actions)
# These will be used for the system prompt to maintain caching
self.unfiltered_actions = self.controller.registry.get_prompt_description()
@@@ -394,136 -456,27 +454,152 @@@
self.DoneActionModel = self.controller.registry.create_action_model(include_actions=['done'])
self.DoneAgentOutput = AgentOutput.type_with_custom_actions(self.DoneActionModel)
+ def _test_tool_calling_method(self, method: str) -> bool:
+ """Test if a specific tool calling method works with the current LLM."""
+ try:
+ # Test configuration
+ CAPITAL_QUESTION = 'What is the capital of France? Respond with just the city name in lowercase.'
+ EXPECTED_ANSWER = 'paris'
+
+ class CapitalResponse(BaseModel):
+ """Response model for capital city question"""
+
+ answer: str # The name of the capital city in lowercase
+
+ def is_valid_raw_response(response, expected_answer: str) -> bool:
+ """
+ Cleans and validates a raw JSON response string against an expected answer.
+ """
+ content = getattr(response, 'content', '').strip()
+ logger.debug(f'Raw response content: {content}')
+
+ # Remove surrounding markdown code blocks if present
+ if content.startswith('```json') and content.endswith('```'):
+ content = content[7:-3].strip()
+ elif content.startswith('```') and content.endswith('```'):
+ content = content[3:-3].strip()
+
+ # Attempt to parse and validate the answer
+ try:
+ result = json.loads(content)
+ answer = str(result.get('answer', '')).strip().lower().strip(' .')
+
+ if expected_answer.lower() not in answer:
+ logger.debug(f"Validation failed: expected '{expected_answer}', got '{answer}'")
+ return False
+
+ return True
+
+ except (json.JSONDecodeError, AttributeError, TypeError) as e:
+ logger.debug(f'Failed to parse JSON content: {e}')
+ return False
+
+ if method == 'raw':
+ # For raw mode, test JSON response format
+ test_prompt = f"""{CAPITAL_QUESTION}
+ Respond with a JSON object like: {{"answer": "city_name_in_lowercase"}}"""
+
+ response = self.llm.invoke([test_prompt])
+ # Basic validation of response
+ if not response or not hasattr(response, 'content'):
+ return False
+
+ if not is_valid_raw_response(response, EXPECTED_ANSWER):
+ return False
+ return True
-
+ else:
+ # For other methods, try to use structured output
+ structured_llm = self.llm.with_structured_output(CapitalResponse, include_raw=True, method=method)
+ response = structured_llm.invoke([HumanMessage(content=CAPITAL_QUESTION)])
+
+ if not response:
+ logger.debug(f'Method {method} failed validation: empty response')
+ return False
+
+ def extract_parsed(response: Any) -> CapitalResponse | None:
+ if isinstance(response, dict):
+ return response.get('parsed')
+ return getattr(response, 'parsed', None)
+
+ parsed = extract_parsed(response)
+
+ if not isinstance(parsed, CapitalResponse):
+ logger.debug(f'Method {method} failed validation: parsed is not CapitalResponse')
+ return False
+
+ if EXPECTED_ANSWER not in parsed.answer.lower():
+ logger.debug(f'Method {method} failed validation: expected answer not in response')
+ return False
+ return True
+
+ except Exception as e:
+ logger.debug(f"Tool calling method '{method}' test failed: {str(e)}")
+ return False
+
+ def _detect_best_tool_calling_method(self) -> str | None:
+ """Detect the best supported tool calling method by testing each one."""
+ # Order of preference for tool calling methods
+ methods_to_try = [
+ 'function_calling', # Most capable and efficient
+ 'tools', # Works with some models that don't support function_calling
+ 'json_mode', # More basic structured output
+ 'raw', # Fallback - no tool calling support
+ ]
+
+ for method in methods_to_try:
+ logger.debug(f'Testing tool calling method: {method}')
+ if self._test_tool_calling_method(method):
+ # if we found the method which means api is verified.
+ self.llm._verified_api_keys = True
+ logger.info(f'Selected tool calling method: {method}')
+ return method
+
+ # If we get here, no methods worked
+ raise ConnectionError('Failed to connect to LLM. Please check your API key and network connection.')
+
- def _set_tool_calling_method(self) -> str | None:
+ def _set_tool_calling_method(self) -> ToolCallingMethod | None:
- tool_calling_method = self.settings.tool_calling_method
- if tool_calling_method == 'auto':
- if is_model_without_tool_support(self.model_name):
- return 'raw'
- elif self.chat_model_library == 'ChatGoogleGenerativeAI':
- return None
- elif self.chat_model_library == 'ChatOpenAI':
- return 'function_calling'
- elif self.chat_model_library == 'AzureChatOpenAI':
- # Azure OpenAI API requires 'tools' parameter for GPT-4
- # The error 'content must be either a string or an array' occurs when
- # the API expects a tools array but gets something else
- if 'gpt-4-' in self.model_name.lower():
- return 'tools'
+ """Determine the best tool calling method to use with the current LLM."""
- # If a specific method is set, use it
++
++ # old hardcoded logic
++ # if is_model_without_tool_support(self.model_name):
++ # return 'raw'
++ # elif self.chat_model_library == 'ChatGoogleGenerativeAI':
++ # return None
++ # elif self.chat_model_library == 'ChatOpenAI':
++ # return 'function_calling'
++ # elif self.chat_model_library == 'AzureChatOpenAI':
++ # # Azure OpenAI API requires 'tools' parameter for GPT-4
++ # # The error 'content must be either a string or an array' occurs when
++ # # the API expects a tools array but gets something else
++ # if 'gpt-4-' in self.model_name.lower():
++ # return 'tools'
++ # else:
++ # return 'function_calling'
++
++ # If a specific method is set, use it
+ if self.settings.tool_calling_method != 'auto':
+ if not self._test_tool_calling_method(self.settings.tool_calling_method):
+ if self.settings.tool_calling_method == 'raw':
+ # if raw failed means error in API key or network connection
+ raise ConnectionError('Failed to connect to LLM. Please check your API key and network connection.')
else:
- return 'function_calling'
- else:
- return None
- else:
- return tool_calling_method
+ raise RuntimeError(
+ f"Configured tool calling method '{self.settings.tool_calling_method}' "
+ 'is not supported by the current LLM.'
+ )
+ return self.settings.tool_calling_method
+
+ # For models known to not support tool calling, use raw mode
+ if is_model_without_tool_support(self.model_name):
+ fallback_method = 'raw'
+ if not self._test_tool_calling_method(fallback_method):
+ # if raw failed means error in API key or network connection
+ raise ConnectionError('Failed to connect to LLM. Please check your API key and network connection.')
+ logger.debug('Model is known to not support tool calling, using raw mode')
+ return fallback_method
+
+ # Auto-detect the best method
+ return self._detect_best_tool_calling_method()
def add_new_task(self, new_task: str) -> None:
self._message_manager.add_new_task(new_task)