Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Merge remote-tracking branch 'origin/main' into include-lmnr
Magnus Müllerd03196c09c51
diff --cc browser_use/agent/prompts.pyindex 6d503d704,c8033e285..09d420a27--- a/browser_use/agent/prompts.py+++ b/browser_use/agent/prompts.py@@@ -92,9 -92,38 +93,40 @@@ class AgentMessagePromptself.max_clickable_elements_length: int = max_clickable_elements_lengthself.sensitive_data: str | None = sensitive_dataself.available_file_paths: list[str] | None = available_file_paths+ self.screenshots = screenshots or []assert self.browser_state++ @observe_debug(name='_deduplicate_screenshots')+ def _deduplicate_screenshots(self, screenshots: list[str]) -> list[str]:+ """+ Remove consecutive duplicate screenshots, keeping only the most recent of each.++ Args:+ screenshots: List of base64-encoded screenshot strings in chronological order (oldest first)++ Returns:+ List of screenshots with consecutive duplicates removed, maintaining chronological order+ """+ if not screenshots:+ return []++ if len(screenshots) == 1:+ return screenshots++ # Keep track of unique screenshots by comparing each with the next one+ unique_screenshots = []++ for i in range(len(screenshots)):+ # Always keep the last screenshot+ if i == len(screenshots) - 1:+ unique_screenshots.append(screenshots[i])+ # Only keep screenshot if it's different from the next one+ elif screenshots[i] != screenshots[i + 1]:+ unique_screenshots.append(screenshots[i])++ return unique_screenshots++ @observe_debug(name='_get_browser_state_description')def _get_browser_state_description(self) -> str:elements_text = self.browser_state.element_tree.clickable_elements_to_string(include_attributes=self.include_attributes)diff --cc browser_use/controller/service.pyindex acdddfce1,409c67437..a6dccd187--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@@ -337,11 -328,11 +337,12 @@@ class Controller(Generic[Context]))# Content Actions+@self.registry.action("""Extract structured, semantic data (e.g. product description, price, all information about XYZ) from the current webpage based on a textual query.- Only use this for extracting info from a single product/article page, not for entire listings or search results pages.- Set extract_links=True ONLY if your query requires extracting links/URLs from the page.+ This tool takes the entire markdown of the page and extracts the query from it.+ Set extract_links=True ONLY if your query requires extracting links/URLs from the page.+ Only use this for specific queries for information retrieval from the page. Don't use this to get interactive elements - the tool does not see HTML elements, only the markdown.""",)async def extract_structured_data(@@@ -594,11 -564,10 +595,10 @@@ Explain the content of the page and thaexcept Exception as e:msg = f"Failed to scroll to text '{text}': {str(e)}"logger.error(msg)- return ActionResult(error=msg, include_in_memory=True)+ raise BrowserError(msg)# File System Actions-- @self.registry.action('Write content to file_name in file system, use only .md or .txt extensions.')+ @self.registry.action('Write content to file_name in file system. Allowed extensions are .md, .txt, .json, .csv.')async def write_file(file_name: str, content: str, file_system: FileSystem):result = await file_system.write_file(file_name, content)logger.info(f'💾 {result}')diff --cc eval/comprehensive_judge.pyindex d1f3253f4,2c1b53203..1e7ab9665--- a/eval/comprehensive_judge.py+++ b/eval/comprehensive_judge.py@@@ -542,8 -631,9 +639,10 @@@ def _write_result_file(result_file: Pat# Integration helper function+@observe_debug()- async def evaluate_task_with_comprehensive_judge(task_folder: Path, model: BaseChatModel, max_images: int = 10) -> dict[str, Any]:+ async def evaluate_task_with_comprehensive_judge(+ task_folder: Path, model: BaseChatModel, max_images: int = 10, judge_repeat_count: int = 1+ ) -> dict[str, Any]:"""Evaluate a task result using the comprehensive judge system.diff --cc eval/service.pyindex e54558879,8f4815e45..7f9d91e57--- a/eval/service.py+++ b/eval/service.py@@@ -54,23 -14,46 +14,49 @@@ from pathlib import Patfrom uuid import UUIDimport anyio- import psutil- import requestsfrom dotenv import load_dotenv- from lmnr import AsyncLaminarClient, Instruments, Laminar- from PIL import Image+ from lmnr import AsyncLaminarClient, Laminar, observefrom 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 AgentHistoryListfrom 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 browser_use.observability import observe, observe_debug- from eval.utils import create_pydantic_model_from_schema++MAX_IMAGE = 5-+ from eval.browsers import (+ ANCHOR_BROWSER_API_KEY,+ BRIGHTDATA_CDP_URL,+ BROWSERBASE_API_KEY,+ BROWSERBASE_PROJECT_ID,+ HYPERBROWSER_API_KEY,+ setup_browser_session,+ )+ from eval.comprehensive_judge import evaluate_task_with_comprehensive_judge+ from eval.cookie_judge import check_login_cookie_at_step, evaluate_task_with_login_cookie, save_login_cookie_tracking+ from eval.models import SUPPORTED_MODELS, get_llm+ from eval.resource_monitoring import (+ get_system_resources,+ log_system_resources,+ setup_signal_handlers,+ start_resource_monitoring,+ stop_resource_monitoring,+ )+ from eval.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 eval.task_types import Stage, StageError, Task, TaskResult+ from eval.utils import get_git_info+ from eval.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__)@@@ -1223,68 -339,14 +342,15 @@@ async def reformat_agent_historyreturn 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+ # ================================================+@observe_debug()- async def judge_task_result(model, task_folder: Path, score_threshold: float = 3, use_mind2web: bool = False) -> dict:+ async def judge_task_result(+ model, task_folder: Path, score_threshold: float = 3, use_mind2web: bool = False, judge_repeat_count: int = 1+ ) -> dict:"""Judge a single task result using the comprehensive judge system by default,with optional fallback to the original Online_Mind2Web evaluation.@@@ -1450,115 -510,12 +514,12 @@@}- @observe_debug()- 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()--- @observe_debug()- 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', '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 == '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]+@observe_debug(name='executor', span_type='EXECUTOR') # type: ignore[arg-type]async def run_agent_with_browser(browser_session: BrowserSession,task: Task,@@@ -1668,175 -633,11 +637,12 @@@ async def evaluate_task_resultreturn judge_resultelse:- return await judge_task_result(eval_model, task_folder, score_threshold=3, use_mind2web=use_mind2web)--- @observe_debug(name='evaluate_task_with_login_cookie') # type: ignore[arg-type]- 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,- }--- @observe_debug()- 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)+ return await judge_task_result(+ eval_model, task_folder, score_threshold=3, use_mind2web=use_mind2web, judge_repeat_count=judge_repeat_count+ )+@observe_debug()async def cleanup_browser_safe(browser_session: BrowserSession):"""Safe browser cleanup with timeout"""try:@@@ -2475,382 -1332,11 +1339,12 @@@ async def run_multiple_tasksreturn {'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+ # ================================================+@observe_debug()async def run_evaluation_pipeline(tasks: list[Task],llm: BaseChatModel,