Skip to content

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

refactor eval script into smaller files and use relative imports for clean code

Alezander97c39427f1f2c
diff --git a/eval/browsers.py b/eval/browsers.py
new file mode 100644
index 000000000..1cd77670f
--- /dev/null
+++ b/eval/browsers.py
@@ -0,0 +1,269 @@
+# pyright: reportMissingImports=false
+
+import asyncio
+import json
+import logging
+import os
+from pathlib import Path
+
+import requests
+
+from browser_use import BrowserProfile, BrowserSession
+from eval.types import Task
+
+logger = logging.getLogger(__name__)
+
+# Check for Anchor Browser API key
+ANCHOR_BROWSER_API_KEY = os.getenv('ANCHOR_BROWSER_API_KEY')
+if ANCHOR_BROWSER_API_KEY:
+ logger.info('ANCHOR_BROWSER_API_KEY is set. Tasks can use Anchor Browser.')
+else:
+ logger.warning('ANCHOR_BROWSER_API_KEY is not set. Anchor Browser will not be available.')
+
+# Check for Brightdata CDP URL
+BRIGHTDATA_CDP_URL = os.getenv('BRIGHTDATA_CDP_URL')
+if BRIGHTDATA_CDP_URL:
+ logger.info('BRIGHTDATA_CDP_URL is set. Tasks can use Brightdata browser.')
+else:
+ logger.warning('BRIGHTDATA_CDP_URL is not set. Brightdata browser will not be available.')
+
+# Check for Browserbase API key
+BROWSERBASE_API_KEY = os.getenv('BROWSERBASE_API_KEY')
+BROWSERBASE_PROJECT_ID = os.getenv('BROWSERBASE_PROJECT_ID')
+if BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID:
+ logger.info('BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID are set. Tasks can use Browserbase.')
+else:
+ logger.warning('BROWSERBASE_API_KEY or BROWSERBASE_PROJECT_ID are not set. Browserbase will not be available.')
+
+# Check for Hyperbrowser API key
+HYPERBROWSER_API_KEY = os.getenv('HYPERBROWSER_API_KEY')
+if HYPERBROWSER_API_KEY:
+ logger.info('HYPERBROWSER_API_KEY is set. Tasks can use Hyperbrowser.')
+else:
+ logger.warning('HYPERBROWSER_API_KEY is not set. Hyperbrowser will not be available.')
+
+
+def create_anchor_browser_session(headless: bool = False) -> str:
+ """Create an Anchor Browser session and return CDP URL"""
+ if not ANCHOR_BROWSER_API_KEY:
+ raise ValueError('ANCHOR_BROWSER_API_KEY must be set')
+
+ browser_configuration = {
+ 'session': {'proxy': {'type': 'anchor_mobile', 'active': True, 'country_code': 'us'}},
+ 'browser': {
+ 'adblock': {'active': True},
+ 'captcha_solver': {'active': True},
+ 'headless': {'active': headless},
+ 'extra_stealth': {'active': True},
+ },
+ }
+
+ try:
+ response = requests.post(
+ 'https://api.anchorbrowser.io/v1/sessions',
+ headers={
+ 'anchor-api-key': ANCHOR_BROWSER_API_KEY,
+ 'Content-Type': 'application/json',
+ },
+ json=browser_configuration,
+ )
+ response.raise_for_status()
+ session_data = response.json()['data']
+ session_id = session_data['id']
+
+ return f'wss://connect.anchorbrowser.io?apiKey={ANCHOR_BROWSER_API_KEY}&sessionId={session_id}'
+
+ except requests.RequestException as e:
+ logger.error(f'Failed to create Anchor Browser session: {type(e).__name__}: {e}')
+ raise
+ except KeyError as e:
+ logger.error(f'Unexpected response format from Anchor Browser API: {e}')
+ raise
+
+
+def create_browserbase_session() -> str:
+ """Create a Browserbase session and return CDP URL"""
+ if not BROWSERBASE_API_KEY or not BROWSERBASE_PROJECT_ID:
+ raise ValueError('BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID must be set')
+
+ try:
+ from browserbase import Browserbase
+ except ImportError:
+ raise ImportError(
+ 'browserbase package is required for Browserbase functionality. Install it with: pip install browserbase'
+ )
+
+ try:
+ bb = Browserbase(api_key=BROWSERBASE_API_KEY)
+ session = bb.sessions.create(
+ project_id=BROWSERBASE_PROJECT_ID,
+ browser_settings={
+ 'advanced_stealth': True,
+ },
+ )
+
+ return session.connect_url
+
+ except Exception as e:
+ logger.error(f'Failed to create Browserbase session: {type(e).__name__}: {e}')
+ raise
+
+
+async def create_hyperbrowser_session() -> str:
+ """Create a Hyperbrowser session and return WebSocket endpoint"""
+ if not HYPERBROWSER_API_KEY:
+ raise ValueError('HYPERBROWSER_API_KEY must be set')
+
+ try:
+ from hyperbrowser import AsyncHyperbrowser
+ from hyperbrowser.models import CreateSessionParams
+ except ImportError:
+ raise ImportError(
+ 'hyperbrowser package is required for Hyperbrowser functionality. Install it with: pip install hyperbrowser'
+ )
+
+ try:
+ client = AsyncHyperbrowser(api_key=HYPERBROWSER_API_KEY)
+
+ session = await client.sessions.create(
+ params=CreateSessionParams(
+ use_stealth=True,
+ )
+ )
+
+ await client.close()
+
+ return session.ws_endpoint or ''
+
+ except Exception as e:
+ logger.error(f'Failed to create Hyperbrowser session: {type(e).__name__}: {e}')
+ raise
+
+
+async def setup_browser_session(
+ task: Task, headless: bool, highlight_elements: bool = True, browser: str = 'local'
+) -> BrowserSession:
+ """Setup browser session for the task"""
+
+ # Validate browser option
+ valid_browsers = ['local', 'anchor-browser', 'brightdata', 'browserbase', 'hyperbrowser', 'browser-use']
+ if browser not in valid_browsers:
+ logger.warning(f'Browser setup: Invalid browser option "{browser}". Falling back to local browser.')
+ browser = 'local'
+
+ cdp_url = None
+
+ if browser == 'anchor-browser':
+ if ANCHOR_BROWSER_API_KEY:
+ try:
+ logger.debug(f'Browser setup: Creating Anchor Browser session for task {task.task_id}')
+ cdp_url = await asyncio.to_thread(create_anchor_browser_session, headless)
+ except Exception as e:
+ logger.error(
+ f'Browser setup: Failed to create Anchor Browser session for task {task.task_id}: {type(e).__name__}: {e}'
+ )
+ logger.info(f'Browser setup: Falling back to local browser for task {task.task_id}')
+ cdp_url = None
+ else:
+ logger.warning(
+ f'Browser setup: Anchor Browser requested but ANCHOR_BROWSER_API_KEY not set. Using local browser for task {task.task_id}'
+ )
+ elif browser == 'brightdata':
+ if BRIGHTDATA_CDP_URL:
+ logger.debug(f'Browser setup: Using Brightdata CDP URL for task {task.task_id}')
+ cdp_url = BRIGHTDATA_CDP_URL
+ else:
+ logger.warning(
+ f'Browser setup: Brightdata requested but BRIGHTDATA_CDP_URL not set. Using local browser for task {task.task_id}'
+ )
+ elif browser == 'browserbase':
+ if BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID:
+ try:
+ logger.debug(f'Browser setup: Creating Browserbase session for task {task.task_id}')
+ cdp_url = await asyncio.to_thread(create_browserbase_session)
+ except Exception as e:
+ logger.error(
+ f'Browser setup: Failed to create Browserbase session for task {task.task_id}: {type(e).__name__}: {e}'
+ )
+ logger.info(f'Browser setup: Falling back to local browser for task {task.task_id}')
+ cdp_url = None
+ else:
+ logger.warning(
+ f'Browser setup: Browserbase requested but BROWSERBASE_API_KEY or BROWSERBASE_PROJECT_ID not set. Using local browser for task {task.task_id}'
+ )
+ elif browser == 'hyperbrowser':
+ if HYPERBROWSER_API_KEY:
+ try:
+ logger.debug(f'Browser setup: Creating Hyperbrowser session for task {task.task_id}')
+ cdp_url = await create_hyperbrowser_session()
+ except Exception as e:
+ logger.error(
+ f'Browser setup: Failed to create Hyperbrowser session for task {task.task_id}: {type(e).__name__}: {e}'
+ )
+ logger.info(f'Browser setup: Falling back to local browser for task {task.task_id}')
+ cdp_url = None
+ else:
+ logger.warning(
+ f'Browser setup: Hyperbrowser requested but HYPERBROWSER_API_KEY not set. Using local browser for task {task.task_id}'
+ )
+ elif browser == 'browser-use':
+ logger.warning(f'Browser setup: Browser-use not implemented yet. Falling back to local browser for task {task.task_id}')
+
+ profile_kwargs = {
+ 'user_data_dir': None, # Incognito mode - no persistent state
+ 'headless': headless,
+ 'chromium_sandbox': False, # running in docker
+ 'highlight_elements': highlight_elements, # Control element highlighting (passed to profile)
+ 'keep_alive': True,
+ # higher timeouts = higher success rates on long tail of slow sites or if on a slow CI server
+ # timeout=60_000,
+ # default_timeout=60_000,
+ # default_navigation_timeout=60_000,
+ # wait_for_network_idle_page_load_time=60.0,
+ # maximum_wait_page_load_time=60.0,
+ # wait_between_actions=0.5,
+ # ignore_https_errors=True, # some eval tasks have http:// or broken https sites in them
+ }
+
+ if hasattr(task, 'login_cookie') and task.login_cookie:
+ # For login tasks, configure storage_state to save cookies to JSON file
+ # Don't set user_data_dir=None for login tasks to avoid conflict
+ task_folder = Path(f'saved_trajectories/{task.task_id}')
+ task_folder.mkdir(parents=True, exist_ok=True)
+
+ storage_state_path = task_folder / 'storage_state.json'
+ # Create empty storage state file if it doesn't exist to avoid FileNotFoundError
+ if not storage_state_path.exists():
+ storage_state_path.write_text(json.dumps({'cookies': [], 'origins': []}))
+
+ profile_kwargs['storage_state'] = str(storage_state_path)
+ # Remove user_data_dir=None for login tasks to avoid conflict with storage_state
+ profile_kwargs.pop('user_data_dir', None)
+
+ downloads_dir_path = task_folder / 'downloads'
+ downloads_dir_path.mkdir(parents=True, exist_ok=True)
+ profile_kwargs['downloads_path'] = str(downloads_dir_path)
+
+ logger.debug(f'Login task {task.task_id}: Configured to save cookies to {storage_state_path}')
+
+ profile = BrowserProfile(**profile_kwargs)
+
+ if cdp_url:
+ logger.debug(f'Browser setup: Using CDP Browser for task {task.task_id}')
+ browser_session = BrowserSession(browser_profile=profile, cdp_url=cdp_url)
+ else:
+ # Use local browser
+ logger.debug(f'Browser setup: Initializing BrowserSession for task {task.task_id}')
+ browser_session = BrowserSession(browser_profile=profile)
+
+ # Start browser session
+ await browser_session.start()
+ logger.debug(f'Browser setup: Browser session started for task {task.task_id}')
+
+ # Navigate to task starting url if provided
+ # if task.website:
+ # logger.debug(f'Browser setup: Navigating to {task.website} for task {task.task_id}')
+ # await browser_session.navigate(task.website)
+
+ logger.debug(f'Browser setup: Setup completed for task {task.task_id}')
+ return browser_session
diff --git a/eval/judge_system.py b/eval/comprehensive_judge.py
similarity index 100%
rename from eval/judge_system.py
rename to eval/comprehensive_judge.py
diff --git a/eval/cookies.py b/eval/cookies.py
new file mode 100644
index 000000000..5bbec531c
--- /dev/null
+++ b/eval/cookies.py
@@ -0,0 +1,247 @@
+# ================================================
+# Login Cookie Tracking and Judgement
+# ================================================
+
+import json
+import logging
+import time
+from pathlib import Path
+
+import anyio
+
+logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(name)s: %(message)s')
+logger = logging.getLogger(__name__)
+
+# Global tracking for login cookie monitoring
+_login_cookie_tracker = {}
+
+
+async def check_login_cookie_at_step(browser_session, task_id: str, login_cookie: str, step: int) -> bool:
+ global _login_cookie_tracker
+
+ try:
+ # Get current cookies from browser
+ current_cookies = await browser_session.get_cookies()
+
+ if not current_cookies:
+ logger.debug(f'Task {task_id} Step {step}: No cookies found')
+ return False
+
+ # Check if this is an exact match requirement
+ if login_cookie.startswith('EXACTMATCH '):
+ exact_cookie_name = login_cookie[11:] # Remove "EXACTMATCH " prefix
+ is_exact_match = True
+ search_target = exact_cookie_name
+ else:
+ is_exact_match = False
+ search_target = login_cookie
+
+ # Check if login_cookie is present
+ for cookie in current_cookies:
+ cookie_name = cookie.get('name', '')
+ cookie_value = cookie.get('value', '')
+
+ if is_exact_match:
+ if cookie_name == search_target:
+ logger.info(f'✅ Task {task_id} Step {step}: Login cookie "{search_target}" found (exact match)')
+ # Track that we found the cookie
+ _login_cookie_tracker[task_id] = {
+ 'found': True,
+ 'step': step,
+ 'cookie_name': cookie_name,
+ 'match_type': 'exact',
+ }
+ return True
+ else:
+ if search_target in cookie_name or search_target in cookie_value:
+ logger.info(f'✅ Task {task_id} Step {step}: Login cookie "{search_target}" found (substring match)')
+ # Track that we found the cookie
+ _login_cookie_tracker[task_id] = {
+ 'found': True,
+ 'step': step,
+ 'cookie_name': cookie_name,
+ 'match_type': 'substring',
+ }
+ return True
+
+ logger.debug(f'Task {task_id} Step {step}: Login cookie "{search_target}" not found in {len(current_cookies)} cookies')
+ return False
+
+ except Exception as e:
+ logger.warning(f'Task {task_id} Step {step}: Error checking login cookie: {type(e).__name__}: {e}')
+ return False
+
+
+async def save_login_cookie_tracking(task_folder: Path, task_id: str) -> None:
+ """
+ Save the login cookie tracking information to a file.
+
+ Args:
+ task_folder: Directory to save the tracking file
+ task_id: The task ID
+ """
+ global _login_cookie_tracker
+
+ try:
+ tracking_file = task_folder / 'login_cookie_tracking.json'
+ tracking_data = _login_cookie_tracker.get(task_id, {'found': False})
+
+ # Add timestamp
+ tracking_data['timestamp'] = time.time()
+
+ # Save to file
+ async with await anyio.open_file(tracking_file, 'w') as f:
+ await f.write(json.dumps(tracking_data, indent=2))
+
+ logger.info(f'📝 Saved login cookie tracking for task {task_id}: {tracking_data}')
+
+ # Clean up tracking data to avoid memory leaks
+ _login_cookie_tracker.pop(task_id, None)
+
+ except Exception as e:
+ logger.warning(f'❌ Failed to save login cookie tracking for task {task_id}: {type(e).__name__}: {e}')
+
+
+async def evaluate_task_with_login_cookie(login_cookie: str, task_folder: Path) -> dict:
+ task_id = task_folder.name
+
+ # First, check if we have step-by-step tracking data
+ tracking_file = task_folder / 'login_cookie_tracking.json'
+ if tracking_file.exists():
+ try:
+ async with await anyio.open_file(tracking_file) as f:
+ tracking_data = json.loads(await f.read())
+
+ if tracking_data.get('found', False):
+ # Cookie was found during execution!
+ step_found = tracking_data.get('step', 'unknown')
+ match_type = tracking_data.get('match_type', 'unknown')
+ cookie_name = tracking_data.get('cookie_name', 'unknown')
+
+ success = True
+ score = 1.0
+ judgement = f"Automatic judgement: Login cookie '{login_cookie}' was found during step {step_found} ({match_type} match on '{cookie_name}')"
+ error = None
+
+ logger.info(
+ f"✅ Cookie evaluation result from step tracking: success={success} for login_cookie='{login_cookie}'"
+ )
+
+ return {
+ 'task_id': task_id,
+ 'judgement': judgement,
+ 'success': success,
+ 'error': error,
+ 'score': score,
+ 'tracking_data': tracking_data,
+ }
+ except Exception as e:
+ logger.warning(f'Failed to load login cookie tracking: {e}')
+
+ # Fallback to end-state cookie checking (original behavior)
+ logger.info(f'🔄 No step-by-step tracking found for task {task_id}, falling back to end-state cookie checking')
+
+ # Look for cookies in saved_trajectories (saved by browser-use during shutdown)
+ cookies_file = task_folder / 'cookies.json'
+ storage_state_file = task_folder / 'storage_state.json'
+
+ cookies_data = None
+ cookies_source = None
+
+ # Try to load cookies from storage_state.json first (newer format)
+ if storage_state_file.exists():
+ try:
+ async with await anyio.open_file(storage_state_file) as f:
+ storage_state = json.loads(await f.read())
+ cookies_data = storage_state.get('cookies', [])
+ cookies_source = 'storage_state.json'
+ except Exception as e:
+ logger.warning(f'Failed to load storage_state.json: {e}')
+
+ # Fallback to cookies.json (older format)
+ if not cookies_data and cookies_file.exists():
+ try:
+ async with await anyio.open_file(cookies_file) as f:
+ cookies_data = json.loads(await f.read())
+ cookies_source = 'cookies.json'
+ except Exception as e:
+ logger.warning(f'Failed to load cookies.json: {e}')
+
+ if not cookies_data:
+ return {
+ 'task_id': task_id,
+ 'judgement': 'Automatic judgement: No cookies saved for evaluation and no step-by-step tracking',
+ 'success': False,
+ 'error': 'No cookies file found for login task evaluation and no step-by-step tracking',
+ 'score': 0.0,
+ }
+
+ logger.debug(f'Found {len(cookies_data)} cookies from {cookies_source}')
+
+ # Check if this is an exact match requirement
+ if login_cookie.startswith('EXACTMATCH '):
+ # Extract the actual cookie name after "EXACTMATCH "
+ exact_cookie_name = login_cookie[11:] # Remove "EXACTMATCH " prefix
+ is_exact_match = True
+ search_target = exact_cookie_name
+ logger.debug(f"Using exact match for cookie name: '{exact_cookie_name}'")
+ else:
+ # Use substring matching (original behavior)
+ is_exact_match = False
+ search_target = login_cookie
+ logger.debug(f"Using substring matching for: '{login_cookie}'")
+
+ # Check if login_cookie is present in cookies
+ login_cookie_found = False
+ matching_cookie_info = None
+
+ for cookie in cookies_data:
+ cookie_name = cookie.get('name', '')
+ cookie_value = cookie.get('value', '')
+
+ if is_exact_match:
+ # Exact match: check if cookie name exactly matches the target
+ if cookie_name == search_target:
+ login_cookie_found = True
+ matching_cookie_info = f"exact name match='{cookie_name}'"
+ logger.debug(f'Login cookie found with exact match: {matching_cookie_info}')
+ break
+ else:
+ # Substring match: check if target appears in cookie name or value
+ if search_target in cookie_name or search_target in cookie_value:
+ login_cookie_found = True
+ matching_cookie_info = f"substring match in name='{cookie_name}'"
+ logger.debug(f'Login cookie found with substring match: {matching_cookie_info}')
+ break
+
+ # Prepare evaluation result
+ if login_cookie_found:
+ if is_exact_match:
+ judgement = (
+ f"Automatic judgement: Login cookie '{search_target}' was found as exact match in end-state browser cookies"
+ )
+ else:
+ judgement = f"Automatic judgement: Login cookie '{search_target}' was found in end-state browser cookies"
+ success = True
+ score = 1.0
+ error = None
+ else:
+ if is_exact_match:
+ judgement = (
+ f"Automatic judgement: Login cookie '{search_target}' was NOT found as exact match in end-state browser cookies"
+ )
+ else:
+ judgement = f"Automatic judgement: Login cookie '{search_target}' was NOT found in end-state browser cookies"
+ success = False
+ score = 0.0
+ error = None
+
+ logger.info(f"Cookie evaluation result from end-state: success={success} for login_cookie='{login_cookie}'")
+
+ return {
+ 'task_id': task_id,
+ 'judgement': judgement,
+ 'success': success,
+ 'error': error,
+ 'score': score,
+ }
diff --git a/eval/models.py b/eval/models.py
new file mode 100644
index 000000000..4e03d73a3
--- /dev/null
+++ b/eval/models.py
@@ -0,0 +1,228 @@
+import logging
+import os
+
+from browser_use.llm.anthropic.chat import ChatAnthropic
+from browser_use.llm.google.chat import ChatGoogle
+from browser_use.llm.groq.chat import ChatGroq
+from browser_use.llm.openai.chat import ChatOpenAI
+
+logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(name)s: %(message)s')
+logger = logging.getLogger(__name__)
+
+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.5-haiku-latest': {
+ 'provider': 'anthropic',
+ 'model_name': 'claude-3-5-haiku-latest',
+ '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',
+ },
+ 'claude-sonnet-4': {
+ 'provider': 'anthropic',
+ 'model_name': 'claude-sonnet-4-20250514',
+ 'api_key_env': 'ANTHROPIC_API_KEY',
+ },
+ 'claude-opus-4': {
+ 'provider': 'anthropic',
+ 'model_name': 'claude-opus-4-20250514',
+ '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-lite': {'provider': 'google', 'model_name': 'gemini-2.0-flash-lite', 'api_key_env': 'GEMINI_API_KEY'},
+ 'gemini-2.0-flash': {
+ 'provider': 'google',
+ 'model_name': 'gemini-2.0-flash',
+ 'api_key_env': 'GEMINI_API_KEY',
+ 'thinking_budget': 0,
+ },
+ 'gemini-2.5-pro': {'provider': 'google', 'model_name': 'gemini-2.5-pro', 'api_key_env': 'GEMINI_API_KEY'},
+ 'gemini-2.5-flash': {
+ 'provider': 'google',
+ 'model_name': 'gemini-2.5-flash',
+ 'api_key_env': 'GEMINI_API_KEY',
+ 'thinking_budget': 0,
+ },
+ 'gemini-2.5-flash-lite-preview': {
+ 'provider': 'google',
+ 'model_name': 'gemini-2.5-flash-lite-preview-06-17',
+ 'api_key_env': 'GEMINI_API_KEY',
+ 'thinking_budget': 0,
+ },
+ 'gemini-2.5-pro-preview-05-06': {
+ 'provider': 'google',
+ 'model_name': 'gemini-2.5-pro-preview-05-06',
+ 'api_key_env': 'GEMINI_API_KEY',
+ },
+ 'gemini-2.5-flash-preview': {
+ 'provider': 'google',
+ 'model_name': 'gemini-2.5-flash-preview-04-17',
+ '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-4.1-mini': {'provider': 'openai', 'model_name': 'gpt-4.1-mini-2025-04-14', 'api_key_env': 'OPENAI_API_KEY'},
+ 'gpt-o3': {'provider': 'openai', 'model_name': 'o3-2025-04-16', 'api_key_env': 'OPENAI_API_KEY'},
+ 'gpt-4.1-nano': {'provider': 'openai', 'model_name': 'gpt-4.1-nano-2025-04-14', 'api_key_env': 'OPENAI_API_KEY'},
+ 'gpt-4o': {'provider': 'openai', 'model_name': 'gpt-4o', 'api_key_env': 'OPENAI_API_KEY'},
+ 'gpt-4o-mini': {'provider': 'openai', 'model_name': 'gpt-4o-mini', 'api_key_env': 'OPENAI_API_KEY'},
+ 'gpt-o4-mini': {'provider': 'openai', 'model_name': 'o4-mini', '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',
+ },
+ # Groq
+ 'gemma2-9b-it': {
+ 'provider': 'groq',
+ 'model_name': 'gemma2-9b-it',
+ 'api_key_env': 'GROQ_API_KEY',
+ 'service_tier': 'auto',
+ },
+ 'llama-3.3-70b-versatile': {
+ 'provider': 'groq',
+ 'model_name': 'llama-3.3-70b-versatile',
+ 'api_key_env': 'GROQ_API_KEY',
+ 'service_tier': 'auto',
+ },
+ 'llama-3.1-8b-instant': {
+ 'provider': 'groq',
+ 'model_name': 'llama-3.1-8b-instant',
+ 'api_key_env': 'GROQ_API_KEY',
+ 'service_tier': 'auto',
+ },
+ 'llama3-70b-8192': {
+ 'provider': 'groq',
+ 'model_name': 'llama3-70b-8192',
+ 'api_key_env': 'GROQ_API_KEY',
+ 'service_tier': 'auto',
+ },
+ 'llama3-8b-8192': {
+ 'provider': 'groq',
+ 'model_name': 'llama3-8b-8192',
+ 'api_key_env': 'GROQ_API_KEY',
+ 'service_tier': 'auto',
+ },
+ # Groq Preview
+ 'llama-4-maverick': {
+ 'provider': 'groq',
+ 'model_name': 'meta-llama/llama-4-maverick-17b-128e-instruct',
+ 'api_key_env': 'GROQ_API_KEY',
+ 'service_tier': 'auto',
+ },
+ 'llama-4-scout': {
+ 'provider': 'groq',
+ 'model_name': 'meta-llama/llama-4-scout-17b-16e-instruct',
+ 'api_key_env': 'GROQ_API_KEY',
+ 'service_tier': 'auto',
+ },
+ # SambaNova
+ 'deepseek-r1-sambanova': {
+ 'provider': 'openai_compatible',
+ 'model_name': 'DeepSeek-R1',
+ 'base_url': 'https://api.sambanova.ai/v1',
+ 'api_key_env': 'SAMBANOVA_API_KEY',
+ },
+ 'llama-4-maverick-sambanova': {
+ 'provider': 'openai_compatible',
+ 'model_name': 'Llama-4-Maverick-17B-128E-Instruct',
+ 'base_url': 'https://api.sambanova.ai/v1',
+ 'api_key_env': 'SAMBANOVA_API_KEY',
+ },
+}
+
+
+def get_llm(model_name: str):
+ """Instantiates the correct 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:
+ 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
+
+ match provider:
+ case 'openai':
+ kwargs = {'model': config['model_name'], 'temperature': 0.0}
+ # Must set temperatue=1 if model is gpt-o4-mini
+ if model_name in ['gpt-o4-mini', 'gpt-o3']:
+ kwargs['temperature'] = 1
+ if api_key:
+ kwargs['api_key'] = api_key
+ return ChatOpenAI(**kwargs)
+ case 'anthropic':
+ kwargs = {
+ 'model': config['model_name'],
+ 'temperature': 0.0,
+ 'timeout': 100,
+ }
+ if api_key:
+ kwargs['api_key'] = api_key
+ return ChatAnthropic(**kwargs)
+ case 'google':
+ kwargs = {'model': config['model_name'], 'temperature': 0.0, 'thinking_budget': config.get('thinking_budget', None)}
+ if api_key:
+ kwargs['api_key'] = api_key
+ return ChatGoogle(**kwargs)
+ case 'groq':
+ kwargs = {
+ 'model': config['model_name'],
+ 'temperature': 0.0,
+ 'service_tier': config.get('service_tier', 'auto'),
+ }
+ if api_key:
+ kwargs['api_key'] = api_key
+ return ChatGroq(**kwargs)
+ case 'openai_compatible':
+ kwargs = {'model': config['model_name'], 'base_url': config['base_url'], 'temperature': 0.0}
+ if api_key:
+ kwargs['api_key'] = api_key
+ elif config.get('base_url'):
+ 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)
+ case _:
+ raise ValueError(f'Unknown provider: {provider}')
diff --git a/eval/resource_monitoring.py b/eval/resource_monitoring.py
new file mode 100644
index 000000000..d954f6896
--- /dev/null
+++ b/eval/resource_monitoring.py
@@ -0,0 +1,232 @@
+# @file purpose: Resource monitoring and system health tracking for eval pipeline
+"""
+Resource monitoring module for browser-use evaluation pipeline.
+
+This module provides system resource monitoring capabilities including:
+- Memory and CPU usage tracking
+- Process monitoring (Chrome/Python processes)
+- Background monitoring with configurable intervals
+- Graceful shutdown handling with signal handlers
+- Resource logging and alerting
+
+The module is designed to help track system health during long-running
+evaluation tasks and provide early warning for resource exhaustion.
+"""
+
+import asyncio
+import gc
+import logging
+import signal
+import sys
+import threading
+import time
+from typing import Any, Dict
+
+import psutil
+
+# Module logger
+logger = logging.getLogger(__name__)
+
+# Global variables for resource monitoring
+_resource_monitor_task = None
+_resource_monitor_stop_event = None
+_graceful_shutdown_initiated = False
+
+
+def get_system_resources() -> Dict[str, Any]:
+ """Get current system resource usage"""
+ try:
+ # Memory usage
+ memory = psutil.virtual_memory()
+ memory_percent = memory.percent
+ memory_available_gb = memory.available / (1024**3)
+
+ # CPU usage
+ cpu_percent = psutil.cpu_percent(interval=1)
+
+ # Load average (Unix only)
+ try:
+ load_avg = psutil.getloadavg()
+ load_1min = load_avg[0]
+ except (AttributeError, OSError):
+ load_1min = 0.0
+
+ # Process count
+ process_count = len(psutil.pids())
+
+ # Chrome/Browser processes
+ chrome_processes = []
+ python_processes = []
+ for proc in psutil.process_iter(['pid', 'name', 'memory_percent', 'cpu_percent']):
+ try:
+ name = proc.info['name'].lower()
+ if 'chrome' in name or 'chromium' in name:
+ chrome_processes.append(proc.info)
+ elif 'python' in name:
+ python_processes.append(proc.info)
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ continue
+
+ return {
+ 'memory_percent': memory_percent,
+ 'memory_available_gb': memory_available_gb,
+ 'cpu_percent': cpu_percent,
+ 'load_1min': load_1min,
+ 'process_count': process_count,
+ 'chrome_process_count': len(chrome_processes),
+ 'python_process_count': len(python_processes),
+ 'chrome_processes': chrome_processes[:5], # Top 5 chrome processes
+ 'python_processes': python_processes[:5], # Top 5 python processes
+ }
+ except Exception as e:
+ logger.warning(f'Failed to get system resources: {type(e).__name__}: {e}')
+ return {
+ 'memory_percent': 0,
+ 'memory_available_gb': 0,
+ 'cpu_percent': 0,
+ 'load_1min': 0,
+ 'process_count': 0,
+ 'chrome_process_count': 0,
+ 'python_process_count': 0,
+ 'chrome_processes': [],
+ 'python_processes': [],
+ }
+
+
+def log_system_resources(context: str = ''):
+ """Log current system resource usage"""
+ resources = get_system_resources()
+ logger.info(f'=== SYSTEM RESOURCES {context} ===')
+ logger.info(f'Memory: {resources["memory_percent"]:.1f}% used, {resources["memory_available_gb"]:.2f}GB available')
+ logger.info(f'CPU: {resources["cpu_percent"]:.1f}%, Load: {resources["load_1min"]:.2f}')
+ logger.info(
+ f'Processes: {resources["process_count"]} total, {resources["chrome_process_count"]} Chrome, {resources["python_process_count"]} Python'
+ )
+
+ if resources['chrome_processes']:
+ logger.info('Top Chrome processes:')
+ for proc in resources['chrome_processes']:
+ logger.info(
+ f' PID {proc["pid"]}: {proc["name"]} - CPU: {proc["cpu_percent"]:.1f}%, Memory: {proc["memory_percent"]:.1f}%'
+ )
+
+ logger.info('=' * (20 + len(context)))
+
+
+async def start_resource_monitoring(interval: int = 30):
+ """Start background resource monitoring"""
+ global _resource_monitor_task, _resource_monitor_stop_event
+
+ if _resource_monitor_task is not None:
+ logger.warning('Resource monitoring is already running')
+ return
+
+ _resource_monitor_stop_event = asyncio.Event()
+
+ async def monitor_loop():
+ """Background monitoring loop"""
+ logger.info(f'Starting resource monitoring (interval: {interval}s)')
+ try:
+ while _resource_monitor_stop_event is not None and not _resource_monitor_stop_event.is_set():
+ try:
+ log_system_resources('MONITOR')
+
+ # Check for concerning resource levels
+ resources = get_system_resources()
+ if resources['memory_percent'] > 85:
+ logger.warning(f'⚠️ HIGH MEMORY USAGE: {resources["memory_percent"]:.1f}%')
+ if resources['cpu_percent'] > 90:
+ logger.warning(f'⚠️ HIGH CPU USAGE: {resources["cpu_percent"]:.1f}%')
+ if resources['chrome_process_count'] > 20:
+ logger.warning(f'⚠️ HIGH CHROME PROCESS COUNT: {resources["chrome_process_count"]}')
+
+ # Force garbage collection periodically
+ if resources['memory_percent'] > 70:
+ logger.info('Running garbage collection due to high memory usage')
+ gc.collect()
+
+ except Exception as e:
+ logger.error(f'Error in resource monitoring: {type(e).__name__}: {e}')
+
+ try:
+ if _resource_monitor_stop_event is not None:
+ await asyncio.wait_for(_resource_monitor_stop_event.wait(), timeout=interval)
+ else:
+ await asyncio.sleep(interval)
+ break # Event was set, exit loop
+ except TimeoutError:
+ continue # Timeout reached, continue monitoring
+ except Exception as e:
+ logger.error(f'Resource monitoring loop crashed: {type(e).__name__}: {e}')
+ finally:
+ logger.info('Resource monitoring stopped')
+
+ _resource_monitor_task = asyncio.create_task(monitor_loop())
+
+
+async def stop_resource_monitoring():
+ """Stop background resource monitoring"""
+ global _resource_monitor_task, _resource_monitor_stop_event
+
+ if _resource_monitor_stop_event is not None:
+ _resource_monitor_stop_event.set()
+
+ if _resource_monitor_task is not None:
+ try:
+ await asyncio.wait_for(_resource_monitor_task, timeout=5.0)
+ except TimeoutError:
+ logger.warning('Resource monitoring task did not stop gracefully')
+ _resource_monitor_task.cancel()
+ try:
+ await _resource_monitor_task
+ except asyncio.CancelledError:
+ pass
+
+ _resource_monitor_task = None
+ _resource_monitor_stop_event = None
+
+
+def setup_signal_handlers():
+ """Setup signal handlers for graceful shutdown"""
+ global _graceful_shutdown_initiated
+
+ def signal_handler(signum, frame):
+ global _graceful_shutdown_initiated
+ if _graceful_shutdown_initiated:
+ logger.critical('🔥 FORCE EXIT: Second signal received, terminating immediately')
+ sys.exit(1)
+
+ _graceful_shutdown_initiated = True
+ logger.warning(f'⚠️ GRACEFUL SHUTDOWN: Received signal {signum}, initiating graceful shutdown...')
+ log_system_resources('SHUTDOWN')
+
+ # Try to stop resource monitoring
+ try:
+ loop = asyncio.get_event_loop()
+ if loop.is_running():
+ loop.create_task(stop_resource_monitoring())
+ except Exception as e:
+ logger.error(f'Failed to stop resource monitoring during shutdown: {e}')
+
+ # Give some time for cleanup, then force exit
+ def force_exit():
+ time.sleep(10)
+ if _graceful_shutdown_initiated:
+ logger.critical('🔥 FORCE EXIT: Graceful shutdown timeout, terminating')
+ sys.exit(1)
+
+ threading.Thread(target=force_exit, daemon=True).start()
+
+ # Register signal handlers
+ signal.signal(signal.SIGINT, signal_handler)
+ signal.signal(signal.SIGTERM, signal_handler)
+
+
+def is_shutdown_initiated() -> bool:
+ """Check if graceful shutdown has been initiated"""
+ return _graceful_shutdown_initiated
+
+
+def is_monitoring_active() -> bool:
+ """Check if resource monitoring is currently active"""
+ return _resource_monitor_task is not None and not _resource_monitor_task.done()
diff --git a/eval/server.py b/eval/server.py
new file mode 100644
index 000000000..56ca7424f
--- /dev/null
+++ b/eval/server.py
@@ -0,0 +1,353 @@
+# ================================================
+# Server Interaction
+# ================================================
+
+import json
+import logging
+import os
+import time
+
+import requests
+
+logger = logging.getLogger(__name__)
+
+
+def fetch_tasks_from_server(convex_url: str, secret_key: str, test_case_name: str):
+ """Fetches the specified test case file from the Convex HTTP endpoint."""
+
+ if not convex_url:
+ logger.error('Error: EVALUATION_TOOL_URL environment variable not set.')
+ return None
+
+ if not secret_key:
+ logger.error('Error: EVALUATION_TOOL_SECRET_KEY environment variable not set.')
+ return None
+
+ endpoint_url = f'{convex_url}/api/getTestCase'
+ headers = {
+ 'Authorization': f'Bearer {secret_key}',
+ 'Content-Type': 'application/json',
+ }
+ payload = {'name': test_case_name}
+
+ logger.info(f"Fetching test case '{test_case_name}' from {endpoint_url}...")
+
+ try:
+ response = requests.post(endpoint_url, headers=headers, json=payload)
+
+ logger.info(f'Fetch Status Code: {response.status_code}')
+
+ if response.status_code == 200:
+ try:
+ data = response.json()
+ logger.info(f"Successfully fetched test case data for '{test_case_name}'.")
+ # Assuming the data is the list of tasks
+ if isinstance(data, list):
+ return data
+ else:
+ logger.error(f'Error: Fetched data is not a list. Type: {type(data)}')
+ logger.error(f'Raw response: {response.text}')
+ return None
+
+ except json.JSONDecodeError:
+ logger.error('Error: Failed to decode JSON response.')
+ logger.error(f'Raw response text: {response.text}')
+ return None
+ else:
+ logger.error(f"Error: Failed to fetch test case '{test_case_name}'. Status: {response.status_code}")
+ logger.error(f'Response: {response.text}')
+ return None
+
+ except requests.exceptions.RequestException as e:
+ logger.error(f'Error during request to fetch test case: {type(e).__name__}: {e}')
+ return None
+
+
+def fetch_auth_distribution_from_server(convex_url: str, secret_key: str):
+ """Fetches an available auth distribution from the Convex HTTP endpoint."""
+
+ if not convex_url:
+ logger.error('Error: EVALUATION_TOOL_URL environment variable not set.')
+ return None
+
+ if not secret_key:
+ logger.error('Error: EVALUATION_TOOL_SECRET_KEY environment variable not set.')
+ return None
+
+ endpoint_url = f'{convex_url}/api/getAuthDistribution'
+ headers = {
+ 'Authorization': f'Bearer {secret_key}',
+ 'Content-Type': 'application/json',
+ }
+
+ logger.info(f'Fetching auth distribution from {endpoint_url}...')
+
+ try:
+ response = requests.post(endpoint_url, headers=headers, json={})
+
+ logger.info(f'Fetch Auth Distribution Status Code: {response.status_code}')
+
+ if response.status_code == 200:
+ try:
+ data = response.json()
+ logger.info('Successfully fetched auth distribution data.')
+ # Verify the response has the expected structure
+ if isinstance(data, dict) and 'id' in data and 'loginInfo' in data:
+ return data
+ else:
+ logger.error(
+ f'Error: Fetched auth distribution data has unexpected structure. Keys: {list(data.keys()) if isinstance(data, dict) else "Not a dict"}'
+ )
+ logger.error(f'Raw response: {response.text}')
+ return None
+
+ except json.JSONDecodeError:
+ logger.error('Error: Failed to decode JSON response for auth distribution.')
+ logger.error(f'Raw response text: {response.text}')
+ return None
+ elif response.status_code == 404:
+ logger.warning('No available auth distribution found on server.')
+ return None
+ else:
+ logger.error(f'Error: Failed to fetch auth distribution. Status: {response.status_code}')
+ logger.error(f'Response: {response.text}')
+ return None
+
+ except requests.exceptions.RequestException as e:
+ logger.error(f'Error during request to fetch auth distribution: {type(e).__name__}: {e}')
+ return None
+
+
+def format_auth_info_for_agent(auth_distribution: dict, auth_keys: list[str]) -> str:
+ """
+ Formats auth information from auth distribution for the agent task description.
+
+ Args:
+ auth_distribution: Dict with 'loginInfo' key containing auth data
+ auth_keys: List of auth keys to extract (e.g., ['google', 'facebook'])
+
+ Returns:
+ Formatted string with login credentials or empty string if no matching keys
+ """
+ if not auth_distribution or not auth_keys:
+ return ''
+
+ login_info = auth_distribution.get('loginInfo', {})
+ if not login_info:
+ logger.warning('Auth distribution has no loginInfo')
+ return ''
+
+ # Extract relevant auth information based on auth_keys
+ relevant_auths = []
+ for auth_key in auth_keys:
+ if auth_key in login_info:
+ auth_data = login_info[auth_key]
+ if isinstance(auth_data, dict):
+ # Format the auth data for this key
+ auth_details = []
+ for key, value in auth_data.items():
+ auth_details.append(f'{key}: {value}')
+
+ if auth_details:
+ relevant_auths.append(f'{auth_key} with {", ".join(auth_details)}')
+ else:
+ logger.warning(f"Auth data for key '{auth_key}' is not a dictionary: {type(auth_data)}")
+ else:
+ logger.warning(f"Auth key '{auth_key}' not found in available login info. Available keys: {list(login_info.keys())}")
+
+ if relevant_auths:
+ auth_text = f'\n\nThe following login credentials can be used to complete this task: {"; ".join(relevant_auths)}.'
+ logger.info(f'Formatted auth info: {auth_text}')
+ return auth_text
+ else:
+ logger.warning(f'No matching auth keys found. Requested: {auth_keys}, Available: {list(login_info.keys())}')
+ return ''
+
+
+def start_new_run(convex_url: str, secret_key: str, run_details: dict, existing_run_id: str | None = None):
+ """Sends a request to start a new evaluation run and returns the run ID."""
+ if not convex_url or not secret_key:
+ logger.error('Error: Convex URL or Secret Key not provided for starting run.')
+ return None
+
+ endpoint_url = f'{convex_url}/api/startRun'
+ headers = {
+ 'Authorization': f'Bearer {secret_key}',
+ 'Content-Type': 'application/json',
+ }
+
+ # Add existing_run_id to the payload if provided
+ payload = run_details.copy()
+ if existing_run_id:
+ payload['runId'] = existing_run_id
+
+ logger.info(f'Sending request to start run at {endpoint_url}...')
+ # Avoid logging secret key in run_details if it were ever passed
+ loggable_details = {k: v for k, v in payload.items() if k != 'secret_key'}
+ logger.info(f'Run details: {json.dumps(loggable_details, indent=2)}')
+
+ try:
+ response = requests.post(endpoint_url, headers=headers, json=payload)
+ logger.info(f'Start Run Status Code: {response.status_code}')
+
+ if response.status_code == 200:
+ try:
+ data = response.json()
+ run_id = data.get('runId')
+ if run_id:
+ logger.info(f'Successfully started run. Run ID: {run_id}')
+ return run_id
+ else:
+ logger.error("Error: 'runId' not found in successful startRun response.")
+ logger.error(f'Raw response: {response.text}')
+ return None
+ except json.JSONDecodeError:
+ logger.error('Error: Failed to decode startRun JSON response.')
+ logger.error(f'Raw response text: {response.text}')
+ return None
+ else:
+ logger.error('Error: Failed to start run.')
+ logger.error(f'Response: {response.text}')
+ return None
+
+ except requests.exceptions.RequestException as e:
+ logger.error(f'Error during startRun request: {type(e).__name__}: {e}')
+ return None
+
+
+def save_task_result_to_server(convex_url: str, secret_key: str, result_details: dict):
+ """Sends a request to save a single task result to the Convex backend."""
+
+ if not convex_url:
+ logger.error('Error: EVALUATION_TOOL_URL environment variable not set for saving task result.')
+ return False
+
+ if not secret_key:
+ logger.error('Error: EVALUATION_TOOL_SECRET_KEY environment variable not set for saving task result.')
+ return False
+
+ # Ensure runId is present in the details being sent
+ if 'runId' not in result_details or not result_details['runId']:
+ logger.error("Error: 'runId' is missing or empty in result_details for saveTaskResult.")
+ return False
+
+ endpoint_url = f'{convex_url}/api/saveTaskResult'
+ headers = {
+ 'Authorization': f'Bearer {secret_key}',
+ 'Content-Type': 'application/json',
+ }
+
+ logger.info(f'Sending request to save task result at {endpoint_url}...')
+ logger.debug(f'Result details payload: {json.dumps(result_details, indent=2)}') # Log details at debug level
+
+ try:
+ response = requests.post(endpoint_url, headers=headers, json=result_details)
+
+ logger.info(f'Save Task Result Status Code: {response.status_code}')
+
+ if response.status_code == 200:
+ try:
+ data = response.json()
+ logger.info(f'Successfully saved task result: {data.get("message")}')
+ logger.info(f'Result ID: {data.get("resultId")}')
+ return True
+ except json.JSONDecodeError:
+ logger.error('Error: Failed to decode saveTaskResult JSON response.')
+ logger.error(f'Raw response text: {response.text}')
+ return False
+ else:
+ logger.error('Error: Failed to save task result.')
+ logger.error(f'Response: {response.text}')
+ return False
+
+ except requests.exceptions.RequestException as e:
+ logger.error(f'Error during saveTaskResult request: {type(e).__name__}: {e}')
+ return False
+
+
+def save_runner_progress_to_server(convex_url: str, secret_key: str, progress_details: dict):
+ """Sends a request to save runner progress to the Convex backend."""
+
+ if not convex_url:
+ logger.debug('No EVALUATION_TOOL_URL environment variable set for saving runner progress.')
+ return False
+
+ if not secret_key:
+ logger.debug('No EVALUATION_TOOL_SECRET_KEY environment variable set for saving runner progress.')
+ return False
+
+ endpoint_url = f'{convex_url}/api/saveRunnerProgress'
+ headers = {
+ 'Authorization': f'Bearer {secret_key}',
+ 'Content-Type': 'application/json',
+ }
+
+ try:
+ response = requests.post(endpoint_url, headers=headers, json=progress_details, timeout=10)
+
+ if response.status_code == 200:
+ logger.debug(f'Successfully saved runner progress for {progress_details.get("runnerId")}')
+ return True
+ else:
+ logger.warning(f'Failed to save runner progress. Status: {response.status_code}')
+ return False
+
+ except requests.exceptions.RequestException as e:
+ logger.warning(f'Error during saveRunnerProgress request: {type(e).__name__}: {e}')
+ return False
+
+
+def generate_runner_id(task_id: str, github_run_id: str | None = None) -> str:
+ """Generate a unique runner ID for progress tracking that matches GitHub Actions pattern"""
+ if github_run_id:
+ # Use batch-level runner ID consistent with GitHub Actions
+ # GitHub Actions uses: github_run_{GITHUB_RUN_ID}_batch_{START_INDEX}
+ # Get start index from environment variable set by GitHub Actions
+ start_index = os.getenv('EVAL_START_INDEX', '0')
+ return f'github_run_{github_run_id}_batch_{start_index}'
+ else:
+ # Fallback for local runs
+ return f'local_run_{int(time.time())}'
+
+
+def send_progress_update(
+ convex_url: str,
+ secret_key: str,
+ run_id: str,
+ task_id: str,
+ current_stage: str,
+ status: str = 'active',
+ github_workflow_url: str | None = None,
+ assigned_task_range: str | None = None,
+ error_message: str | None = None,
+) -> bool:
+ """Send a progress update for the current runner and task"""
+ try:
+ # Generate runner ID
+ github_run_id = os.getenv('GITHUB_RUN_ID')
+ runner_id = generate_runner_id(task_id, github_run_id)
+
+ # Extract workflow run ID from URL if available
+ github_workflow_run_id = None
+ if github_workflow_url and 'actions/runs/' in github_workflow_url:
+ try:
+ github_workflow_run_id = github_workflow_url.split('actions/runs/')[1].split('/')[0]
+ except (IndexError, AttributeError):
+ pass
+
+ progress_details = {
+ 'runId': run_id,
+ 'runnerId': runner_id,
+ 'taskId': task_id,
+ 'currentStage': current_stage,
+ 'status': status,
+ 'githubWorkflowUrl': github_workflow_url,
+ 'githubWorkflowRunId': github_workflow_run_id,
+ 'assignedTaskRange': assigned_task_range,
+ 'errorMessage': error_message,
+ }
+
+ return save_runner_progress_to_server(convex_url, secret_key, progress_details)
+ except Exception as e:
+ logger.warning(f'Failed to send progress update: {type(e).__name__}: {e}')
+ return False
diff --git a/eval/service.py b/eval/service.py
index 395d67b48..6ffdcaa0d 100644
--- a/eval/service.py
+++ b/eval/service.py
@@ -1,976 +1,90 @@
-# pyright: reportMissingImports=false
-# ==============================================================================================================
-# Documentation for this evaluation file.
-
-# Here is the command to run the evaluation:
-# python eval/service.py --parallel-runs 2 --max-steps 25 --start 0 --end 100 --model llama-4-maverick --eval-model gpt-4.1 --no-vision --eval-group "PRTests" --user-message "message here"
-
-# ==============================================================================================================
-
-
-# ==============================================================================================================
-# This is the LLM as a judge evaluation system from the OSU-NLP Group paper
-# Any adaptiations made should be explicitly stated here:
-# Adaptations:
-# We are using our own wrapper for the OpenAI API
-# This means we changed model.generate to model.invoke. The behavior of the model should be identical.
-# Added a Online_Mind2Web_eval_with_retry wrapper with retry logic in case of API rate limiting or other issues.
-
-
-# @article{xue2025illusionprogressassessingcurrent,
-# title={An Illusion of Progress? Assessing the Current State of Web Agents},
-# author={Tianci Xue and Weijian Qi and Tianneng Shi and Chan Hee Song and Boyu Gou and Dawn Song and Huan Sun and Yu Su},
-# year={2025},
-# eprint={2504.01382},
-# archivePrefix={arXiv},
-# primaryClass={cs.AI},
-# url={https://arxiv.org/abs/2504.01382},
-# }
-
-# @inproceedings{deng2023mind2web,
-# author = {Deng, Xiang and Gu, Yu and Zheng, Boyuan and Chen, Shijie and Stevens, Sam and Wang, Boshi and Sun, Huan and Su, Yu},
-# booktitle = {Advances in Neural Information Processing Systems},
-# editor = {A. Oh and T. Naumann and A. Globerson and K. Saenko and M. Hardt and S. Levine},
-# pages = {28091--28114},
-# publisher = {Curran Associates, Inc.},
-# title = {Mind2Web: Towards a Generalist Agent for the Web},
-# url = {https://proceedings.neurips.cc/paper_files/paper/2023/file/5950bf290a1570ea401bf98882128160-Paper-Datasets_and_Benchmarks.pdf},
-# volume = {36},
-# year = {2023}
-# }
-# ==============================================================================================================
+# ================================================
+# Imports
+# ================================================
+
+import argparse
import asyncio
import base64
-import gc
-import io
+import http.client
import json
import logging
import os
-import re
-import signal
-import sys
-import threading
import time
from pathlib import Path
from uuid import UUID
import anyio
-import psutil
-import requests
from dotenv import load_dotenv
from lmnr import AsyncLaminarClient, Laminar, observe
-from PIL import Image
from pydantic import BaseModel
-from browser_use.llm.anthropic.chat import ChatAnthropic
+from browser_use import ActionResult, Agent, BrowserSession, Controller
+from browser_use.agent.views import AgentHistoryList
from browser_use.llm.base import BaseChatModel
-from browser_use.llm.google.chat import ChatGoogle
-from browser_use.llm.groq.chat import ChatGroq
-from browser_use.llm.openai.chat import ChatOpenAI
-from eval.utils import create_pydantic_model_from_schema
-
-MAX_IMAGE = 5
+from .browsers import (
+ ANCHOR_BROWSER_API_KEY,
+ BRIGHTDATA_CDP_URL,
+ BROWSERBASE_API_KEY,
+ BROWSERBASE_PROJECT_ID,
+ HYPERBROWSER_API_KEY,
+ setup_browser_session,
+)
+from .comprehensive_judge import evaluate_task_with_comprehensive_judge
+from .cookies import check_login_cookie_at_step, evaluate_task_with_login_cookie, save_login_cookie_tracking
+from .models import SUPPORTED_MODELS, get_llm
+from .resource_monitoring import (
+ get_system_resources,
+ log_system_resources,
+ setup_signal_handlers,
+ start_resource_monitoring,
+ stop_resource_monitoring,
+)
+from .server import (
+ fetch_auth_distribution_from_server,
+ fetch_tasks_from_server,
+ format_auth_info_for_agent,
+ save_task_result_to_server,
+ send_progress_update,
+ start_new_run,
+)
+from .types import Stage, StageError, Task, TaskResult
+from .utils import get_git_info
+from .web_judge import Online_Mind2Web_eval_with_retry
+
+# ================================================
+# Setup Logging
+# ================================================
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(name)s: %(message)s')
logger = logging.getLogger(__name__)
+# ================================================
+# Environment variables
+# ================================================
+
# Load dotenv
load_dotenv()
-# Check for Anchor Browser API key
-ANCHOR_BROWSER_API_KEY = os.getenv('ANCHOR_BROWSER_API_KEY')
-if ANCHOR_BROWSER_API_KEY:
- logger.info('ANCHOR_BROWSER_API_KEY is set. Tasks can use Anchor Browser.')
-else:
- logger.warning('ANCHOR_BROWSER_API_KEY is not set. Anchor Browser will not be available.')
-
-# Check for Brightdata CDP URL
-BRIGHTDATA_CDP_URL = os.getenv('BRIGHTDATA_CDP_URL')
-if BRIGHTDATA_CDP_URL:
- logger.info('BRIGHTDATA_CDP_URL is set. Tasks can use Brightdata browser.')
-else:
- logger.warning('BRIGHTDATA_CDP_URL is not set. Brightdata browser will not be available.')
-
-# Check for Browserbase API key
-BROWSERBASE_API_KEY = os.getenv('BROWSERBASE_API_KEY')
-BROWSERBASE_PROJECT_ID = os.getenv('BROWSERBASE_PROJECT_ID')
-if BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID:
- logger.info('BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID are set. Tasks can use Browserbase.')
-else:
- logger.warning('BROWSERBASE_API_KEY or BROWSERBASE_PROJECT_ID are not set. Browserbase will not be available.')
-
-# Check for Hyperbrowser API key
-HYPERBROWSER_API_KEY = os.getenv('HYPERBROWSER_API_KEY')
-if HYPERBROWSER_API_KEY:
- logger.info('HYPERBROWSER_API_KEY is set. Tasks can use Hyperbrowser.')
-else:
- logger.warning('HYPERBROWSER_API_KEY is not set. Hyperbrowser will not be available.')
-
-
-def create_anchor_browser_session(headless: bool = False) -> str:
- """Create an Anchor Browser session and return CDP URL"""
- if not ANCHOR_BROWSER_API_KEY:
- raise ValueError('ANCHOR_BROWSER_API_KEY must be set')
-
- browser_configuration = {
- 'session': {'proxy': {'type': 'anchor_mobile', 'active': True, 'country_code': 'us'}},
- 'browser': {
- 'adblock': {'active': True},
- 'captcha_solver': {'active': True},
- 'headless': {'active': headless},
- 'extra_stealth': {'active': True},
- },
- }
-
- try:
- response = requests.post(
- 'https://api.anchorbrowser.io/v1/sessions',
- headers={
- 'anchor-api-key': ANCHOR_BROWSER_API_KEY,
- 'Content-Type': 'application/json',
- },
- json=browser_configuration,
- )
- response.raise_for_status()
- session_data = response.json()['data']
- session_id = session_data['id']
-
- return f'wss://connect.anchorbrowser.io?apiKey={ANCHOR_BROWSER_API_KEY}&sessionId={session_id}'
-
- except requests.RequestException as e:
- logger.error(f'Failed to create Anchor Browser session: {type(e).__name__}: {e}')
- raise
- except KeyError as e:
- logger.error(f'Unexpected response format from Anchor Browser API: {e}')
- raise
-
-
-def create_browserbase_session() -> str:
- """Create a Browserbase session and return CDP URL"""
- if not BROWSERBASE_API_KEY or not BROWSERBASE_PROJECT_ID:
- raise ValueError('BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID must be set')
-
- try:
- from browserbase import Browserbase
- except ImportError:
- raise ImportError(
- 'browserbase package is required for Browserbase functionality. Install it with: pip install browserbase'
- )
-
- try:
- bb = Browserbase(api_key=BROWSERBASE_API_KEY)
- session = bb.sessions.create(
- project_id=BROWSERBASE_PROJECT_ID,
- browser_settings={
- 'advanced_stealth': True,
- },
- )
-
- return session.connect_url
-
- except Exception as e:
- logger.error(f'Failed to create Browserbase session: {type(e).__name__}: {e}')
- raise
-
-
-async def create_hyperbrowser_session() -> str:
- """Create a Hyperbrowser session and return WebSocket endpoint"""
- if not HYPERBROWSER_API_KEY:
- raise ValueError('HYPERBROWSER_API_KEY must be set')
-
- try:
- from hyperbrowser import AsyncHyperbrowser
- from hyperbrowser.models import CreateSessionParams
- except ImportError:
- raise ImportError(
- 'hyperbrowser package is required for Hyperbrowser functionality. Install it with: pip install hyperbrowser'
- )
-
- try:
- client = AsyncHyperbrowser(api_key=HYPERBROWSER_API_KEY)
-
- session = await client.sessions.create(
- params=CreateSessionParams(
- use_stealth=True,
- )
- )
-
- await client.close()
-
- return session.ws_endpoint or ''
+# Check for SERPER API key
+SERPER_API_KEY = os.getenv('SERPER_API_KEY')
+if not SERPER_API_KEY:
+ logger.warning('SERPER_API_KEY is not set. Search functionality will not be available.')
- except Exception as e:
- logger.error(f'Failed to create Hyperbrowser session: {type(e).__name__}: {e}')
- raise
+# ================================================
+# Tracking and Observations
+# ================================================
Laminar.initialize()
laminar_client = AsyncLaminarClient()
-# Global variables for resource monitoring
-_resource_monitor_task = None
-_resource_monitor_stop_event = None
-_graceful_shutdown_initiated = False
-
-# Global tracking for login cookie monitoring
-_login_cookie_tracker = {}
-
-
-def get_system_resources():
- """Get current system resource usage"""
- try:
- # Memory usage
- memory = psutil.virtual_memory()
- memory_percent = memory.percent
- memory_available_gb = memory.available / (1024**3)
-
- # CPU usage
- cpu_percent = psutil.cpu_percent(interval=1)
-
- # Load average (Unix only)
- try:
- load_avg = psutil.getloadavg()
- load_1min = load_avg[0]
- except (AttributeError, OSError):
- load_1min = 0.0
-
- # Process count
- process_count = len(psutil.pids())
-
- # Chrome/Browser processes
- chrome_processes = []
- python_processes = []
- for proc in psutil.process_iter(['pid', 'name', 'memory_percent', 'cpu_percent']):
- try:
- name = proc.info['name'].lower()
- if 'chrome' in name or 'chromium' in name:
- chrome_processes.append(proc.info)
- elif 'python' in name:
- python_processes.append(proc.info)
- except (psutil.NoSuchProcess, psutil.AccessDenied):
- continue
-
- return {
- 'memory_percent': memory_percent,
- 'memory_available_gb': memory_available_gb,
- 'cpu_percent': cpu_percent,
- 'load_1min': load_1min,
- 'process_count': process_count,
- 'chrome_process_count': len(chrome_processes),
- 'python_process_count': len(python_processes),
- 'chrome_processes': chrome_processes[:5], # Top 5 chrome processes
- 'python_processes': python_processes[:5], # Top 5 python processes
- }
- except Exception as e:
- logger.warning(f'Failed to get system resources: {type(e).__name__}: {e}')
- return {
- 'memory_percent': 0,
- 'memory_available_gb': 0,
- 'cpu_percent': 0,
- 'load_1min': 0,
- 'process_count': 0,
- 'chrome_process_count': 0,
- 'python_process_count': 0,
- 'chrome_processes': [],
- 'python_processes': [],
- }
-
-
-def log_system_resources(context: str = ''):
- """Log current system resource usage"""
- resources = get_system_resources()
- logger.info(f'=== SYSTEM RESOURCES {context} ===')
- logger.info(f'Memory: {resources["memory_percent"]:.1f}% used, {resources["memory_available_gb"]:.2f}GB available')
- logger.info(f'CPU: {resources["cpu_percent"]:.1f}%, Load: {resources["load_1min"]:.2f}')
- logger.info(
- f'Processes: {resources["process_count"]} total, {resources["chrome_process_count"]} Chrome, {resources["python_process_count"]} Python'
- )
-
- if resources['chrome_processes']:
- logger.info('Top Chrome processes:')
- for proc in resources['chrome_processes']:
- logger.info(
- f' PID {proc["pid"]}: {proc["name"]} - CPU: {proc["cpu_percent"]:.1f}%, Memory: {proc["memory_percent"]:.1f}%'
- )
-
- logger.info('=' * (20 + len(context)))
-
-
-async def start_resource_monitoring(interval: int = 30):
- """Start background resource monitoring"""
- global _resource_monitor_task, _resource_monitor_stop_event
-
- if _resource_monitor_task is not None:
- logger.warning('Resource monitoring is already running')
- return
-
- _resource_monitor_stop_event = asyncio.Event()
-
- async def monitor_loop():
- """Background monitoring loop"""
- logger.info(f'Starting resource monitoring (interval: {interval}s)')
- try:
- while _resource_monitor_stop_event is not None and not _resource_monitor_stop_event.is_set():
- try:
- log_system_resources('MONITOR')
-
- # Check for concerning resource levels
- resources = get_system_resources()
- if resources['memory_percent'] > 85:
- logger.warning(f'⚠️ HIGH MEMORY USAGE: {resources["memory_percent"]:.1f}%')
- if resources['cpu_percent'] > 90:
- logger.warning(f'⚠️ HIGH CPU USAGE: {resources["cpu_percent"]:.1f}%')
- if resources['chrome_process_count'] > 20:
- logger.warning(f'⚠️ HIGH CHROME PROCESS COUNT: {resources["chrome_process_count"]}')
-
- # Force garbage collection periodically
- if resources['memory_percent'] > 70:
- logger.info('Running garbage collection due to high memory usage')
- gc.collect()
-
- except Exception as e:
- logger.error(f'Error in resource monitoring: {type(e).__name__}: {e}')
-
- try:
- if _resource_monitor_stop_event is not None:
- await asyncio.wait_for(_resource_monitor_stop_event.wait(), timeout=interval)
- else:
- await asyncio.sleep(interval)
- break # Event was set, exit loop
- except TimeoutError:
- continue # Timeout reached, continue monitoring
- except Exception as e:
- logger.error(f'Resource monitoring loop crashed: {type(e).__name__}: {e}')
- finally:
- logger.info('Resource monitoring stopped')
-
- _resource_monitor_task = asyncio.create_task(monitor_loop())
-
-
-async def stop_resource_monitoring():
- """Stop background resource monitoring"""
- global _resource_monitor_task, _resource_monitor_stop_event
-
- if _resource_monitor_stop_event is not None:
- _resource_monitor_stop_event.set()
-
- if _resource_monitor_task is not None:
- try:
- await asyncio.wait_for(_resource_monitor_task, timeout=5.0)
- except TimeoutError:
- logger.warning('Resource monitoring task did not stop gracefully')
- _resource_monitor_task.cancel()
- try:
- await _resource_monitor_task
- except asyncio.CancelledError:
- pass
-
- _resource_monitor_task = None
- _resource_monitor_stop_event = None
-
-
-def setup_signal_handlers():
- """Setup signal handlers for graceful shutdown"""
- global _graceful_shutdown_initiated
-
- def signal_handler(signum, frame):
- global _graceful_shutdown_initiated
- if _graceful_shutdown_initiated:
- logger.critical('🔥 FORCE EXIT: Second signal received, terminating immediately')
- sys.exit(1)
-
- _graceful_shutdown_initiated = True
- logger.warning(f'⚠️ GRACEFUL SHUTDOWN: Received signal {signum}, initiating graceful shutdown...')
- log_system_resources('SHUTDOWN')
-
- # Try to stop resource monitoring
- try:
- loop = asyncio.get_event_loop()
- if loop.is_running():
- loop.create_task(stop_resource_monitoring())
- except Exception as e:
- logger.error(f'Failed to stop resource monitoring during shutdown: {e}')
-
- # Give some time for cleanup, then force exit
- def force_exit():
- time.sleep(10)
- if _graceful_shutdown_initiated:
- logger.critical('🔥 FORCE EXIT: Graceful shutdown timeout, terminating')
- sys.exit(1)
-
- threading.Thread(target=force_exit, daemon=True).start()
-
- # Register signal handlers
- signal.signal(signal.SIGINT, signal_handler)
- signal.signal(signal.SIGTERM, signal_handler)
-
-
-def encode_image(image):
- """Convert a PIL image to base64 string."""
- if image.mode == 'RGBA':
- image = image.convert('RGB')
- buffered = io.BytesIO()
- image.save(buffered, format='JPEG')
- return base64.b64encode(buffered.getvalue()).decode('utf-8')
-
-
-async def identify_key_points(task, model):
- system_msg = """You are an expert tasked with analyzing a given task to identify the key points explicitly stated in the task description.
-
-**Objective**: Carefully analyze the task description and extract the critical elements explicitly mentioned in the task for achieving its goal.
-
-**Instructions**:
-1. Read the task description carefully.
-2. Identify and extract **key points** directly stated in the task description.
- - A **key point** is a critical element, condition, or step explicitly mentioned in the task description.
- - Do not infer or add any unstated elements.
- - Words such as "best," "highest," "cheapest," "latest," "most recent," "lowest," "closest," "highest-rated," "largest," and "newest" must go through the sort function(e.g., the key point should be "Filter by highest").
-
-**Respond with**:
-- **Key Points**: A numbered list of the explicit key points for completing this task, one per line, without explanations or additional details."""
- prompt = """Task: {task}"""
- text = prompt.format(task=task)
- messages = [
- {'role': 'system', 'content': system_msg},
- {
- 'role': 'user',
- 'content': [{'type': 'text', 'text': text}],
- },
- ]
- response = await model.ainvoke(messages)
- return response.completion
-
-
-async def judge_image(task, image_path, key_points, model):
- system_msg = """You are an expert evaluator tasked with determining whether an image contains information about the necessary steps to complete a task.
-
-**Objective**: Analyze the provided image and decide if it shows essential steps or evidence required for completing the task. Use your reasoning to explain your decision before assigning a score.
-
-**Instructions**:
-1. Provide a detailed description of the image, including its contents, visible elements, text (if any), and any notable features.
-
-2. Carefully examine the image and evaluate whether it contains necessary steps or evidence crucial to task completion:
-- Identify key points that could be relevant to task completion, such as actions, progress indicators, tool usage, applied filters, or step-by-step instructions.
-- Does the image show actions, progress indicators, or critical information directly related to completing the task?
-- Is this information indispensable for understanding or ensuring task success?
-- If the image contains partial but relevant information, consider its usefulness rather than dismissing it outright.
-
-3. Provide your response in the following format:
-- **Reasoning**: Explain your thought process and observations. Mention specific elements in the image that indicate necessary steps, evidence, or lack thereof.
-- **Score**: Assign a score based on the reasoning, using the following scale:
- - **1**: The image does not contain any necessary steps or relevant information.
- - **2**: The image contains minimal or ambiguous information, unlikely to be essential.
- - **3**: The image includes some relevant steps or hints but lacks clarity or completeness.
- - **4**: The image contains important steps or evidence that are highly relevant but not fully comprehensive.
- - **5**: The image clearly displays necessary steps or evidence crucial for completing the task.
-
-Respond with:
-1. **Reasoning**: [Your explanation]
-2. **Score**: [1-5]"""
-
- jpg_base64_str = encode_image(Image.open(image_path))
-
- prompt = """**Task**: {task}
-
-**Key Points for Task Completion**: {key_points}
-
-The snapshot of the web page is shown in the image."""
- text = prompt.format(task=task, key_points=key_points)
-
- messages = [
- {'role': 'system', 'content': system_msg},
- {
- 'role': 'user',
- 'content': [
- {'type': 'text', 'text': text},
- {
- 'type': 'image_url',
- 'image_url': {'url': f'data:image/jpeg;base64,{jpg_base64_str}', 'detail': 'high'},
- },
- ],
- },
- ]
- response = await model.ainvoke(messages)
- return response.completion
-
-
-async def Online_Mind2Web_eval(task, last_actions, images_path, model, score_threshold):
- system_msg = """You are an expert in evaluating the performance of a web navigation agent. The agent is designed to help a human user navigate a website to complete a task. Given the user's task, the agent's action history, key points for task completion, some potentially important web pages in the agent's trajectory and their reasons, your goal is to determine whether the agent has completed the task and achieved all requirements.
-
-Your response must strictly follow the following evaluation criteria!
-*Important Evaluation Criteria*:
-1: The filtered results must be displayed correctly. If filters were not properly applied (i.e., missing selection, missing confirmation, or no visible effect in results), the task is not considered successful.
-2: You must carefully check whether these snapshots and action history meet these key points. Ensure that specific filter conditions, such as "best," "highest," "cheapest," "latest," "most recent," "lowest," "closest," "highest-rated," "largest," and "newest" are correctly applied using the filter function(e.g., sort function).
-3: Certain key points or requirements should be applied by the filter. Otherwise, a search with all requirements as input will be deemed a failure since it cannot guarantee that all results meet the requirements!
-4: If the task requires filtering by a specific range of money, years, or the number of beds and bathrooms, the applied filter must exactly match the given requirement. Any deviation results in failure. To ensure the task is successful, the applied filter must precisely match the specified range without being too broad or too narrow.
-Examples of Failure Cases:
-- If the requirement is less than $50, but the applied filter is less than $25, it is a failure.
-- If the requirement is $1500-$2500, but the applied filter is $2000-$2500, it is a failure.
-- If the requirement is $25-$200, but the applied filter is $0-$200, it is a failure.
-- If the required years are 2004-2012, but the filter applied is 2001-2012, it is a failure.
-- If the required years are before 2015, but the applied filter is 2000-2014, it is a failure.
-- If the task requires exactly 2 beds, but the filter applied is 2+ beds, it is a failure.
-5: Some tasks require a submission action or a display of results to be considered successful.
-6: If the retrieved information is invalid or empty(e.g., No match was found), but the agent has correctly performed the required action, it should still be considered successful.
-7: If the current page already displays all available items, then applying a filter is not necessary. As long as the agent selects items that meet the requirements (e.g., the cheapest or lowest price), the task is still considered successful.
-
-*IMPORTANT*
-Format your response into two lines as shown below:
-
-Thoughts: <your thoughts and reasoning process based on double-checking each key points and the evaluation criteria>
-Status: "success" or "failure"
-"""
- prompt = """User Task: {task}
-
-Key Points: {key_points}
+# Resource monitoring functions moved to resource_monitoring.py module
-Action History:
-{last_actions}
-The potentially important snapshots of the webpage in the agent's trajectory and their reasons:
-{thoughts}"""
-
- key_points = await identify_key_points(task, model)
- key_points = key_points.replace('\n\n', '\n')
-
- try:
- key_points = key_points.split('**Key Points**:')[1]
- key_points = '\n'.join(line.lstrip() for line in key_points.splitlines())
- except IndexError:
- key_points = key_points.split('Key Points:')[-1]
- key_points = '\n'.join(line.lstrip() for line in key_points.splitlines())
-
- tasks = [judge_image(task, image_path, key_points, model) for image_path in images_path]
- image_responses = await asyncio.gather(*tasks)
-
- whole_content_img = []
- whole_thoughts = []
- record = []
- pattern = r'[1-5]'
- for response, image_path in zip(image_responses, images_path):
- try:
- score_text = response.split('Score')[1]
- thought = response.split('**Reasoning**:')[-1].strip().lstrip('\n').split('\n\n')[0].replace('\n', ' ')
- score = re.findall(pattern, score_text)[0]
- record.append({'Response': response, 'Score': int(score)})
- except Exception as e:
- logger.error(f'Error processing response: {type(e).__name__}: {e}')
- score = 0
- record.append({'Response': response, 'Score': 0})
-
- if int(score) >= score_threshold:
- jpg_base64_str = encode_image(Image.open(image_path))
- whole_content_img.append(
- {'type': 'image_url', 'image_url': {'url': f'data:image/png;base64,{jpg_base64_str}', 'detail': 'high'}}
- )
- if thought != '':
- whole_thoughts.append(thought)
-
- whole_content_img = whole_content_img[:MAX_IMAGE]
- whole_thoughts = whole_thoughts[:MAX_IMAGE]
- if len(whole_content_img) == 0:
- prompt = """User Task: {task}
-
-Key Points: {key_points}
-
-Action History:
-{last_actions}"""
- text = prompt.format(
- task=task,
- last_actions='\n'.join(f'{i + 1}. {action}' for i, action in enumerate(last_actions)),
- key_points=key_points,
- thoughts='\n'.join(f'{i + 1}. {thought}' for i, thought in enumerate(whole_thoughts)),
- )
-
- messages = [
- {'role': 'system', 'content': system_msg},
- {'role': 'user', 'content': [{'type': 'text', 'text': text}] + whole_content_img},
- ]
- return messages, text, system_msg, record, key_points
-
-
-async def Online_Mind2Web_eval_with_retry(task, last_actions, images_path, model, score_threshold, max_retries=3):
- """
- Wrapper for Online_Mind2Web_eval with retry logic.
-
- Args:
- task: The task description
- last_actions: list of actions taken
- images_path: list of image paths
- model: The model to use for evaluation
- score_threshold: Score threshold for image filtering
- max_retries: Maximum number of retry attempts
-
- Returns:
- Tuple of (messages, text, system_msg, record, key_points) or None if all retries fail
- """
- for attempt in range(max_retries):
- try:
- return await Online_Mind2Web_eval(task, last_actions, images_path, model, score_threshold)
- except Exception as e:
- if attempt == max_retries - 1: # Last attempt
- logger.error(f'Failed to evaluate after {max_retries} attempts. Error: {type(e).__name__}: {str(e)}')
- raise
- logger.warning(f'Attempt {attempt + 1} failed. Retrying... Error: {type(e).__name__}: {str(e)}')
- await asyncio.sleep(2**attempt) # Exponential backoff
-
-
-# ==============================================================================================================
-
-
-# ==============================================================================================================
-# A service for evaluating the performance of the agent
-# ==============================================================================================================
-import argparse
-import http.client
-import os
-import subprocess
-from dataclasses import dataclass, field
-
-# Define Stage enum and related classes for the pipeline
-from enum import Enum
-from typing import Any
-
-from dotenv import load_dotenv
-
-# Import the new comprehensive judge system (conditional import for backwards compatibility)
-try:
- from judge_system import evaluate_task_with_comprehensive_judge
-
- COMPREHENSIVE_JUDGE_AVAILABLE = True
-except ImportError:
- logger.warning('Comprehensive judge system not available. Only Mind2Web judge will be available.')
- COMPREHENSIVE_JUDGE_AVAILABLE = False
-
- async def evaluate_task_with_comprehensive_judge(*args, **kwargs) -> dict[str, Any]:
- """Fallback function when comprehensive judge system is not available"""
- raise ImportError('Comprehensive judge system not available')
-
-
-class Stage(Enum):
- SETUP_BROWSER = 'setup_browser'
- RUN_AGENT = 'run_agent'
- FORMAT_HISTORY = 'format_history'
- EVALUATE = 'evaluate'
- SAVE_SERVER = 'save_server'
-
-
-@dataclass
-class StageError:
- stage: Stage
- error_type: str
- message: str
-
-
-@dataclass
-class TaskResult:
- task_id: str
- run_id: str
- confirmed_task: str
- task: Any
- max_steps: int
- laminar_link: str | None = None
- github_workflow_url: str | None = None
- completed_stages: set[Stage] = field(default_factory=set)
- stage_data: dict[Stage, Any] = field(default_factory=dict)
- errors: list = field(default_factory=list)
- cancelled: bool = False
- critical_error: str | None = None
- server_save_failed: bool = False
-
- def stage_completed(self, stage: Stage, data: Any = None):
- self.completed_stages.add(stage)
- if data is not None:
- self.stage_data[stage] = data
-
- def stage_failed(self, stage: Stage, error: StageError):
- self.errors.append(error)
-
- def mark_cancelled(self):
- self.cancelled = True
-
- def mark_critical_error(self, error: str):
- self.critical_error = error
-
- def mark_server_save_failed(self, error: str):
- self.server_save_failed = True
- self.errors.append(StageError(Stage.SAVE_SERVER, 'server_save', error))
-
- def has_execution_data(self) -> bool:
- return Stage.RUN_AGENT in self.completed_stages or Stage.FORMAT_HISTORY in self.completed_stages
-
- @property
- def server_payload(self) -> dict[str, Any]:
- """Generate payload for server submission"""
- payload = {
- 'taskId': self.task_id,
- 'runId': self.run_id,
- 'task': self.confirmed_task,
- 'completed_stages': [stage.value for stage in self.completed_stages],
- 'has_errors': len(self.errors) > 0,
- 'cancelled': self.cancelled,
- 'critical_error': self.critical_error,
- 'server_save_failed': self.server_save_failed,
- 'laminarTaskLink': self.laminar_link,
- 'githubWorkflowUrl': self.github_workflow_url,
- }
-
- # Add task execution data if available
- if Stage.FORMAT_HISTORY in self.completed_stages:
- format_data = self.stage_data.get(Stage.FORMAT_HISTORY, {})
- logger.info(f'format_data: {format_data}')
- # log token usage
- logger.info(f'tokensUsed: {format_data.get("tokensUsed")}')
- logger.info(f'usage: {format_data.get("usage")}')
-
- # Handle usage data - convert to JSON string if it's a dict
- usage_data = format_data.get('usage')
- if usage_data and isinstance(usage_data, dict):
- usage_data = json.dumps(usage_data)
-
- payload.update(
- {
- 'actionHistory': format_data.get('action_history', []),
- 'finalResultResponse': format_data.get('final_result_response', ''),
- 'selfReportCompleted': format_data.get('self_report_completed', False),
- 'selfReportSuccess': format_data.get('self_report_success', False),
- 'taskDuration': format_data.get('task_duration'),
- 'steps': format_data.get('steps'),
- 'maxSteps': self.max_steps,
- 'tokensUsed': format_data.get('tokensUsed'),
- 'usage': usage_data, # Add usage data (JSON string if dict)
- 'completeHistory': format_data.get('complete_history', []), # Add complete step history
- }
- )
-
- # Add evaluation data if available
- if Stage.EVALUATE in self.completed_stages:
- eval_data = self.stage_data.get(Stage.EVALUATE, {})
-
- # Handle comprehensive judge evaluation
- comp_eval = eval_data.get('comprehensive_evaluation') or eval_data.get('comprehensive_judge')
- if comp_eval:
- # Convert enum lists to string lists for database storage
- task_categories = comp_eval.get('task_categories', [])
- if task_categories and hasattr(task_categories[0], 'value'):
- task_categories = [cat.value for cat in task_categories]
-
- error_categories = comp_eval.get('error_categories', [])
- if error_categories and hasattr(error_categories[0], 'value'):
- error_categories = [err.value for err in error_categories]
-
- payload.update(
- {
- 'comprehensiveJudgeEvaluationSummary': comp_eval.get('task_summary'),
- 'comprehensiveJudgeEvaluationReasoning': comp_eval.get('reasoning'),
- 'comprehensiveJudgeEvaluationPassed': comp_eval.get('passed'),
- 'comprehensiveJudgeEvaluationScore': comp_eval.get('final_score'),
- 'comprehensiveJudgeEvaluationCategories': task_categories,
- 'comprehensiveJudgeEvaluationErrors': error_categories,
- 'comprehensiveJudgeEvaluationTips': comp_eval.get('improvement_tips', []),
- 'comprehensiveJudgeEvaluationCriticalIssues': comp_eval.get('critical_issues', []),
- 'comprehensiveJudgeEvaluationScores': comp_eval.get('scores'),
- 'comprehensiveJudgeEvaluationFull': comp_eval, # Include full comprehensive eval data
- }
- )
-
- # Handle legacy Mind2Web evaluation (for compatibility)
- payload.update(
- {
- 'onlineMind2WebEvaluationJudgement': eval_data.get('judgement') or 'No evaluation available',
- 'onlineMind2WebEvaluationError': eval_data.get('error'),
- 'onlineMind2WebEvaluationSuccess': eval_data.get('success', False),
- 'onlineMind2WebEvaluationScore': eval_data.get('score', 0.0),
- }
- )
-
- # Ensure all data in payload is JSON serializable
- serialized_payload = make_json_serializable(payload)
- # Type assertion since we know payload is a dict and make_json_serializable preserves dict structure
- assert isinstance(serialized_payload, dict), 'Payload serialization should preserve dict structure'
- return serialized_payload
-
- def get_local_status(self) -> dict[str, Any]:
- """Get local status summary"""
- success = (
- Stage.EVALUATE in self.completed_stages
- and not self.cancelled
- and self.critical_error is None
- and len([e for e in self.errors if e.error_type == 'exception']) == 0
- )
- return {
- 'task_id': self.task_id,
- 'success': success,
- 'error': self.critical_error or (self.errors[0].message if self.errors else None),
- 'completed_stages': [stage.value for stage in self.completed_stages],
- }
-
-
-from browser_use import ActionResult, Agent, BrowserProfile, BrowserSession, Controller
-from browser_use.agent.views import AgentHistoryList
-
-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.5-haiku-latest': {
- 'provider': 'anthropic',
- 'model_name': 'claude-3-5-haiku-latest',
- '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',
- },
- 'claude-sonnet-4': {
- 'provider': 'anthropic',
- 'model_name': 'claude-sonnet-4-20250514',
- 'api_key_env': 'ANTHROPIC_API_KEY',
- },
- 'claude-opus-4': {
- 'provider': 'anthropic',
- 'model_name': 'claude-opus-4-20250514',
- '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-lite': {'provider': 'google', 'model_name': 'gemini-2.0-flash-lite', 'api_key_env': 'GEMINI_API_KEY'},
- 'gemini-2.0-flash': {
- 'provider': 'google',
- 'model_name': 'gemini-2.0-flash',
- 'api_key_env': 'GEMINI_API_KEY',
- 'thinking_budget': 0,
- },
- 'gemini-2.5-pro': {'provider': 'google', 'model_name': 'gemini-2.5-pro', 'api_key_env': 'GEMINI_API_KEY'},
- 'gemini-2.5-flash': {
- 'provider': 'google',
- 'model_name': 'gemini-2.5-flash',
- 'api_key_env': 'GEMINI_API_KEY',
- 'thinking_budget': 0,
- },
- 'gemini-2.5-flash-lite-preview': {
- 'provider': 'google',
- 'model_name': 'gemini-2.5-flash-lite-preview-06-17',
- 'api_key_env': 'GEMINI_API_KEY',
- 'thinking_budget': 0,
- },
- 'gemini-2.5-pro-preview-05-06': {
- 'provider': 'google',
- 'model_name': 'gemini-2.5-pro-preview-05-06',
- 'api_key_env': 'GEMINI_API_KEY',
- },
- 'gemini-2.5-flash-preview': {
- 'provider': 'google',
- 'model_name': 'gemini-2.5-flash-preview-04-17',
- '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-4.1-mini': {'provider': 'openai', 'model_name': 'gpt-4.1-mini-2025-04-14', 'api_key_env': 'OPENAI_API_KEY'},
- 'gpt-o3': {'provider': 'openai', 'model_name': 'o3-2025-04-16', 'api_key_env': 'OPENAI_API_KEY'},
- 'gpt-4.1-nano': {'provider': 'openai', 'model_name': 'gpt-4.1-nano-2025-04-14', 'api_key_env': 'OPENAI_API_KEY'},
- 'gpt-4o': {'provider': 'openai', 'model_name': 'gpt-4o', 'api_key_env': 'OPENAI_API_KEY'},
- 'gpt-4o-mini': {'provider': 'openai', 'model_name': 'gpt-4o-mini', 'api_key_env': 'OPENAI_API_KEY'},
- 'gpt-o4-mini': {'provider': 'openai', 'model_name': 'o4-mini', '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',
- },
- # Groq
- 'gemma2-9b-it': {
- 'provider': 'groq',
- 'model_name': 'gemma2-9b-it',
- 'api_key_env': 'GROQ_API_KEY',
- 'service_tier': 'auto',
- },
- 'llama-3.3-70b-versatile': {
- 'provider': 'groq',
- 'model_name': 'llama-3.3-70b-versatile',
- 'api_key_env': 'GROQ_API_KEY',
- 'service_tier': 'auto',
- },
- 'llama-3.1-8b-instant': {
- 'provider': 'groq',
- 'model_name': 'llama-3.1-8b-instant',
- 'api_key_env': 'GROQ_API_KEY',
- 'service_tier': 'auto',
- },
- 'llama3-70b-8192': {
- 'provider': 'groq',
- 'model_name': 'llama3-70b-8192',
- 'api_key_env': 'GROQ_API_KEY',
- 'service_tier': 'auto',
- },
- 'llama3-8b-8192': {
- 'provider': 'groq',
- 'model_name': 'llama3-8b-8192',
- 'api_key_env': 'GROQ_API_KEY',
- 'service_tier': 'auto',
- },
- # Groq Preview
- 'llama-4-maverick': {
- 'provider': 'groq',
- 'model_name': 'meta-llama/llama-4-maverick-17b-128e-instruct',
- 'api_key_env': 'GROQ_API_KEY',
- 'service_tier': 'auto',
- },
- 'llama-4-scout': {
- 'provider': 'groq',
- 'model_name': 'meta-llama/llama-4-scout-17b-16e-instruct',
- 'api_key_env': 'GROQ_API_KEY',
- 'service_tier': 'auto',
- },
- # SambaNova
- 'deepseek-r1-sambanova': {
- 'provider': 'openai_compatible',
- 'model_name': 'DeepSeek-R1',
- 'base_url': 'https://api.sambanova.ai/v1',
- 'api_key_env': 'SAMBANOVA_API_KEY',
- },
- 'llama-4-maverick-sambanova': {
- 'provider': 'openai_compatible',
- 'model_name': 'Llama-4-Maverick-17B-128E-Instruct',
- 'base_url': 'https://api.sambanova.ai/v1',
- 'api_key_env': 'SAMBANOVA_API_KEY',
- },
-}
-
-# Check for SERPER API key
-SERPER_API_KEY = os.getenv('SERPER_API_KEY')
-if not SERPER_API_KEY:
- logger.warning('SERPER_API_KEY is not set. Search functionality will not be available.')
+# ================================================
+# Custom Controllers
+# ================================================
def create_controller_with_serp_search(output_model: type[BaseModel] | None = None):
@@ -1076,92 +190,15 @@ def create_controller(
return controller
-def get_llm(model_name: str):
- """Instantiates the correct 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:
- 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
-
- match provider:
- case 'openai':
- kwargs = {'model': config['model_name'], 'temperature': 0.0}
- # Must set temperatue=1 if model is gpt-o4-mini
- if model_name in ['gpt-o4-mini', 'gpt-o3']:
- kwargs['temperature'] = 1
- if api_key:
- kwargs['api_key'] = api_key
- return ChatOpenAI(**kwargs)
- case 'anthropic':
- kwargs = {
- 'model': config['model_name'],
- 'temperature': 0.0,
- 'timeout': 100,
- }
- if api_key:
- kwargs['api_key'] = api_key
- return ChatAnthropic(**kwargs)
- case 'google':
- kwargs = {'model': config['model_name'], 'temperature': 0.0, 'thinking_budget': config.get('thinking_budget', None)}
- if api_key:
- kwargs['api_key'] = api_key
- return ChatGoogle(**kwargs)
- case 'groq':
- kwargs = {
- 'model': config['model_name'],
- 'temperature': 0.0,
- 'service_tier': config.get('service_tier', 'auto'),
- }
- if api_key:
- kwargs['api_key'] = api_key
- return ChatGroq(**kwargs)
- case 'openai_compatible':
- kwargs = {'model': config['model_name'], 'base_url': config['base_url'], 'temperature': 0.0}
- if api_key:
- kwargs['api_key'] = api_key
- elif config.get('base_url'):
- 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)
- case _:
- raise ValueError(f'Unknown provider: {provider}')
+# ================================================
+# Formatting results
+# ================================================
def clean_action_dict(action_dict: dict) -> dict:
return {k: clean_action_dict(v) if isinstance(v, dict) else v for k, v in action_dict.items() if v is not None}
-def make_json_serializable(obj: Any) -> Any:
- """
- Convert objects to JSON-serializable types.
- Handles common non-serializable types like enums, custom objects, etc.
- """
- if obj is None:
- return None
- elif isinstance(obj, (str, int, float, bool)):
- return obj
- elif isinstance(obj, dict):
- return {k: make_json_serializable(v) for k, v in obj.items()}
- elif isinstance(obj, (list, tuple)):
- return [make_json_serializable(item) for item in obj]
- elif hasattr(obj, 'value'): # Handle enums
- return obj.value
- elif hasattr(obj, '__dict__'): # Handle custom objects
- return str(obj)
- else:
- return str(obj)
-
-
async def reformat_agent_history(
agent_history: AgentHistoryList,
task_id: str,
@@ -1303,64 +340,9 @@ async def reformat_agent_history(
return results
-class Task:
- def __init__(self, task_id, confirmed_task, **kwargs):
- # Validate required fields
- if not task_id:
- raise ValueError('task_id is required and cannot be empty')
- if not confirmed_task:
- raise ValueError('confirmed_task is required and cannot be empty')
-
- # Set required fields
- self.task_id = task_id
- self.confirmed_task = confirmed_task
-
- # Set optional fields dynamically
- # Known optional fields with defaults
- self.website = kwargs.get('website', None)
- self.reference_length = kwargs.get('reference_length', None)
- self.level = kwargs.get('level', None)
- self.cluster_id = kwargs.get('cluster_id', None)
- self.login_cookie = kwargs.get('login_cookie', None)
- self.login_type = kwargs.get('login_type', None)
- self.category = kwargs.get('category', None)
- self.output_schema = kwargs.get('output_schema', None) # Add structured output schema support
- self.auth_keys = kwargs.get('auth_keys', None) # List of auth keys to fetch from auth distribution
- if self.output_schema:
- # Convert JSON schema to Pydantic model class
- self.output_model = create_pydantic_model_from_schema(self.output_schema, f'Task_{self.task_id}_Output')
- else:
- self.output_model = None
-
- # Store any additional optional fields
- known_fields = {
- 'website',
- 'reference_length',
- 'level',
- 'cluster_id',
- 'login_cookie',
- 'login_type',
- 'category',
- 'output_schema',
- 'auth_keys',
- }
- self.additional_fields = {k: v for k, v in kwargs.items() if k not in known_fields}
-
- # Make all additional fields accessible as attributes
- for key, value in self.additional_fields.items():
- setattr(self, key, value)
-
- def __str__(self):
- # Include main fields and indicate if there are additional fields
- base_str = f'Task(task_id={self.task_id}, confirmed_task={self.confirmed_task}, website={self.website}, reference_length={self.reference_length}, level={self.level}, cluster_id={self.cluster_id}, login_cookie={self.login_cookie}, login_type={self.login_type}, category={self.category}, output_schema={self.output_schema}, auth_keys={self.auth_keys}'
- if self.additional_fields:
- additional_str = ', '.join(f'{k}={v}' for k, v in self.additional_fields.items())
- base_str += f', {additional_str}'
- base_str += ')'
- return base_str
-
- def __repr__(self):
- return self.__str__()
+# ================================================
+# Judge task result
+# ================================================
async def judge_task_result(model, task_folder: Path, score_threshold: float = 3, use_mind2web: bool = False) -> dict:
@@ -1457,11 +439,6 @@ async def judge_task_result(model, task_folder: Path, score_threshold: float = 3
# Use the new comprehensive judge system (default)
logger.info(f'Task {task_folder.name}: Using comprehensive judge evaluation')
- # Check if comprehensive judge is available
- if not COMPREHENSIVE_JUDGE_AVAILABLE:
- logger.warning(f'Task {task_folder.name}: Comprehensive judge not available, falling back to Mind2Web')
- return await judge_task_result(model, task_folder, score_threshold, use_mind2web=True)
-
# Check if comprehensive judge result already exists
if result.get('comprehensive_judge_evaluation'):
existing_eval = result['comprehensive_judge_evaluation']
@@ -1529,140 +506,9 @@ async def judge_task_result(model, task_folder: Path, score_threshold: float = 3
}
-async def run_stage(stage: Stage, stage_func, timeout: int | None = None):
- """Generic stage runner with timeout"""
- if timeout:
- return await asyncio.wait_for(stage_func(), timeout)
- return await stage_func()
-
-
-async def setup_browser_session(
- task: Task, headless: bool, highlight_elements: bool = True, browser: str = 'local'
-) -> BrowserSession:
- """Setup browser session for the task"""
-
- # Validate browser option
- valid_browsers = ['local', 'anchor-browser', 'brightdata', 'browserbase', 'hyperbrowser', 'browser-use']
- if browser not in valid_browsers:
- logger.warning(f'Browser setup: Invalid browser option "{browser}". Falling back to local browser.')
- browser = 'local'
-
- cdp_url = None
-
- if browser == 'anchor-browser':
- if ANCHOR_BROWSER_API_KEY:
- try:
- logger.debug(f'Browser setup: Creating Anchor Browser session for task {task.task_id}')
- cdp_url = await asyncio.to_thread(create_anchor_browser_session, headless)
- except Exception as e:
- logger.error(
- f'Browser setup: Failed to create Anchor Browser session for task {task.task_id}: {type(e).__name__}: {e}'
- )
- logger.info(f'Browser setup: Falling back to local browser for task {task.task_id}')
- cdp_url = None
- else:
- logger.warning(
- f'Browser setup: Anchor Browser requested but ANCHOR_BROWSER_API_KEY not set. Using local browser for task {task.task_id}'
- )
- elif browser == 'brightdata':
- if BRIGHTDATA_CDP_URL:
- logger.debug(f'Browser setup: Using Brightdata CDP URL for task {task.task_id}')
- cdp_url = BRIGHTDATA_CDP_URL
- else:
- logger.warning(
- f'Browser setup: Brightdata requested but BRIGHTDATA_CDP_URL not set. Using local browser for task {task.task_id}'
- )
- elif browser == 'browserbase':
- if BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID:
- try:
- logger.debug(f'Browser setup: Creating Browserbase session for task {task.task_id}')
- cdp_url = await asyncio.to_thread(create_browserbase_session)
- except Exception as e:
- logger.error(
- f'Browser setup: Failed to create Browserbase session for task {task.task_id}: {type(e).__name__}: {e}'
- )
- logger.info(f'Browser setup: Falling back to local browser for task {task.task_id}')
- cdp_url = None
- else:
- logger.warning(
- f'Browser setup: Browserbase requested but BROWSERBASE_API_KEY or BROWSERBASE_PROJECT_ID not set. Using local browser for task {task.task_id}'
- )
- elif browser == 'hyperbrowser':
- if HYPERBROWSER_API_KEY:
- try:
- logger.debug(f'Browser setup: Creating Hyperbrowser session for task {task.task_id}')
- cdp_url = await create_hyperbrowser_session()
- except Exception as e:
- logger.error(
- f'Browser setup: Failed to create Hyperbrowser session for task {task.task_id}: {type(e).__name__}: {e}'
- )
- logger.info(f'Browser setup: Falling back to local browser for task {task.task_id}')
- cdp_url = None
- else:
- logger.warning(
- f'Browser setup: Hyperbrowser requested but HYPERBROWSER_API_KEY not set. Using local browser for task {task.task_id}'
- )
- elif browser == 'browser-use':
- logger.warning(f'Browser setup: Browser-use not implemented yet. Falling back to local browser for task {task.task_id}')
-
- profile_kwargs = {
- 'user_data_dir': None, # Incognito mode - no persistent state
- 'headless': headless,
- 'chromium_sandbox': False, # running in docker
- 'highlight_elements': highlight_elements, # Control element highlighting (passed to profile)
- 'keep_alive': True,
- # higher timeouts = higher success rates on long tail of slow sites or if on a slow CI server
- # timeout=60_000,
- # default_timeout=60_000,
- # default_navigation_timeout=60_000,
- # wait_for_network_idle_page_load_time=60.0,
- # maximum_wait_page_load_time=60.0,
- # wait_between_actions=0.5,
- # ignore_https_errors=True, # some eval tasks have http:// or broken https sites in them
- }
-
- if hasattr(task, 'login_cookie') and task.login_cookie:
- # For login tasks, configure storage_state to save cookies to JSON file
- # Don't set user_data_dir=None for login tasks to avoid conflict
- task_folder = Path(f'saved_trajectories/{task.task_id}')
- task_folder.mkdir(parents=True, exist_ok=True)
-
- storage_state_path = task_folder / 'storage_state.json'
- # Create empty storage state file if it doesn't exist to avoid FileNotFoundError
- if not storage_state_path.exists():
- storage_state_path.write_text(json.dumps({'cookies': [], 'origins': []}))
-
- profile_kwargs['storage_state'] = str(storage_state_path)
- # Remove user_data_dir=None for login tasks to avoid conflict with storage_state
- profile_kwargs.pop('user_data_dir', None)
-
- downloads_dir_path = task_folder / 'downloads'
- downloads_dir_path.mkdir(parents=True, exist_ok=True)
- profile_kwargs['downloads_path'] = str(downloads_dir_path)
-
- logger.debug(f'Login task {task.task_id}: Configured to save cookies to {storage_state_path}')
-
- profile = BrowserProfile(**profile_kwargs)
-
- if cdp_url:
- logger.debug(f'Browser setup: Using CDP Browser for task {task.task_id}')
- browser_session = BrowserSession(browser_profile=profile, cdp_url=cdp_url)
- else:
- # Use local browser
- logger.debug(f'Browser setup: Initializing BrowserSession for task {task.task_id}')
- browser_session = BrowserSession(browser_profile=profile)
-
- # Start browser session
- await browser_session.start()
- logger.debug(f'Browser setup: Browser session started for task {task.task_id}')
-
- # Navigate to task starting url if provided
- # if task.website:
- # logger.debug(f'Browser setup: Navigating to {task.website} for task {task.task_id}')
- # await browser_session.navigate(task.website)
-
- logger.debug(f'Browser setup: Setup completed for task {task.task_id}')
- return browser_session
+# ================================================
+# Main Evaluation Functions
+# ================================================
@observe(name='executor', span_type='EXECUTOR') # type: ignore[arg-type]
@@ -1778,169 +624,6 @@ async def evaluate_task_result(
return await judge_task_result(eval_model, task_folder, score_threshold=3, use_mind2web=use_mind2web)
-async def evaluate_task_with_login_cookie(login_cookie: str, task_folder: Path) -> dict:
- """
- Evaluate a login task by checking if the login_cookie is present in browser cookies.
-
- First checks step-by-step tracking to see if the cookie was found during execution.
- If not found in tracking, falls back to checking end-state cookies.
-
- Args:
- login_cookie: String identifier that should appear in cookies if login was successful
- task_folder: Path to the task result folder containing saved cookies
-
- Returns:
- Dictionary containing evaluation results similar to Online_Mind2Web_eval format
- """
- task_id = task_folder.name
-
- # First, check if we have step-by-step tracking data
- tracking_file = task_folder / 'login_cookie_tracking.json'
- if tracking_file.exists():
- try:
- async with await anyio.open_file(tracking_file) as f:
- tracking_data = json.loads(await f.read())
-
- if tracking_data.get('found', False):
- # Cookie was found during execution!
- step_found = tracking_data.get('step', 'unknown')
- match_type = tracking_data.get('match_type', 'unknown')
- cookie_name = tracking_data.get('cookie_name', 'unknown')
-
- success = True
- score = 1.0
- judgement = f"Automatic judgement: Login cookie '{login_cookie}' was found during step {step_found} ({match_type} match on '{cookie_name}')"
- error = None
-
- logger.info(
- f"✅ Cookie evaluation result from step tracking: success={success} for login_cookie='{login_cookie}'"
- )
-
- return {
- 'task_id': task_id,
- 'judgement': judgement,
- 'success': success,
- 'error': error,
- 'score': score,
- 'tracking_data': tracking_data,
- }
- except Exception as e:
- logger.warning(f'Failed to load login cookie tracking: {e}')
-
- # Fallback to end-state cookie checking (original behavior)
- logger.info(f'🔄 No step-by-step tracking found for task {task_id}, falling back to end-state cookie checking')
-
- # Look for cookies in saved_trajectories (saved by browser-use during shutdown)
- cookies_file = task_folder / 'cookies.json'
- storage_state_file = task_folder / 'storage_state.json'
-
- cookies_data = None
- cookies_source = None
-
- # Try to load cookies from storage_state.json first (newer format)
- if storage_state_file.exists():
- try:
- async with await anyio.open_file(storage_state_file) as f:
- storage_state = json.loads(await f.read())
- cookies_data = storage_state.get('cookies', [])
- cookies_source = 'storage_state.json'
- except Exception as e:
- logger.warning(f'Failed to load storage_state.json: {e}')
-
- # Fallback to cookies.json (older format)
- if not cookies_data and cookies_file.exists():
- try:
- async with await anyio.open_file(cookies_file) as f:
- cookies_data = json.loads(await f.read())
- cookies_source = 'cookies.json'
- except Exception as e:
- logger.warning(f'Failed to load cookies.json: {e}')
-
- if not cookies_data:
- return {
- 'task_id': task_id,
- 'judgement': 'Automatic judgement: No cookies saved for evaluation and no step-by-step tracking',
- 'success': False,
- 'error': 'No cookies file found for login task evaluation and no step-by-step tracking',
- 'score': 0.0,
- }
-
- logger.debug(f'Found {len(cookies_data)} cookies from {cookies_source}')
-
- # Check if this is an exact match requirement
- if login_cookie.startswith('EXACTMATCH '):
- # Extract the actual cookie name after "EXACTMATCH "
- exact_cookie_name = login_cookie[11:] # Remove "EXACTMATCH " prefix
- is_exact_match = True
- search_target = exact_cookie_name
- logger.debug(f"Using exact match for cookie name: '{exact_cookie_name}'")
- else:
- # Use substring matching (original behavior)
- is_exact_match = False
- search_target = login_cookie
- logger.debug(f"Using substring matching for: '{login_cookie}'")
-
- # Check if login_cookie is present in cookies
- login_cookie_found = False
- matching_cookie_info = None
-
- for cookie in cookies_data:
- cookie_name = cookie.get('name', '')
- cookie_value = cookie.get('value', '')
-
- if is_exact_match:
- # Exact match: check if cookie name exactly matches the target
- if cookie_name == search_target:
- login_cookie_found = True
- matching_cookie_info = f"exact name match='{cookie_name}'"
- logger.debug(f'Login cookie found with exact match: {matching_cookie_info}')
- break
- else:
- # Substring match: check if target appears in cookie name or value
- if search_target in cookie_name or search_target in cookie_value:
- login_cookie_found = True
- matching_cookie_info = f"substring match in name='{cookie_name}'"
- logger.debug(f'Login cookie found with substring match: {matching_cookie_info}')
- break
-
- # Prepare evaluation result
- if login_cookie_found:
- if is_exact_match:
- judgement = (
- f"Automatic judgement: Login cookie '{search_target}' was found as exact match in end-state browser cookies"
- )
- else:
- judgement = f"Automatic judgement: Login cookie '{search_target}' was found in end-state browser cookies"
- success = True
- score = 1.0
- error = None
- else:
- if is_exact_match:
- judgement = (
- f"Automatic judgement: Login cookie '{search_target}' was NOT found as exact match in end-state browser cookies"
- )
- else:
- judgement = f"Automatic judgement: Login cookie '{search_target}' was NOT found in end-state browser cookies"
- success = False
- score = 0.0
- error = None
-
- logger.info(f"Cookie evaluation result from end-state: success={success} for login_cookie='{login_cookie}'")
-
- return {
- 'task_id': task_id,
- 'judgement': judgement,
- 'success': success,
- 'error': error,
- 'score': score,
- }
-
-
-def save_result_to_server(convex_url: str, secret_key: str, payload: dict) -> bool:
- """Save result to server (sync function for use with asyncio.to_thread)"""
- return save_task_result_to_server(convex_url, secret_key, payload)
-
-
async def cleanup_browser_safe(browser_session: BrowserSession):
"""Safe browser cleanup with timeout"""
try:
@@ -1953,6 +636,23 @@ async def cleanup_browser_safe(browser_session: BrowserSession):
logger.warning(f'Browser cleanup: Failed with error: {type(e).__name__}: {e}')
+# ================================================
+# Stage runner and related functions
+# ================================================
+
+
+def save_result_to_server(convex_url: str, secret_key: str, payload: dict) -> bool:
+ """Save result to server (sync function for use with asyncio.to_thread)"""
+ return save_task_result_to_server(convex_url, secret_key, payload)
+
+
+async def run_stage(stage: Stage, stage_func, timeout: int | None = None):
+ """Generic stage runner with timeout"""
+ if timeout:
+ return await asyncio.wait_for(stage_func(), timeout)
+ return await stage_func()
+
+
def determine_current_stage(completed_stages: set) -> Stage:
"""Determine current stage based on completed stages"""
if Stage.SAVE_SERVER in completed_stages:
@@ -2578,379 +1278,9 @@ async def run_multiple_tasks(
return {'task_results': processed_results}
-# Helper function to fetch tasks from the server
-def fetch_tasks_from_server(convex_url: str, secret_key: str, test_case_name: str):
- """Fetches the specified test case file from the Convex HTTP endpoint."""
-
- if not convex_url:
- logger.error('Error: EVALUATION_TOOL_URL environment variable not set.')
- return None
-
- if not secret_key:
- logger.error('Error: EVALUATION_TOOL_SECRET_KEY environment variable not set.')
- return None
-
- endpoint_url = f'{convex_url}/api/getTestCase'
- headers = {
- 'Authorization': f'Bearer {secret_key}',
- 'Content-Type': 'application/json',
- }
- payload = {'name': test_case_name}
-
- logger.info(f"Fetching test case '{test_case_name}' from {endpoint_url}...")
-
- try:
- response = requests.post(endpoint_url, headers=headers, json=payload)
-
- logger.info(f'Fetch Status Code: {response.status_code}')
-
- if response.status_code == 200:
- try:
- data = response.json()
- logger.info(f"Successfully fetched test case data for '{test_case_name}'.")
- # Assuming the data is the list of tasks
- if isinstance(data, list):
- return data
- else:
- logger.error(f'Error: Fetched data is not a list. Type: {type(data)}')
- logger.error(f'Raw response: {response.text}')
- return None
-
- except json.JSONDecodeError:
- logger.error('Error: Failed to decode JSON response.')
- logger.error(f'Raw response text: {response.text}')
- return None
- else:
- logger.error(f"Error: Failed to fetch test case '{test_case_name}'. Status: {response.status_code}")
- logger.error(f'Response: {response.text}')
- return None
-
- except requests.exceptions.RequestException as e:
- logger.error(f'Error during request to fetch test case: {type(e).__name__}: {e}')
- return None
-
-
-# Helper function to fetch auth distribution from the server
-def fetch_auth_distribution_from_server(convex_url: str, secret_key: str):
- """Fetches an available auth distribution from the Convex HTTP endpoint."""
-
- if not convex_url:
- logger.error('Error: EVALUATION_TOOL_URL environment variable not set.')
- return None
-
- if not secret_key:
- logger.error('Error: EVALUATION_TOOL_SECRET_KEY environment variable not set.')
- return None
-
- endpoint_url = f'{convex_url}/api/getAuthDistribution'
- headers = {
- 'Authorization': f'Bearer {secret_key}',
- 'Content-Type': 'application/json',
- }
-
- logger.info(f'Fetching auth distribution from {endpoint_url}...')
-
- try:
- response = requests.post(endpoint_url, headers=headers, json={})
-
- logger.info(f'Fetch Auth Distribution Status Code: {response.status_code}')
-
- if response.status_code == 200:
- try:
- data = response.json()
- logger.info('Successfully fetched auth distribution data.')
- # Verify the response has the expected structure
- if isinstance(data, dict) and 'id' in data and 'loginInfo' in data:
- return data
- else:
- logger.error(
- f'Error: Fetched auth distribution data has unexpected structure. Keys: {list(data.keys()) if isinstance(data, dict) else "Not a dict"}'
- )
- logger.error(f'Raw response: {response.text}')
- return None
-
- except json.JSONDecodeError:
- logger.error('Error: Failed to decode JSON response for auth distribution.')
- logger.error(f'Raw response text: {response.text}')
- return None
- elif response.status_code == 404:
- logger.warning('No available auth distribution found on server.')
- return None
- else:
- logger.error(f'Error: Failed to fetch auth distribution. Status: {response.status_code}')
- logger.error(f'Response: {response.text}')
- return None
-
- except requests.exceptions.RequestException as e:
- logger.error(f'Error during request to fetch auth distribution: {type(e).__name__}: {e}')
- return None
-
-
-# Helper function to format auth information for the agent
-def format_auth_info_for_agent(auth_distribution: dict, auth_keys: list[str]) -> str:
- """
- Formats auth information from auth distribution for the agent task description.
-
- Args:
- auth_distribution: Dict with 'loginInfo' key containing auth data
- auth_keys: List of auth keys to extract (e.g., ['google', 'facebook'])
-
- Returns:
- Formatted string with login credentials or empty string if no matching keys
- """
- if not auth_distribution or not auth_keys:
- return ''
-
- login_info = auth_distribution.get('loginInfo', {})
- if not login_info:
- logger.warning('Auth distribution has no loginInfo')
- return ''
-
- # Extract relevant auth information based on auth_keys
- relevant_auths = []
- for auth_key in auth_keys:
- if auth_key in login_info:
- auth_data = login_info[auth_key]
- if isinstance(auth_data, dict):
- # Format the auth data for this key
- auth_details = []
- for key, value in auth_data.items():
- auth_details.append(f'{key}: {value}')
-
- if auth_details:
- relevant_auths.append(f'{auth_key} with {", ".join(auth_details)}')
- else:
- logger.warning(f"Auth data for key '{auth_key}' is not a dictionary: {type(auth_data)}")
- else:
- logger.warning(f"Auth key '{auth_key}' not found in available login info. Available keys: {list(login_info.keys())}")
-
- if relevant_auths:
- auth_text = f'\n\nThe following login credentials can be used to complete this task: {"; ".join(relevant_auths)}.'
- logger.info(f'Formatted auth info: {auth_text}')
- return auth_text
- else:
- logger.warning(f'No matching auth keys found. Requested: {auth_keys}, Available: {list(login_info.keys())}')
- return ''
-
-
-# Helper function to get git information
-def get_git_info():
- """Retrieves git branch, commit hash, commit timestamp, and repository URL using subprocess."""
- try:
- branch = subprocess.run(
- ['git', 'rev-parse', '--abbrev-ref', 'HEAD'], capture_output=True, text=True, check=True
- ).stdout.strip()
- commit_hash = subprocess.run(['git', 'rev-parse', 'HEAD'], capture_output=True, text=True, check=True).stdout.strip()
- # Get commit timestamp as Unix epoch integer
- commit_timestamp_str = subprocess.run(
- ['git', 'log', '-1', '--format=%ct'], capture_output=True, text=True, check=True
- ).stdout.strip()
- commit_timestamp = int(commit_timestamp_str)
- # Get repository URL
- repo_url = subprocess.run(
- ['git', 'config', '--get', 'remote.origin.url'], capture_output=True, text=True, check=True
- ).stdout.strip()
- return {'branch': branch, 'hash': commit_hash, 'timestamp': commit_timestamp, 'repo': repo_url}
- except (subprocess.CalledProcessError, FileNotFoundError, ValueError) as e:
- logger.warning(f'Could not retrieve git info: {type(e).__name__}: {e}. Using defaults.')
- return {
- 'branch': 'unknown',
- 'hash': 'unknown',
- 'timestamp': int(time.time()), # Fallback to current time
- 'repo': 'unknown',
- }
-
-
-# Helper function to start a new run on the convex server
-def start_new_run(convex_url: str, secret_key: str, run_details: dict, existing_run_id: str | None = None):
- """Sends a request to start a new evaluation run and returns the run ID."""
- if not convex_url or not secret_key:
- logger.error('Error: Convex URL or Secret Key not provided for starting run.')
- return None
-
- endpoint_url = f'{convex_url}/api/startRun'
- headers = {
- 'Authorization': f'Bearer {secret_key}',
- 'Content-Type': 'application/json',
- }
-
- # Add existing_run_id to the payload if provided
- payload = run_details.copy()
- if existing_run_id:
- payload['runId'] = existing_run_id
-
- logger.info(f'Sending request to start run at {endpoint_url}...')
- # Avoid logging secret key in run_details if it were ever passed
- loggable_details = {k: v for k, v in payload.items() if k != 'secret_key'}
- logger.info(f'Run details: {json.dumps(loggable_details, indent=2)}')
-
- try:
- response = requests.post(endpoint_url, headers=headers, json=payload)
- logger.info(f'Start Run Status Code: {response.status_code}')
-
- if response.status_code == 200:
- try:
- data = response.json()
- run_id = data.get('runId')
- if run_id:
- logger.info(f'Successfully started run. Run ID: {run_id}')
- return run_id
- else:
- logger.error("Error: 'runId' not found in successful startRun response.")
- logger.error(f'Raw response: {response.text}')
- return None
- except json.JSONDecodeError:
- logger.error('Error: Failed to decode startRun JSON response.')
- logger.error(f'Raw response text: {response.text}')
- return None
- else:
- logger.error('Error: Failed to start run.')
- logger.error(f'Response: {response.text}')
- return None
-
- except requests.exceptions.RequestException as e:
- logger.error(f'Error during startRun request: {type(e).__name__}: {e}')
- return None
-
-
-# Helper function to save a task result to the server
-def save_task_result_to_server(convex_url: str, secret_key: str, result_details: dict):
- """Sends a request to save a single task result to the Convex backend."""
-
- if not convex_url:
- logger.error('Error: EVALUATION_TOOL_URL environment variable not set for saving task result.')
- return False
-
- if not secret_key:
- logger.error('Error: EVALUATION_TOOL_SECRET_KEY environment variable not set for saving task result.')
- return False
-
- # Ensure runId is present in the details being sent
- if 'runId' not in result_details or not result_details['runId']:
- logger.error("Error: 'runId' is missing or empty in result_details for saveTaskResult.")
- return False
-
- endpoint_url = f'{convex_url}/api/saveTaskResult'
- headers = {
- 'Authorization': f'Bearer {secret_key}',
- 'Content-Type': 'application/json',
- }
-
- logger.info(f'Sending request to save task result at {endpoint_url}...')
- logger.debug(f'Result details payload: {json.dumps(result_details, indent=2)}') # Log details at debug level
-
- try:
- response = requests.post(endpoint_url, headers=headers, json=result_details)
-
- logger.info(f'Save Task Result Status Code: {response.status_code}')
-
- if response.status_code == 200:
- try:
- data = response.json()
- logger.info(f'Successfully saved task result: {data.get("message")}')
- logger.info(f'Result ID: {data.get("resultId")}')
- return True
- except json.JSONDecodeError:
- logger.error('Error: Failed to decode saveTaskResult JSON response.')
- logger.error(f'Raw response text: {response.text}')
- return False
- else:
- logger.error('Error: Failed to save task result.')
- logger.error(f'Response: {response.text}')
- return False
-
- except requests.exceptions.RequestException as e:
- logger.error(f'Error during saveTaskResult request: {type(e).__name__}: {e}')
- return False
-
-
-# Helper function to save runner progress to the server
-def save_runner_progress_to_server(convex_url: str, secret_key: str, progress_details: dict):
- """Sends a request to save runner progress to the Convex backend."""
-
- if not convex_url:
- logger.debug('No EVALUATION_TOOL_URL environment variable set for saving runner progress.')
- return False
-
- if not secret_key:
- logger.debug('No EVALUATION_TOOL_SECRET_KEY environment variable set for saving runner progress.')
- return False
-
- endpoint_url = f'{convex_url}/api/saveRunnerProgress'
- headers = {
- 'Authorization': f'Bearer {secret_key}',
- 'Content-Type': 'application/json',
- }
-
- try:
- response = requests.post(endpoint_url, headers=headers, json=progress_details, timeout=10)
-
- if response.status_code == 200:
- logger.debug(f'Successfully saved runner progress for {progress_details.get("runnerId")}')
- return True
- else:
- logger.warning(f'Failed to save runner progress. Status: {response.status_code}')
- return False
-
- except requests.exceptions.RequestException as e:
- logger.warning(f'Error during saveRunnerProgress request: {type(e).__name__}: {e}')
- return False
-
-
-def generate_runner_id(task_id: str, github_run_id: str | None = None) -> str:
- """Generate a unique runner ID for progress tracking that matches GitHub Actions pattern"""
- if github_run_id:
- # Use batch-level runner ID consistent with GitHub Actions
- # GitHub Actions uses: github_run_{GITHUB_RUN_ID}_batch_{START_INDEX}
- # Get start index from environment variable set by GitHub Actions
- start_index = os.getenv('EVAL_START_INDEX', '0')
- return f'github_run_{github_run_id}_batch_{start_index}'
- else:
- # Fallback for local runs
- return f'local_run_{int(time.time())}'
-
-
-def send_progress_update(
- convex_url: str,
- secret_key: str,
- run_id: str,
- task_id: str,
- current_stage: str,
- status: str = 'active',
- github_workflow_url: str | None = None,
- assigned_task_range: str | None = None,
- error_message: str | None = None,
-) -> bool:
- """Send a progress update for the current runner and task"""
- try:
- # Generate runner ID
- github_run_id = os.getenv('GITHUB_RUN_ID')
- runner_id = generate_runner_id(task_id, github_run_id)
-
- # Extract workflow run ID from URL if available
- github_workflow_run_id = None
- if github_workflow_url and 'actions/runs/' in github_workflow_url:
- try:
- github_workflow_run_id = github_workflow_url.split('actions/runs/')[1].split('/')[0]
- except (IndexError, AttributeError):
- pass
-
- progress_details = {
- 'runId': run_id,
- 'runnerId': runner_id,
- 'taskId': task_id,
- 'currentStage': current_stage,
- 'status': status,
- 'githubWorkflowUrl': github_workflow_url,
- 'githubWorkflowRunId': github_workflow_run_id,
- 'assignedTaskRange': assigned_task_range,
- 'errorMessage': error_message,
- }
-
- return save_runner_progress_to_server(convex_url, secret_key, progress_details)
- except Exception as e:
- logger.warning(f'Failed to send progress update: {type(e).__name__}: {e}')
- return False
+# ================================================
+# Main Evaluation Pipeline
+# ================================================
async def run_evaluation_pipeline(
@@ -3042,102 +1372,9 @@ async def run_evaluation_pipeline(
)
-async def check_login_cookie_at_step(browser_session, task_id: str, login_cookie: str, step: int) -> bool:
- """
- Check if login cookie is present at the current step.
-
- Args:
- browser_session: The browser session to check cookies from
- task_id: The task ID for tracking
- login_cookie: The cookie to search for
- step: Current step number
-
- Returns:
- bool: True if login cookie was found, False otherwise
- """
- global _login_cookie_tracker
-
- try:
- # Get current cookies from browser
- current_cookies = await browser_session.get_cookies()
-
- if not current_cookies:
- logger.debug(f'Task {task_id} Step {step}: No cookies found')
- return False
-
- # Check if this is an exact match requirement
- if login_cookie.startswith('EXACTMATCH '):
- exact_cookie_name = login_cookie[11:] # Remove "EXACTMATCH " prefix
- is_exact_match = True
- search_target = exact_cookie_name
- else:
- is_exact_match = False
- search_target = login_cookie
-
- # Check if login_cookie is present
- for cookie in current_cookies:
- cookie_name = cookie.get('name', '')
- cookie_value = cookie.get('value', '')
-
- if is_exact_match:
- if cookie_name == search_target:
- logger.info(f'✅ Task {task_id} Step {step}: Login cookie "{search_target}" found (exact match)')
- # Track that we found the cookie
- _login_cookie_tracker[task_id] = {
- 'found': True,
- 'step': step,
- 'cookie_name': cookie_name,
- 'match_type': 'exact',
- }
- return True
- else:
- if search_target in cookie_name or search_target in cookie_value:
- logger.info(f'✅ Task {task_id} Step {step}: Login cookie "{search_target}" found (substring match)')
- # Track that we found the cookie
- _login_cookie_tracker[task_id] = {
- 'found': True,
- 'step': step,
- 'cookie_name': cookie_name,
- 'match_type': 'substring',
- }
- return True
-
- logger.debug(f'Task {task_id} Step {step}: Login cookie "{search_target}" not found in {len(current_cookies)} cookies')
- return False
-
- except Exception as e:
- logger.warning(f'Task {task_id} Step {step}: Error checking login cookie: {type(e).__name__}: {e}')
- return False
-
-
-async def save_login_cookie_tracking(task_folder: Path, task_id: str) -> None:
- """
- Save the login cookie tracking information to a file.
-
- Args:
- task_folder: Directory to save the tracking file
- task_id: The task ID
- """
- global _login_cookie_tracker
-
- try:
- tracking_file = task_folder / 'login_cookie_tracking.json'
- tracking_data = _login_cookie_tracker.get(task_id, {'found': False})
-
- # Add timestamp
- tracking_data['timestamp'] = time.time()
-
- # Save to file
- async with await anyio.open_file(tracking_file, 'w') as f:
- await f.write(json.dumps(tracking_data, indent=2))
-
- logger.info(f'📝 Saved login cookie tracking for task {task_id}: {tracking_data}')
-
- # Clean up tracking data to avoid memory leaks
- _login_cookie_tracker.pop(task_id, None)
-
- except Exception as e:
- logger.warning(f'❌ Failed to save login cookie tracking for task {task_id}: {type(e).__name__}: {e}')
+# ================================================
+# Main Evaluation Pipeline Execution
+# ================================================
if __name__ == '__main__':
diff --git a/eval/types.py b/eval/types.py
new file mode 100644
index 000000000..f8944ebc1
--- /dev/null
+++ b/eval/types.py
@@ -0,0 +1,228 @@
+import json
+import logging
+from dataclasses import dataclass, field
+from enum import Enum
+from typing import Any
+
+from eval.utils import create_pydantic_model_from_schema, make_json_serializable
+
+logger = logging.getLogger(__name__)
+
+
+class Stage(Enum):
+ SETUP_BROWSER = 'setup_browser'
+ RUN_AGENT = 'run_agent'
+ FORMAT_HISTORY = 'format_history'
+ EVALUATE = 'evaluate'
+ SAVE_SERVER = 'save_server'
+
+
+@dataclass
+class StageError:
+ stage: Stage
+ error_type: str
+ message: str
+
+
+@dataclass
+class TaskResult:
+ task_id: str
+ run_id: str
+ confirmed_task: str
+ task: Any
+ max_steps: int
+ laminar_link: str | None = None
+ github_workflow_url: str | None = None
+ completed_stages: set[Stage] = field(default_factory=set)
+ stage_data: dict[Stage, Any] = field(default_factory=dict)
+ errors: list = field(default_factory=list)
+ cancelled: bool = False
+ critical_error: str | None = None
+ server_save_failed: bool = False
+
+ def stage_completed(self, stage: Stage, data: Any = None):
+ self.completed_stages.add(stage)
+ if data is not None:
+ self.stage_data[stage] = data
+
+ def stage_failed(self, stage: Stage, error: StageError):
+ self.errors.append(error)
+
+ def mark_cancelled(self):
+ self.cancelled = True
+
+ def mark_critical_error(self, error: str):
+ self.critical_error = error
+
+ def mark_server_save_failed(self, error: str):
+ self.server_save_failed = True
+ self.errors.append(StageError(Stage.SAVE_SERVER, 'server_save', error))
+
+ def has_execution_data(self) -> bool:
+ return Stage.RUN_AGENT in self.completed_stages or Stage.FORMAT_HISTORY in self.completed_stages
+
+ @property
+ def server_payload(self) -> dict[str, Any]:
+ """Generate payload for server submission"""
+ payload = {
+ 'taskId': self.task_id,
+ 'runId': self.run_id,
+ 'task': self.confirmed_task,
+ 'completed_stages': [stage.value for stage in self.completed_stages],
+ 'has_errors': len(self.errors) > 0,
+ 'cancelled': self.cancelled,
+ 'critical_error': self.critical_error,
+ 'server_save_failed': self.server_save_failed,
+ 'laminarTaskLink': self.laminar_link,
+ 'githubWorkflowUrl': self.github_workflow_url,
+ }
+
+ # Add task execution data if available
+ if Stage.FORMAT_HISTORY in self.completed_stages:
+ format_data = self.stage_data.get(Stage.FORMAT_HISTORY, {})
+ logger.info(f'format_data: {format_data}')
+ # log token usage
+ logger.info(f'tokensUsed: {format_data.get("tokensUsed")}')
+ logger.info(f'usage: {format_data.get("usage")}')
+
+ # Handle usage data - convert to JSON string if it's a dict
+ usage_data = format_data.get('usage')
+ if usage_data and isinstance(usage_data, dict):
+ usage_data = json.dumps(usage_data)
+
+ payload.update(
+ {
+ 'actionHistory': format_data.get('action_history', []),
+ 'finalResultResponse': format_data.get('final_result_response', ''),
+ 'selfReportCompleted': format_data.get('self_report_completed', False),
+ 'selfReportSuccess': format_data.get('self_report_success', False),
+ 'taskDuration': format_data.get('task_duration'),
+ 'steps': format_data.get('steps'),
+ 'maxSteps': self.max_steps,
+ 'tokensUsed': format_data.get('tokensUsed'),
+ 'usage': usage_data, # Add usage data (JSON string if dict)
+ 'completeHistory': format_data.get('complete_history', []), # Add complete step history
+ }
+ )
+
+ # Add evaluation data if available
+ if Stage.EVALUATE in self.completed_stages:
+ eval_data = self.stage_data.get(Stage.EVALUATE, {})
+
+ # Handle comprehensive judge evaluation
+ comp_eval = eval_data.get('comprehensive_evaluation') or eval_data.get('comprehensive_judge')
+ if comp_eval:
+ # Convert enum lists to string lists for database storage
+ task_categories = comp_eval.get('task_categories', [])
+ if task_categories and hasattr(task_categories[0], 'value'):
+ task_categories = [cat.value for cat in task_categories]
+
+ error_categories = comp_eval.get('error_categories', [])
+ if error_categories and hasattr(error_categories[0], 'value'):
+ error_categories = [err.value for err in error_categories]
+
+ payload.update(
+ {
+ 'comprehensiveJudgeEvaluationSummary': comp_eval.get('task_summary'),
+ 'comprehensiveJudgeEvaluationReasoning': comp_eval.get('reasoning'),
+ 'comprehensiveJudgeEvaluationPassed': comp_eval.get('passed'),
+ 'comprehensiveJudgeEvaluationScore': comp_eval.get('final_score'),
+ 'comprehensiveJudgeEvaluationCategories': task_categories,
+ 'comprehensiveJudgeEvaluationErrors': error_categories,
+ 'comprehensiveJudgeEvaluationTips': comp_eval.get('improvement_tips', []),
+ 'comprehensiveJudgeEvaluationCriticalIssues': comp_eval.get('critical_issues', []),
+ 'comprehensiveJudgeEvaluationScores': comp_eval.get('scores'),
+ 'comprehensiveJudgeEvaluationFull': comp_eval, # Include full comprehensive eval data
+ }
+ )
+
+ # Handle legacy Mind2Web evaluation (for compatibility)
+ payload.update(
+ {
+ 'onlineMind2WebEvaluationJudgement': eval_data.get('judgement') or 'No evaluation available',
+ 'onlineMind2WebEvaluationError': eval_data.get('error'),
+ 'onlineMind2WebEvaluationSuccess': eval_data.get('success', False),
+ 'onlineMind2WebEvaluationScore': eval_data.get('score', 0.0),
+ }
+ )
+
+ # Ensure all data in payload is JSON serializable
+ serialized_payload = make_json_serializable(payload)
+ # Type assertion since we know payload is a dict and make_json_serializable preserves dict structure
+ assert isinstance(serialized_payload, dict), 'Payload serialization should preserve dict structure'
+ return serialized_payload
+
+ def get_local_status(self) -> dict[str, Any]:
+ """Get local status summary"""
+ success = (
+ Stage.EVALUATE in self.completed_stages
+ and not self.cancelled
+ and self.critical_error is None
+ and len([e for e in self.errors if e.error_type == 'exception']) == 0
+ )
+ return {
+ 'task_id': self.task_id,
+ 'success': success,
+ 'error': self.critical_error or (self.errors[0].message if self.errors else None),
+ 'completed_stages': [stage.value for stage in self.completed_stages],
+ }
+
+
+class Task:
+ def __init__(self, task_id, confirmed_task, **kwargs):
+ # Validate required fields
+ if not task_id:
+ raise ValueError('task_id is required and cannot be empty')
+ if not confirmed_task:
+ raise ValueError('confirmed_task is required and cannot be empty')
+
+ # Set required fields
+ self.task_id = task_id
+ self.confirmed_task = confirmed_task
+
+ # Set optional fields dynamically
+ # Known optional fields with defaults
+ self.website = kwargs.get('website', None)
+ self.reference_length = kwargs.get('reference_length', None)
+ self.level = kwargs.get('level', None)
+ self.cluster_id = kwargs.get('cluster_id', None)
+ self.login_cookie = kwargs.get('login_cookie', None)
+ self.login_type = kwargs.get('login_type', None)
+ self.category = kwargs.get('category', None)
+ self.output_schema = kwargs.get('output_schema', None) # Add structured output schema support
+ self.auth_keys = kwargs.get('auth_keys', None) # List of auth keys to fetch from auth distribution
+ if self.output_schema:
+ # Convert JSON schema to Pydantic model class
+ self.output_model = create_pydantic_model_from_schema(self.output_schema, f'Task_{self.task_id}_Output')
+ else:
+ self.output_model = None
+
+ # Store any additional optional fields
+ known_fields = {
+ 'website',
+ 'reference_length',
+ 'level',
+ 'cluster_id',
+ 'login_cookie',
+ 'login_type',
+ 'category',
+ 'output_schema',
+ 'auth_keys',
+ }
+ self.additional_fields = {k: v for k, v in kwargs.items() if k not in known_fields}
+
+ # Make all additional fields accessible as attributes
+ for key, value in self.additional_fields.items():
+ setattr(self, key, value)
+
+ def __str__(self):
+ # Include main fields and indicate if there are additional fields
+ base_str = f'Task(task_id={self.task_id}, confirmed_task={self.confirmed_task}, website={self.website}, reference_length={self.reference_length}, level={self.level}, cluster_id={self.cluster_id}, login_cookie={self.login_cookie}, login_type={self.login_type}, category={self.category}, output_schema={self.output_schema}, auth_keys={self.auth_keys}'
+ if self.additional_fields:
+ additional_str = ', '.join(f'{k}={v}' for k, v in self.additional_fields.items())
+ base_str += f', {additional_str}'
+ base_str += ')'
+ return base_str
+
+ def __repr__(self):
+ return self.__str__()
diff --git a/eval/utils.py b/eval/utils.py
index 43726166c..87beed480 100644
--- a/eval/utils.py
+++ b/eval/utils.py
@@ -1,5 +1,8 @@
import json
import logging
+import subprocess
+import time
+from typing import Any
from pydantic import BaseModel
@@ -41,7 +44,7 @@ def create_pydantic_model_from_schema(original_schema: dict | str, model_name: s
if isinstance(original_schema, str):
schema: dict = json.loads(original_schema)
else:
- schema: dict = original_schema
+ schema = original_schema
logger.debug(f'Creating Pydantic model from schema: {schema}')
@@ -224,3 +227,51 @@ def create_pydantic_model_from_schema(original_schema: dict | str, model_name: s
logger.error(f'Failed to create Pydantic model from schema: {e}')
logger.error(f'Schema: {schema}')
raise ValueError(f'Invalid JSON schema: {e}') from e
+
+
+def make_json_serializable(obj: Any) -> Any:
+ """
+ Convert objects to JSON-serializable types.
+ Handles common non-serializable types like enums, custom objects, etc.
+ """
+ if obj is None:
+ return None
+ elif isinstance(obj, (str, int, float, bool)):
+ return obj
+ elif isinstance(obj, dict):
+ return {k: make_json_serializable(v) for k, v in obj.items()}
+ elif isinstance(obj, (list, tuple)):
+ return [make_json_serializable(item) for item in obj]
+ elif hasattr(obj, 'value'): # Handle enums
+ return obj.value
+ elif hasattr(obj, '__dict__'): # Handle custom objects
+ return str(obj)
+ else:
+ return str(obj)
+
+
+def get_git_info():
+ """Retrieves git branch, commit hash, commit timestamp, and repository URL using subprocess."""
+ try:
+ branch = subprocess.run(
+ ['git', 'rev-parse', '--abbrev-ref', 'HEAD'], capture_output=True, text=True, check=True
+ ).stdout.strip()
+ commit_hash = subprocess.run(['git', 'rev-parse', 'HEAD'], capture_output=True, text=True, check=True).stdout.strip()
+ # Get commit timestamp as Unix epoch integer
+ commit_timestamp_str = subprocess.run(
+ ['git', 'log', '-1', '--format=%ct'], capture_output=True, text=True, check=True
+ ).stdout.strip()
+ commit_timestamp = int(commit_timestamp_str)
+ # Get repository URL
+ repo_url = subprocess.run(
+ ['git', 'config', '--get', 'remote.origin.url'], capture_output=True, text=True, check=True
+ ).stdout.strip()
+ return {'branch': branch, 'hash': commit_hash, 'timestamp': commit_timestamp, 'repo': repo_url}
+ except (subprocess.CalledProcessError, FileNotFoundError, ValueError) as e:
+ logger.warning(f'Could not retrieve git info: {type(e).__name__}: {e}. Using defaults.')
+ return {
+ 'branch': 'unknown',
+ 'hash': 'unknown',
+ 'timestamp': int(time.time()), # Fallback to current time
+ 'repo': 'unknown',
+ }
diff --git a/eval/web_judge.py b/eval/web_judge.py
new file mode 100644
index 000000000..9a952966f
--- /dev/null
+++ b/eval/web_judge.py
@@ -0,0 +1,253 @@
+# ==============================================================================================================
+# This is the LLM as a judge evaluation system from the OSU-NLP Group paper
+# Any adaptiations made should be explicitly stated here:
+# Adaptations:
+# We are using our own wrapper for the OpenAI API
+# This means we changed model.generate to model.invoke. The behavior of the model should be identical.
+# Added a Online_Mind2Web_eval_with_retry wrapper with retry logic in case of API rate limiting or other issues.
+
+
+# @article{xue2025illusionprogressassessingcurrent,
+# title={An Illusion of Progress? Assessing the Current State of Web Agents},
+# author={Tianci Xue and Weijian Qi and Tianneng Shi and Chan Hee Song and Boyu Gou and Dawn Song and Huan Sun and Yu Su},
+# year={2025},
+# eprint={2504.01382},
+# archivePrefix={arXiv},
+# primaryClass={cs.AI},
+# url={https://arxiv.org/abs/2504.01382},
+# }
+
+# @inproceedings{deng2023mind2web,
+# author = {Deng, Xiang and Gu, Yu and Zheng, Boyuan and Chen, Shijie and Stevens, Sam and Wang, Boshi and Sun, Huan and Su, Yu},
+# booktitle = {Advances in Neural Information Processing Systems},
+# editor = {A. Oh and T. Naumann and A. Globerson and K. Saenko and M. Hardt and S. Levine},
+# pages = {28091--28114},
+# publisher = {Curran Associates, Inc.},
+# title = {Mind2Web: Towards a Generalist Agent for the Web},
+# url = {https://proceedings.neurips.cc/paper_files/paper/2023/file/5950bf290a1570ea401bf98882128160-Paper-Datasets_and_Benchmarks.pdf},
+# volume = {36},
+# year = {2023}
+# }
+# ==============================================================================================================
+import asyncio
+import base64
+import io
+import logging
+import re
+
+from PIL import Image
+
+MAX_IMAGE = 5
+
+
+logger = logging.getLogger(__name__)
+
+
+def encode_image(image):
+ """Convert a PIL image to base64 string."""
+ if image.mode == 'RGBA':
+ image = image.convert('RGB')
+ buffered = io.BytesIO()
+ image.save(buffered, format='JPEG')
+ return base64.b64encode(buffered.getvalue()).decode('utf-8')
+
+
+async def identify_key_points(task, model):
+ system_msg = """You are an expert tasked with analyzing a given task to identify the key points explicitly stated in the task description.
+
+**Objective**: Carefully analyze the task description and extract the critical elements explicitly mentioned in the task for achieving its goal.
+
+**Instructions**:
+1. Read the task description carefully.
+2. Identify and extract **key points** directly stated in the task description.
+ - A **key point** is a critical element, condition, or step explicitly mentioned in the task description.
+ - Do not infer or add any unstated elements.
+ - Words such as "best," "highest," "cheapest," "latest," "most recent," "lowest," "closest," "highest-rated," "largest," and "newest" must go through the sort function(e.g., the key point should be "Filter by highest").
+
+**Respond with**:
+- **Key Points**: A numbered list of the explicit key points for completing this task, one per line, without explanations or additional details."""
+ prompt = """Task: {task}"""
+ text = prompt.format(task=task)
+ messages = [
+ {'role': 'system', 'content': system_msg},
+ {
+ 'role': 'user',
+ 'content': [{'type': 'text', 'text': text}],
+ },
+ ]
+ response = await model.ainvoke(messages)
+ return response.completion
+
+
+async def judge_image(task, image_path, key_points, model):
+ system_msg = """You are an expert evaluator tasked with determining whether an image contains information about the necessary steps to complete a task.
+
+**Objective**: Analyze the provided image and decide if it shows essential steps or evidence required for completing the task. Use your reasoning to explain your decision before assigning a score.
+
+**Instructions**:
+1. Provide a detailed description of the image, including its contents, visible elements, text (if any), and any notable features.
+
+2. Carefully examine the image and evaluate whether it contains necessary steps or evidence crucial to task completion:
+- Identify key points that could be relevant to task completion, such as actions, progress indicators, tool usage, applied filters, or step-by-step instructions.
+- Does the image show actions, progress indicators, or critical information directly related to completing the task?
+- Is this information indispensable for understanding or ensuring task success?
+- If the image contains partial but relevant information, consider its usefulness rather than dismissing it outright.
+
+3. Provide your response in the following format:
+- **Reasoning**: Explain your thought process and observations. Mention specific elements in the image that indicate necessary steps, evidence, or lack thereof.
+- **Score**: Assign a score based on the reasoning, using the following scale:
+ - **1**: The image does not contain any necessary steps or relevant information.
+ - **2**: The image contains minimal or ambiguous information, unlikely to be essential.
+ - **3**: The image includes some relevant steps or hints but lacks clarity or completeness.
+ - **4**: The image contains important steps or evidence that are highly relevant but not fully comprehensive.
+ - **5**: The image clearly displays necessary steps or evidence crucial for completing the task.
+
+Respond with:
+1. **Reasoning**: [Your explanation]
+2. **Score**: [1-5]"""
+
+ jpg_base64_str = encode_image(Image.open(image_path))
+
+ prompt = """**Task**: {task}
+
+**Key Points for Task Completion**: {key_points}
+
+The snapshot of the web page is shown in the image."""
+ text = prompt.format(task=task, key_points=key_points)
+
+ messages = [
+ {'role': 'system', 'content': system_msg},
+ {
+ 'role': 'user',
+ 'content': [
+ {'type': 'text', 'text': text},
+ {
+ 'type': 'image_url',
+ 'image_url': {'url': f'data:image/jpeg;base64,{jpg_base64_str}', 'detail': 'high'},
+ },
+ ],
+ },
+ ]
+ response = await model.ainvoke(messages)
+ return response.completion
+
+
+async def Online_Mind2Web_eval(task, last_actions, images_path, model, score_threshold):
+ system_msg = """You are an expert in evaluating the performance of a web navigation agent. The agent is designed to help a human user navigate a website to complete a task. Given the user's task, the agent's action history, key points for task completion, some potentially important web pages in the agent's trajectory and their reasons, your goal is to determine whether the agent has completed the task and achieved all requirements.
+
+Your response must strictly follow the following evaluation criteria!
+*Important Evaluation Criteria*:
+1: The filtered results must be displayed correctly. If filters were not properly applied (i.e., missing selection, missing confirmation, or no visible effect in results), the task is not considered successful.
+2: You must carefully check whether these snapshots and action history meet these key points. Ensure that specific filter conditions, such as "best," "highest," "cheapest," "latest," "most recent," "lowest," "closest," "highest-rated," "largest," and "newest" are correctly applied using the filter function(e.g., sort function).
+3: Certain key points or requirements should be applied by the filter. Otherwise, a search with all requirements as input will be deemed a failure since it cannot guarantee that all results meet the requirements!
+4: If the task requires filtering by a specific range of money, years, or the number of beds and bathrooms, the applied filter must exactly match the given requirement. Any deviation results in failure. To ensure the task is successful, the applied filter must precisely match the specified range without being too broad or too narrow.
+Examples of Failure Cases:
+- If the requirement is less than $50, but the applied filter is less than $25, it is a failure.
+- If the requirement is $1500-$2500, but the applied filter is $2000-$2500, it is a failure.
+- If the requirement is $25-$200, but the applied filter is $0-$200, it is a failure.
+- If the required years are 2004-2012, but the filter applied is 2001-2012, it is a failure.
+- If the required years are before 2015, but the applied filter is 2000-2014, it is a failure.
+- If the task requires exactly 2 beds, but the filter applied is 2+ beds, it is a failure.
+5: Some tasks require a submission action or a display of results to be considered successful.
+6: If the retrieved information is invalid or empty(e.g., No match was found), but the agent has correctly performed the required action, it should still be considered successful.
+7: If the current page already displays all available items, then applying a filter is not necessary. As long as the agent selects items that meet the requirements (e.g., the cheapest or lowest price), the task is still considered successful.
+
+*IMPORTANT*
+Format your response into two lines as shown below:
+
+Thoughts: <your thoughts and reasoning process based on double-checking each key points and the evaluation criteria>
+Status: "success" or "failure"
+"""
+ prompt = """User Task: {task}
+
+Key Points: {key_points}
+
+Action History:
+{last_actions}
+
+The potentially important snapshots of the webpage in the agent's trajectory and their reasons:
+{thoughts}"""
+
+ key_points = await identify_key_points(task, model)
+ key_points = key_points.replace('\n\n', '\n')
+
+ try:
+ key_points = key_points.split('**Key Points**:')[1]
+ key_points = '\n'.join(line.lstrip() for line in key_points.splitlines())
+ except IndexError:
+ key_points = key_points.split('Key Points:')[-1]
+ key_points = '\n'.join(line.lstrip() for line in key_points.splitlines())
+
+ tasks = [judge_image(task, image_path, key_points, model) for image_path in images_path]
+ image_responses = await asyncio.gather(*tasks)
+
+ whole_content_img = []
+ whole_thoughts = []
+ record = []
+ pattern = r'[1-5]'
+ for response, image_path in zip(image_responses, images_path):
+ try:
+ score_text = response.split('Score')[1]
+ thought = response.split('**Reasoning**:')[-1].strip().lstrip('\n').split('\n\n')[0].replace('\n', ' ')
+ score = re.findall(pattern, score_text)[0]
+ record.append({'Response': response, 'Score': int(score)})
+ except Exception as e:
+ logger.error(f'Error processing response: {type(e).__name__}: {e}')
+ score = 0
+ record.append({'Response': response, 'Score': 0})
+
+ if int(score) >= score_threshold:
+ jpg_base64_str = encode_image(Image.open(image_path))
+ whole_content_img.append(
+ {'type': 'image_url', 'image_url': {'url': f'data:image/png;base64,{jpg_base64_str}', 'detail': 'high'}}
+ )
+ if thought != '':
+ whole_thoughts.append(thought)
+
+ whole_content_img = whole_content_img[:MAX_IMAGE]
+ whole_thoughts = whole_thoughts[:MAX_IMAGE]
+ if len(whole_content_img) == 0:
+ prompt = """User Task: {task}
+
+Key Points: {key_points}
+
+Action History:
+{last_actions}"""
+ text = prompt.format(
+ task=task,
+ last_actions='\n'.join(f'{i + 1}. {action}' for i, action in enumerate(last_actions)),
+ key_points=key_points,
+ thoughts='\n'.join(f'{i + 1}. {thought}' for i, thought in enumerate(whole_thoughts)),
+ )
+
+ messages = [
+ {'role': 'system', 'content': system_msg},
+ {'role': 'user', 'content': [{'type': 'text', 'text': text}] + whole_content_img},
+ ]
+ return messages, text, system_msg, record, key_points
+
+
+async def Online_Mind2Web_eval_with_retry(task, last_actions, images_path, model, score_threshold, max_retries=3):
+ """
+ Wrapper for Online_Mind2Web_eval with retry logic.
+
+ Args:
+ task: The task description
+ last_actions: list of actions taken
+ images_path: list of image paths
+ model: The model to use for evaluation
+ score_threshold: Score threshold for image filtering
+ max_retries: Maximum number of retry attempts
+
+ Returns:
+ Tuple of (messages, text, system_msg, record, key_points) or None if all retries fail
+ """
+ for attempt in range(max_retries):
+ try:
+ return await Online_Mind2Web_eval(task, last_actions, images_path, model, score_threshold)
+ except Exception as e:
+ if attempt == max_retries - 1: # Last attempt
+ logger.error(f'Failed to evaluate after {max_retries} attempts. Error: {type(e).__name__}: {str(e)}')
+ raise
+ logger.warning(f'Attempt {attempt + 1} failed. Retrying... Error: {type(e).__name__}: {str(e)}')
+ await asyncio.sleep(2**attempt) # Exponential backoff