Skip to content

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

feat: allow eval script to use any model for BU agent, add vision disabling for XAI models, test all models work in eval script

Alezander9057a69e298d6
diff --git a/browser_use/agent/message_manager/service.py b/browser_use/agent/message_manager/service.py
index 085adc6c3..fcd5125ad 100644
--- a/browser_use/agent/message_manager/service.py
+++ b/browser_use/agent/message_manager/service.py
@@ -72,34 +72,36 @@ class MessageManager:
example_tool_call = AIMessage(
content='',
- tool_calls=[{
- 'name': 'AgentOutput',
- 'args': {
- 'current_state': {
- 'evaluation_previous_goal': """
+ tool_calls=[
+ {
+ 'name': 'AgentOutput',
+ 'args': {
+ 'current_state': {
+ 'evaluation_previous_goal': """
Success - I successfully clicked on the 'Apple' link from the Google Search results page,
which directed me to the 'Apple' company homepage. This is a good start toward finding
the best place to buy a new iPhone as the Apple website often list iPhones for sale.
""".strip(),
- 'memory': """
+ 'memory': """
I searched for 'iPhone retailers' on Google. From the Google Search results page,
I used the 'click_element' tool to click on a element labelled 'Best Buy' but calling
the tool did not direct me to a new page. I then used the 'click_element' tool to click
on a element labelled 'Apple' which redirected me to the 'Apple' company homepage.
Currently at step 3/15.
""".strip(),
- 'next_goal': """
+ 'next_goal': """
Looking at reported structure of the current page, I can see the item '[127]<h3 iPhone/>'
in the content. I think this button will lead to more information and potentially prices
for iPhones. I'll click on the link to 'iPhone' at index [127] using the 'click_element'
tool and hope to see prices on the next page.
""".strip(),
+ },
+ 'action': [{'click_element': {'index': 127}}],
},
- 'action': [{'click_element': {'index': 127}}],
+ 'id': str(self.state.tool_id),
+ 'type': 'tool_call',
},
- 'id': str(self.state.tool_id),
- 'type': 'tool_call',
- },]
+ ],
)
self._add_message_with_tokens(example_tool_call, message_type='init')
self.add_tool_message(content='Browser started', message_type='init')
diff --git a/browser_use/agent/service.py b/browser_use/agent/service.py
index ae4be2c43..f16b9b498 100644
--- a/browser_use/agent/service.py
+++ b/browser_use/agent/service.py
@@ -208,6 +208,13 @@ class Agent(Generic[Context]):
'⚠️ DeepSeek models do not support use_vision=True yet. Setting use_vision_for_planner=False for now...'
)
self.settings.use_vision_for_planner = False
+ # Handle users trying to use use_vision=True with XAI models
+ if 'grok' in self.model_name.lower():
+ logger.warning('⚠️ XAI models do not support use_vision=True yet. Setting use_vision=False for now...')
+ self.settings.use_vision = False
+ if 'grok' in (self.planner_model_name or '').lower():
+ logger.warning('⚠️ XAI models do not support use_vision=True yet. Setting use_vision_for_planner=False for now...')
+ self.settings.use_vision_for_planner = False
logger.info(
f'🧠 Starting an agent with main_model={self.model_name}'
diff --git a/eval/service.py b/eval/service.py
index 688f26f03..94b606a79 100644
--- a/eval/service.py
+++ b/eval/service.py
@@ -4,7 +4,7 @@
# Here is the command to run the evaluation:
-# python eval/service.py --parallel_runs 5 --parallel_evaluations 5 --max-steps 25 --start 0 --end 100
+# python eval/service.py --model gpt-4o --parallel_runs 5 --parallel_evaluations 5 --max-steps 25 --start 0 --end 100
# options:
# --parallel_runs: Number of parallel tasks to run
# --max-steps: Maximum steps per task
@@ -286,15 +286,141 @@ async def Online_Mind2Web_eval_with_retry(task, last_actions, images_path, model
# ==============================================================================================================
import argparse
import json
+import os
from datetime import datetime
from pathlib import Path
from typing import Dict, Optional
from dotenv import load_dotenv
+from langchain_anthropic import ChatAnthropic
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_openai import ChatOpenAI
+from pydantic.types import SecretStr
from browser_use import Agent, Browser, BrowserConfig
+SUPPORTED_MODELS = {
+ # Anthropic
+ 'claude-3.5-sonnet': {
+ 'provider': 'anthropic',
+ 'model_name': 'claude-3-5-sonnet-20240620',
+ 'api_key_env': 'ANTHROPIC_API_KEY',
+ },
+ 'claude-3.5-sonnet-exp': {
+ 'provider': 'anthropic',
+ 'model_name': 'claude-3-5-sonnet-20241022',
+ 'api_key_env': 'ANTHROPIC_API_KEY',
+ },
+ 'claude-3.7-sonnet-exp': {
+ 'provider': 'anthropic',
+ 'model_name': 'claude-3-7-sonnet-20250219',
+ 'api_key_env': 'ANTHROPIC_API_KEY',
+ },
+ # Deepseek (via OpenAI Compatible API)
+ 'deepseek-reasoner': {
+ 'provider': 'openai_compatible',
+ 'model_name': 'deepseek-reasoner',
+ 'base_url': 'https://api.deepseek.com/v1',
+ 'api_key_env': 'DEEPSEEK_API_KEY',
+ },
+ 'deepseek-chat': {
+ 'provider': 'openai_compatible',
+ 'model_name': 'deepseek-chat',
+ 'base_url': 'https://api.deepseek.com/v1',
+ 'api_key_env': 'DEEPSEEK_API_KEY',
+ },
+ # Google
+ 'gemini-1.5-flash': {'provider': 'google', 'model_name': 'gemini-1.5-flash-latest', 'api_key_env': 'GEMINI_API_KEY'},
+ 'gemini-2.0-flash-exp': {'provider': 'google', 'model_name': 'gemini-2.0-flash-exp', 'api_key_env': 'GEMINI_API_KEY'},
+ 'gemini-2.5-pro': {'provider': 'google', 'model_name': 'gemini-2.5-pro-preview-03-25', 'api_key_env': 'GEMINI_API_KEY'},
+ # OpenAI
+ 'gpt-4.1': {'provider': 'openai', 'model_name': 'gpt-4.1-2025-04-14', 'api_key_env': 'OPENAI_API_KEY'},
+ 'gpt-4o': {'provider': 'openai', 'model_name': 'gpt-4o', 'api_key_env': 'OPENAI_API_KEY'},
+ # X.ai (via OpenAI Compatible API)
+ 'grok-2': {
+ 'provider': 'openai_compatible',
+ 'model_name': 'grok-2-1212',
+ 'base_url': 'https://api.x.ai/v1',
+ 'api_key_env': 'XAI_API_KEY',
+ },
+ 'grok-3': {
+ 'provider': 'openai_compatible',
+ 'model_name': 'grok-3-beta',
+ 'base_url': 'https://api.x.ai/v1',
+ 'api_key_env': 'XAI_API_KEY',
+ },
+}
+
+
+def get_llm(model_name: str):
+ """Instantiates the correct LangChain ChatModel based on the model name."""
+ if model_name not in SUPPORTED_MODELS:
+ raise ValueError(f'Unsupported model: {model_name}. Supported models are: {list(SUPPORTED_MODELS.keys())}')
+
+ config = SUPPORTED_MODELS[model_name]
+ provider = config['provider']
+ api_key_env = config.get('api_key_env')
+ api_key = os.getenv(api_key_env) if api_key_env else None
+
+ if not api_key and api_key_env:
+ # Only warn if the specified env var is set but key is missing/empty
+ logger.warning(
+ f'API key environment variable {api_key_env} not found or empty for model {model_name}. Trying without API key if possible.'
+ )
+ api_key = None # Ensure api_key is None if not found
+
+ api_key_secret = SecretStr(api_key) if api_key else None
+
+ if provider == 'openai':
+ kwargs = {
+ 'model': config['model_name'],
+ 'temperature': 0.0,
+ }
+ if api_key_secret:
+ kwargs['api_key'] = api_key_secret
+ return ChatOpenAI(**kwargs)
+ elif provider == 'anthropic':
+ # Note: Anthropic client often uses env var ANTHROPIC_API_KEY directly if api_key=None
+ kwargs = {
+ 'model_name': config['model_name'],
+ 'temperature': 0.0,
+ 'timeout': 100,
+ 'stop': None,
+ }
+ if api_key_secret:
+ kwargs['api_key'] = api_key_secret
+ return ChatAnthropic(**kwargs)
+ elif provider == 'google':
+ # Note: Google client often uses env var GOOGLE_API_KEY directly if api_key=None
+ kwargs = {
+ 'model': config['model_name'],
+ 'temperature': 0.0,
+ }
+ if api_key_secret:
+ kwargs['api_key'] = api_key_secret
+ return ChatGoogleGenerativeAI(**kwargs)
+ elif provider == 'openai_compatible':
+ # Note: OpenAI client often uses env var OPENAI_API_KEY directly if api_key=None and no base_url specified
+ # Providing base_url requires explicitly passing the key for that endpoint.
+ kwargs = {
+ 'model': config['model_name'],
+ 'base_url': config['base_url'],
+ 'temperature': 0.0,
+ }
+ if api_key_secret:
+ kwargs['api_key'] = api_key_secret
+ # Ensure api_key is provided if base_url is set and key exists
+ elif config.get('base_url'):
+ # If base_url is present but key is missing, we might still error depending on the endpoint's auth requirements.
+ # Log a warning here, the constructor will likely raise an error if the key is truly required.
+ logger.warning(
+ f'API key for {model_name} at {config["base_url"]} is missing, but base_url is specified. Authentication may fail.'
+ )
+ return ChatOpenAI(**kwargs)
+ else:
+ raise ValueError(f'Unknown provider: {provider}')
+
class Task:
def __init__(self, task_id, confirmed_task, website, reference_length, level):
@@ -392,16 +518,12 @@ class TaskTracker:
return formatted_result
-async def run_agent_with_tracing(task: Task, browser: Browser | None = None, max_steps: int = 25):
+async def run_agent_with_tracing(task: Task, llm: BaseChatModel, browser: Browser | None = None, max_steps: int = 25):
try:
# Create task tracker
tracker = TaskTracker(task.task_id, task.confirmed_task)
browser = browser or Browser()
- llm = ChatOpenAI(
- model='gpt-4o',
- temperature=0.0,
- )
agent = Agent(task=task.confirmed_task, llm=llm, browser=browser)
@@ -544,6 +666,7 @@ async def evaluate_all_saved_results(args) -> Dict:
async def run_multiple_tasks(
tasks: list[Task],
+ llm: BaseChatModel,
max_parallel_runs: int = 3,
max_parallel_evaluations: int = 5,
max_steps_per_task: int = 25,
@@ -590,7 +713,8 @@ async def run_multiple_tasks(
# Create browser with headless configuration
browserConfig = BrowserConfig(headless=headless)
browser = Browser(config=browserConfig)
- result = await run_agent_with_tracing(task=task, browser=browser, max_steps=max_steps_per_task)
+ # Pass the llm to run_agent_with_tracing
+ result = await run_agent_with_tracing(task=task, llm=llm, browser=browser, max_steps=max_steps_per_task)
logger.info(f'Completed task {task.task_id}')
# Extract relevant information from the agent history
@@ -645,6 +769,10 @@ if __name__ == '__main__':
parser.add_argument('--end', type=int, default=None, help='End index (exclusive)')
parser.add_argument('--headless', action='store_true', help='Run in headless mode')
parser.add_argument('--evaluate-only', action='store_true', help='Only evaluate existing results without running new tasks')
+ # Add model argument
+ parser.add_argument(
+ '--model', type=str, default='gpt-4o', choices=list(SUPPORTED_MODELS.keys()), help='Model to use for the agent'
+ )
args = parser.parse_args()
# Set up logging
@@ -673,9 +801,13 @@ if __name__ == '__main__':
with open('eval/mind2web_tasks.json', 'r') as f:
tasks = [Task(**task) for task in json.load(f)]
+ # Get the selected LLM
+ llm = get_llm(args.model)
+
results = asyncio.run(
run_multiple_tasks(
tasks=tasks,
+ llm=llm, # Pass the instantiated llm
max_parallel_runs=args.parallel_runs,
max_parallel_evaluations=args.parallel_evaluations,
max_steps_per_task=args.max_steps,
diff --git a/examples/models/deepseek.py b/examples/models/deepseek.py
index 072c0a192..eef76c131 100644
--- a/examples/models/deepseek.py
+++ b/examples/models/deepseek.py
@@ -35,4 +35,4 @@ async def run_search():
if __name__ == '__main__':
- asyncio.run(run_search())
\ No newline at end of file
+ asyncio.run(run_search())
diff --git a/examples/use-cases/web_voyager_agent.py b/examples/use-cases/web_voyager_agent.py
index f57638211..ad06a4b66 100644
--- a/examples/use-cases/web_voyager_agent.py
+++ b/examples/use-cases/web_voyager_agent.py
@@ -58,6 +58,7 @@ TASK = """
Find and book a hotel in Paris with suitable accommodations for a family of four (two adults and two children) offering free cancellation for the dates of February 14-21, 2025. on https://www.booking.com/
"""
+
async def main():
agent = Agent(
task=TASK,