Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Implement comprehensive judge system for task evaluation
Magnus Müllerbe16ff3f6965
diff --git a/.github/workflows/eval.yaml b/.github/workflows/eval.yamlindex d8e7e389e..f82fc3420 100644--- a/.github/workflows/eval.yaml+++ b/.github/workflows/eval.yaml@@ -194,6 +194,7 @@ jobs:[[ "${{ github.event.client_payload.script_args.validate_output }}" == "true" ]] && CMD_ARGS+=("--validate-output")[[ "${{ github.event.client_payload.script_args.include_result }}" == "true" ]] && CMD_ARGS+=("--include-result")[[ "${{ github.event.client_payload.script_args.highlight_elements }}" == "false" ]] && CMD_ARGS+=("--no-highlight-elements")+ [[ "${{ github.event.client_payload.script_args.use_mind2web_judge }}" == "true" ]] && CMD_ARGS+=("--use-mind2web-judge")# Add optional string parameters[[ -n "$USER_MESSAGE" ]] && CMD_ARGS+=("--user-message" "$USER_MESSAGE")diff --git a/eval/judge_system.py b/eval/judge_system.pynew file mode 100644index 000000000..357b42373--- /dev/null+++ b/eval/judge_system.py@@ -0,0 +1,471 @@+"""+@file purpose: Comprehensive judge system for evaluating browser-use agent runs with detailed structured feedback.++This system provides multi-dimensional evaluation of agent performance including:+- Task analysis and categorization+- Trajectory quality assessment+- Tool usage effectiveness+- Agent reasoning quality+- Browser handling capabilities+- Structured error categorization+- Actionable improvement suggestions++The judge uses vision-language models to analyze agent execution history, screenshots,+and final results to provide detailed structured JSON feedback for developers.+"""++import asyncio+import base64+import io+import json+import logging+from dataclasses import dataclass+from datetime import datetime+from enum import Enum+from pathlib import Path++from langchain_core.language_models.chat_models import BaseChatModel+from PIL import Image++logger = logging.getLogger(__name__)+++class ErrorCategory(Enum):+ # Access & Authentication+ BLOCKED_ACCESS = 'blocked_access'+ CAPTCHA_CHALLENGE = 'captcha_challenge'+ LOGIN_REQUIRED = 'login_required'+ RATE_LIMITED = 'rate_limited'++ # Tool & Action Failures+ TOOL_MISUSE = 'tool_misuse'+ INVALID_PARAMETERS = 'invalid_parameters'+ ACTION_SEQUENCE_ERROR = 'action_sequence_error'++ # Agent Behavior Issues+ INFINITE_LOOP = 'infinite_loop'+ STUCK_PATTERN = 'stuck_pattern'+ POOR_PLANNING = 'poor_planning'+ CONTEXT_LOSS = 'context_loss'++ # Browser & Technical+ ELEMENT_NOT_FOUND = 'element_not_found'+ CLICK_FAILURE = 'click_failure'+ LOAD_TIMEOUT = 'load_timeout'+ JAVASCRIPT_ERROR = 'javascript_error'++ # Content & Understanding+ MISUNDERSTOOD_TASK = 'misunderstood_task'+ FORMAT_ERROR = 'format_error'+ CONTENT_PARSING_ERROR = 'content_parsing_error'++ # Enhanced Detection Categories+ NAVIGATION_CONFUSION = 'navigation_confusion'+ FORM_FILLING_ERROR = 'form_filling_error'+ MODAL_HANDLING = 'modal_handling'+ IFRAME_ISSUES = 'iframe_issues'+ BROWSER_CRASHES = 'browser_crashes'+ IMPOSSIBLE_TASK = 'impossible_task'+ MISSING_INFORMATION = 'missing_information'+++class TaskCategory(Enum):+ EXTRACTION = 'extraction'+ INTERACTION = 'interaction'+ LOGIN = 'login'+ RESEARCH = 'research'+ SHOPPING = 'shopping'+ BOOKING = 'booking'+ COMPARISON = 'comparison'+ QA_TESTING = 'qa_testing'+ FORM_FILLING = 'form_filling'+ NAVIGATION = 'navigation'+ SEARCH = 'search'+ FILTERING = 'filtering'+ CONTENT_CREATION = 'content_creation'+ FILE_OPERATIONS = 'file_operations'+ MULTI_STEP_WORKFLOW = 'multi_step_workflow'+++@dataclass+class ScoreBreakdown:+ trajectory_quality: int # How human-like is the solution path (1-100)+ tool_calling_effectiveness: int # How well do tools work (1-100)+ agent_reasoning: int # Quality of agent's decision making (1-100)+ browser_handling: int # Browser stability and error handling (1-100)+ task_satisfaction: int # Final user satisfaction (1-100)+++@dataclass+class JudgeResult:+ # Basic Information+ task_summary: str # 1 sentence summary+ task_clarity_score: int # How clear vs uncertain the task is (1-100)+ task_categories: list[TaskCategory] # Primary task categories++ # Analysis+ reasoning: str # What went well/not well analysis+ error_categories: list[ErrorCategory] # Core error categories identified++ # Scores+ scores: ScoreBreakdown+ final_score: int # Overall score (1-100)+ passed: bool # Whether it meets 70% threshold++ # Developer Feedback+ improvement_tips: list[str] # Concrete improvement suggestions+ critical_issues: list[str] # Must-fix issues++ # Metadata+ evaluation_timestamp: str+ confidence_level: int # How confident the judge is (1-100)+++def encode_image(image_path: str) -> str:+ """Convert image file to base64 string."""+ try:+ with Image.open(image_path) as image:+ if image.mode == 'RGBA':+ image = image.convert('RGB')+ buffered = io.BytesIO()+ image.save(buffered, format='JPEG')+ return base64.b64encode(buffered.getvalue()).decode('utf-8')+ except Exception as e:+ logger.error(f'Failed to encode image {image_path}: {e}')+ return ''+++def truncate_text(text: str, max_length: int) -> str:+ """Truncate text to maximum length with ellipsis."""+ if len(text) <= max_length:+ return text+ return text[: max_length - 3] + '...'+++def prepare_agent_steps(complete_history: list[dict]) -> list[str]:+ """Extract and format agent steps, limiting each to 2000 characters."""+ steps = []+ for i, step in enumerate(complete_history):+ step_text = f'Step {i + 1}:\n'++ # Add model output if available+ if step.get('model_output'):+ model_output = step['model_output']+ if isinstance(model_output, dict):+ # Format the model output nicely+ if 'action' in model_output:+ step_text += f'Actions: {json.dumps(model_output["action"], indent=1)}\n'+ if 'current_state' in model_output:+ step_text += f'State: {model_output["current_state"]}\n'++ # Add results if available+ if step.get('result'):+ for j, result in enumerate(step['result']):+ if isinstance(result, dict):+ if result.get('extracted_content'):+ step_text += f'Result {j + 1}: {result["extracted_content"]}\n'+ if result.get('error'):+ step_text += f'Error {j + 1}: {result["error"]}\n'++ # Add URL info+ if step.get('state', {}).get('url'):+ step_text += f'URL: {step["state"]["url"]}\n'++ # Truncate to 2000 characters+ steps.append(truncate_text(step_text, 2000))++ return steps+++async def comprehensive_judge(+ task: str,+ complete_history: list[dict],+ final_result: str,+ screenshot_paths: list[str],+ model: BaseChatModel,+ max_images: int = 10,+) -> JudgeResult:+ """+ Comprehensive judge that evaluates browser-use agent runs with detailed structured feedback.+ """++ # Prepare inputs with length limits+ task_truncated = truncate_text(task, 40000)+ final_result_truncated = truncate_text(final_result or 'No final result', 40000)+ agent_steps = prepare_agent_steps(complete_history)++ # Select last N images+ selected_images = screenshot_paths[-max_images:] if screenshot_paths else []++ # Encode images+ encoded_images = []+ for img_path in selected_images:+ if Path(img_path).exists():+ encoded_img = encode_image(img_path)+ if encoded_img:+ encoded_images.append(+ {+ 'type': 'image_url',+ 'image_url': {+ 'url': f'data:image/jpeg;base64,{encoded_img}',+ 'detail': 'high',+ },+ }+ )++ # Construct the evaluation prompt+ system_prompt = """You are an expert judge evaluating browser automation agent performance.++Your task is to comprehensively analyze the agent's execution and provide structured feedback.++**EVALUATION CRITERIA:**++1. **Task Analysis**: Understand what the user wanted to accomplish+2. **Trajectory Quality**: How human-like and efficient was the solution path?+3. **Tool Usage**: How effectively were browser automation tools used?+4. **Agent Reasoning**: Quality of decision-making and problem-solving+5. **Browser Handling**: How well were browser issues handled?+6. **Final Outcome**: Did the task satisfy the user's intent?++**ERROR CATEGORIES TO CONSIDER:**+- Access & Authentication: blocked_access, captcha_challenge, login_required, rate_limited+- Tool & Action Failures: tool_misuse, invalid_parameters, action_sequence_error+- Agent Behavior: infinite_loop, stuck_pattern, poor_planning, context_loss+- Browser & Technical: element_not_found, click_failure, load_timeout, javascript_error+- Content & Understanding: misunderstood_task, format_error, content_parsing_error+- Enhanced: navigation_confusion, form_filling_error, modal_handling, iframe_issues, browser_crashes, impossible_task, missing_information++**TASK CATEGORIES TO CONSIDER:**+extraction, interaction, login, research, shopping, booking, comparison, qa_testing, form_filling, navigation, search, filtering, content_creation, file_operations, multi_step_workflow++**SCORING SCALE:**+- 90-100: Excellent execution, human-like, minimal issues+- 80-89: Good execution with minor issues+- 70-79: Acceptable execution, some problems but functional+- 60-69: Poor execution with significant issues+- 1-59: Failed execution, major problems++**PASS THRESHOLD: 70%**++Respond with EXACTLY this JSON structure (no additional text):++{+ "task_summary": "One sentence summary of what the task was trying to accomplish",+ "task_clarity_score": 85,+ "task_categories": ["category1", "category2"],+ "reasoning": "Detailed analysis of what went well and what didn't, trajectory quality, planning assessment",+ "error_categories": ["error1", "error2"],+ "scores": {+ "trajectory_quality": 75,+ "tool_calling_effectiveness": 80,+ "agent_reasoning": 85,+ "browser_handling": 65,+ "task_satisfaction": 70+ },+ "final_score": 75,+ "improvement_tips": [+ "Specific actionable improvement 1",+ "Specific actionable improvement 2"+ ],+ "critical_issues": [+ "Critical issue that must be fixed 1",+ "Critical issue that must be fixed 2"+ ],+ "confidence_level": 90+}"""++ user_prompt = f"""**TASK:** {task_truncated}++**AGENT EXECUTION STEPS:**+{chr(10).join(agent_steps)}++**FINAL RESULT:**+{final_result_truncated}++**TOTAL STEPS:** {len(complete_history)}+**SCREENSHOTS PROVIDED:** {len(selected_images)}++Analyze this execution and respond with the exact JSON structure requested."""++ # Build messages+ content_parts = [{'type': 'text', 'text': user_prompt}]+ content_parts.extend(encoded_images)++ messages = [+ {'role': 'system', 'content': system_prompt},+ {'role': 'user', 'content': content_parts},+ ]++ # Get structured response+ try:+ response = await asyncio.to_thread(model.invoke, messages)++ # Parse the JSON response+ response_text = response.content.strip()++ # Try to extract JSON if wrapped in markdown+ if '```json' in response_text:+ json_start = response_text.find('```json') + 7+ json_end = response_text.find('```', json_start)+ if json_end != -1:+ response_text = response_text[json_start:json_end].strip()+ elif '```' in response_text:+ json_start = response_text.find('```') + 3+ json_end = response_text.find('```', json_start)+ if json_end != -1:+ response_text = response_text[json_start:json_end].strip()++ # Parse JSON+ try:+ result_dict = json.loads(response_text)+ except json.JSONDecodeError as e:+ logger.error(f'Failed to parse JSON response: {e}')+ logger.error(f'Response text: {response_text}')+ # Create fallback result+ return create_fallback_result(task, 'Failed to parse judge response')++ # Convert to structured result+ return parse_judge_response(result_dict, task)++ except Exception as e:+ logger.error(f'Judge evaluation failed: {e}')+ return create_fallback_result(task, str(e))+++def parse_judge_response(result_dict: dict, task: str) -> JudgeResult:+ """Parse the LLM response into a structured JudgeResult."""+ try:+ # Parse task categories+ task_categories = []+ if 'task_categories' in result_dict:+ for cat in result_dict['task_categories']:+ try:+ task_categories.append(TaskCategory(cat))+ except ValueError:+ logger.warning(f'Unknown task category: {cat}')++ # Parse error categories+ error_categories = []+ if 'error_categories' in result_dict:+ for err in result_dict['error_categories']:+ try:+ error_categories.append(ErrorCategory(err))+ except ValueError:+ logger.warning(f'Unknown error category: {err}')++ # Parse scores+ scores_dict = result_dict.get('scores', {})+ scores = ScoreBreakdown(+ trajectory_quality=scores_dict.get('trajectory_quality', 50),+ tool_calling_effectiveness=scores_dict.get('tool_calling_effectiveness', 50),+ agent_reasoning=scores_dict.get('agent_reasoning', 50),+ browser_handling=scores_dict.get('browser_handling', 50),+ task_satisfaction=scores_dict.get('task_satisfaction', 50),+ )++ final_score = result_dict.get('final_score', 50)++ return JudgeResult(+ task_summary=result_dict.get('task_summary', 'Task analysis unavailable'),+ task_clarity_score=result_dict.get('task_clarity_score', 50),+ task_categories=task_categories,+ reasoning=result_dict.get('reasoning', 'Analysis unavailable'),+ error_categories=error_categories,+ scores=scores,+ final_score=final_score,+ passed=final_score >= 70,+ improvement_tips=result_dict.get('improvement_tips', []),+ critical_issues=result_dict.get('critical_issues', []),+ evaluation_timestamp=datetime.now().isoformat(),+ confidence_level=result_dict.get('confidence_level', 75),+ )++ except Exception as e:+ logger.error(f'Failed to parse judge response: {e}')+ return create_fallback_result(task, 'Failed to parse structured response')+++def create_fallback_result(task: str, error_msg: str) -> JudgeResult:+ """Create a fallback result when evaluation fails."""+ return JudgeResult(+ task_summary=f'Failed to analyze task: {task[:100]}...',+ task_clarity_score=0,+ task_categories=[TaskCategory.QA_TESTING],+ reasoning=f'Evaluation failed: {error_msg}',+ error_categories=[ErrorCategory.IMPOSSIBLE_TASK],+ scores=ScoreBreakdown(+ trajectory_quality=0,+ tool_calling_effectiveness=0,+ agent_reasoning=0,+ browser_handling=0,+ task_satisfaction=0,+ ),+ final_score=0,+ passed=False,+ improvement_tips=['Fix evaluation system'],+ critical_issues=[f'Evaluation system failure: {error_msg}'],+ evaluation_timestamp=datetime.now().isoformat(),+ confidence_level=0,+ )+++async def judge_with_retry(+ task: str,+ complete_history: list[dict],+ final_result: str,+ screenshot_paths: list[str],+ model: BaseChatModel,+ max_retries: int = 3,+ max_images: int = 10,+) -> JudgeResult:+ """+ Judge with retry logic for robustness.+ """+ for attempt in range(max_retries):+ try:+ return await comprehensive_judge(+ task,+ complete_history,+ final_result,+ screenshot_paths,+ model,+ max_images,+ )+ except Exception as e:+ if attempt == max_retries - 1:+ logger.error(f'Judge failed after {max_retries} attempts: {e}')+ return create_fallback_result(task, str(e))+ logger.warning(f'Judge attempt {attempt + 1} failed, retrying: {e}')+ await asyncio.sleep(2**attempt)+++def get_example_json_structure() -> dict:+ """Get an example of the expected JSON response structure for the LLM judge."""+ return {+ 'task_summary': 'Extract product prices from an e-commerce website',+ 'task_clarity_score': 85,+ 'task_categories': ['extraction', 'research'],+ 'reasoning': 'The agent successfully navigated to the target website and extracted most product information. However, it had difficulty with dynamic loading elements and missed some prices that loaded asynchronously. The overall approach was logical but could benefit from better wait strategies.',+ 'error_categories': ['element_not_found', 'load_timeout'],+ 'scores': {+ 'trajectory_quality': 75,+ 'tool_calling_effectiveness': 80,+ 'agent_reasoning': 85,+ 'browser_handling': 65,+ 'task_satisfaction': 70,+ },+ 'final_score': 75,+ 'improvement_tips': [+ 'Implement better wait strategies for dynamic content',+ 'Add retry logic for element detection',+ 'Improve error handling for async loading',+ ],+ 'critical_issues': [+ 'Missing wait for dynamic content to load',+ 'No fallback strategy when primary selectors fail',+ ],+ 'confidence_level': 90,+ }+++# Integration helper functiondiff --git a/eval/service.py b/eval/service.pyindex 7e2c9e08f..58d1c0cd7 100644--- a/eval/service.py+++ b/eval/service.py@@ -482,11 +482,157 @@ import http.clientimport jsonimport osimport subprocess+from dataclasses import dataclass, fieldfrom datetime import datetime++# Define Stage enum and related classes for the pipeline+from enum import Enumfrom pathlib import Path+from typing import Anyimport requestsfrom dotenv import load_dotenv++# Import the new comprehensive judge system+from judge_system import evaluate_task_with_comprehensive_judge+++class Stage(Enum):+ LOAD_EXISTING = 'load_existing'+ 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+ 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+ 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,+ 'laminar_link': self.laminar_link,+ }++ # Add task execution data if available+ if Stage.FORMAT_HISTORY in self.completed_stages:+ format_data = self.stage_data.get(Stage.FORMAT_HISTORY, {})+ 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'),+ }+ )++ # 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')+ if comp_eval:+ 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': comp_eval.get('task_categories', []),+ 'comprehensiveJudgeEvaluationErrors': comp_eval.get('error_categories', []),+ 'comprehensiveJudgeEvaluationTips': comp_eval.get('improvement_tips', []),+ 'comprehensiveJudgeEvaluationScores': comp_eval.get('scores'),+ }+ )++ # Handle legacy Mind2Web evaluation (for compatibility)+ payload.update(+ {+ 'onlineMind2WebEvaluationJudgement': eval_data.get('judgement'),+ 'onlineMind2WebEvaluationError': eval_data.get('error'),+ 'onlineMind2WebEvaluationSuccess': eval_data.get('success', False),+ 'onlineMind2WebEvaluationScore': eval_data.get('score', 0.0),+ }+ )++ return 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],+ }+++def calculate_local_summary():+ """Calculate summary of local evaluation results (stub implementation)"""+ return {'total_tasks': 0, 'success_rate': 0.0, 'average_score': 0.0, 'message': 'Local summary calculation not implemented'}++from langchain_anthropic import ChatAnthropicfrom langchain_core.language_models.chat_models import BaseChatModelfrom langchain_google_genai import ChatGoogleGenerativeAI@@ -906,12 +1052,16 @@ class Task:return self.__str__()-async def judge_task_result(model, task_folder: Path, score_threshold: float = 3) -> dict:+async def judge_task_result(model, task_folder: Path, score_threshold: float = 3, use_mind2web: bool = False) -> dict:"""- Judge a single task result based on the success value of the final action.+ Judge a single task result using the comprehensive judge system by default,+ with optional fallback to the original Online_Mind2Web evaluation.Args:+ model: The model to use for evaluationtask_folder: Path to the task result folder+ score_threshold: Score threshold for image filtering (used only for Mind2Web)+ use_mind2web: If True, use the original Online_Mind2Web evaluation insteadReturns:Dictionary containing judgment results@@ -924,329 +1074,136 @@ async def judge_task_result(model, task_folder: Path, score_threshold: float = 3async with await anyio.open_file(result_file) as f:result = json.loads(await f.read())- # If a Online_Mind2Web_evaluation is already saved, we can skip the eval- if result.get('Online_Mind2Web_evaluation'):- return result.get('Online_Mind2Web_evaluation')-- # Get the screenshot paths, task description, and action history- screenshot_paths = result.get('screenshot_paths', [])- task_description = result.get('task')- action_history = result.get('action_history', [])-- # Use the retry wrapper for evaluation- try:- # Await the async function directly instead of using asyncio.run()- eval_result = await Online_Mind2Web_eval_with_retry(- task_description, action_history, screenshot_paths, model, score_threshold- )-- if eval_result is None:- raise Exception('Evaluation failed after all retries')-- messages, text, system_msg, record, key_points = eval_result-- # Final steps to get judgement - run invoke in a thread- judgement_msg = await asyncio.to_thread(model.invoke, messages)- judgement = judgement_msg.content-- if 'success' in judgement.lower().split('status:')[1]: # This is the official criteria for success- evaluation = {'task_id': task_folder.name, 'judgement': judgement, 'success': True, 'error': None, 'score': 1.0}- else: # This is the official criteria for failure- evaluation = {'task_id': task_folder.name, 'judgement': judgement, 'success': False, 'error': None, 'score': 0.0}-- # Save the Online_Mind2Web_evaluation into the result.json file- result['Online_Mind2Web_evaluation'] = evaluation- async with await anyio.open_file(result_file, 'w') as f:- await f.write(json.dumps(result, indent=2))+ # Check if we should use the original Mind2Web evaluation+ if use_mind2web:+ logger.info(f'Task {task_folder.name}: Using original Online_Mind2Web evaluation')- return evaluation-- except Exception as err:- return {- 'task_id': task_folder.name,- 'judgement': None,- 'success': False,- 'error': f'{type(err).__name__}: {err}',- 'score': 0.0,- }-- except Exception as err:- return {- 'task_id': task_folder.name,- 'judgement': None,- 'success': False,- 'error': f'{type(err).__name__}: {err}',- 'score': 0.0,- }+ # If a Online_Mind2Web_evaluation is already saved, we can skip the eval+ if result.get('Online_Mind2Web_evaluation'):+ return result.get('Online_Mind2Web_evaluation')+ # Get the screenshot paths, task description, and action history+ screenshot_paths = result.get('screenshot_paths', [])+ task_description = result.get('task')+ action_history = result.get('action_history', [])-def calculate_local_summary(results_dir: str | None = None) -> dict:- """- Calculates a summary of task results by reading the saved result.json files.- Does not make any network requests.- """- if results_dir is None:- results_dir = 'saved_trajectories'-- path = Path(results_dir)- if not path.is_dir():- logger.warning(f'Results directory {results_dir} does not exist')- return {- 'timestamp': datetime.now().isoformat(),- 'total_tasks': 0,- 'successful_tasks': 0,- 'failed_tasks': 0,- 'success_rate': 0,- 'average_score': 0,- }-- # Collect all task folders- task_folders = [f for f in path.iterdir() if f.is_dir()]- total_tasks = len(task_folders)- successful_tasks = 0- total_score = 0.0- results_with_score = 0-- for folder in task_folders:- result_file = folder / 'result.json'- if result_file.exists():+ # Use the retry wrapper for evaluationtry:- with open(result_file) as f:- result_data = json.load(f)-- # Look for evaluation data- evaluation = result_data.get('Online_Mind2Web_evaluation', {})- if evaluation:- if evaluation.get('success', False):- successful_tasks += 1-- score = evaluation.get('score', 0.0)- if score > 0:- total_score += score- results_with_score += 1- except Exception as e:- logger.error(f'Error reading result file {result_file}: {type(e).__name__}: {e}')-- # Calculate statistics- failed_tasks = total_tasks - successful_tasks- success_rate = successful_tasks / total_tasks if total_tasks > 0 else 0- average_score = total_score / results_with_score if results_with_score > 0 else 0-- return {- 'timestamp': datetime.now().isoformat(),- 'total_tasks': total_tasks,- 'successful_tasks': successful_tasks,- 'failed_tasks': failed_tasks,- 'success_rate': success_rate,- 'average_score': average_score,- }---from dataclasses import dataclass-from enum import Enum-from typing import Any---class Stage(Enum):- LOAD_EXISTING = 'load_existing'- SETUP_BROWSER = 'setup_browser'- RUN_AGENT = 'run_agent'- FORMAT_HISTORY = 'format_history'- EVALUATE = 'evaluate'- SAVE_SERVER = 'save_server'+ # Await the async function directly instead of using asyncio.run()+ eval_result = await Online_Mind2Web_eval_with_retry(+ task_description, action_history, screenshot_paths, model, score_threshold+ )+ if eval_result is None:+ raise Exception('Evaluation failed after all retries')-@dataclass-class StageError(Exception):- stage: Stage- error_type: str # "timeout", "cancelled", "exception"- message: str+ messages, text, system_msg, record, key_points = eval_result+ # Final steps to get judgement - run invoke in a thread+ judgement_msg = await asyncio.to_thread(model.invoke, messages)+ judgement = judgement_msg.content-class TaskResult:- """Simplified task state tracker with auto-updating server payload"""-- def __init__(- self,- task_id: str,- run_id: str,- task_description: str,- task: Task,- max_steps: int,- laminar_task_link: str | None = None,- ):- self.task_id = task_id- self.completed_stages = set()- self.stage_data = {} # Store actual results from each stage- self.failed_stages = {} # Store errors from failed stages- self.local_error = None-- # Initialize server payload with defaults- self.server_payload = {- 'runId': run_id,- 'taskId': task_id,- 'task': task_description,- 'taskWebsite': task.website,- 'taskReferenceLength': task.reference_length,- 'taskLevel': task.level,- 'taskClusterId': task.cluster_id,- 'actionHistory': [],- 'finalResultResponse': 'None',- 'selfReportCompleted': False,- 'selfReportSuccess': None,- 'browserCrash': False,- 'browserCrashReason': None,- 'onlineMind2WebEvaluationJudgement': 'Not Attempted',- 'onlineMind2WebEvaluationError': None,- 'onlineMind2WebEvaluationSuccess': False,- 'onlineMind2WebEvaluationScore': 0.0,- 'completeHistory': [],- 'maxSteps': max_steps,- 'tokensUsed': 0,- 'taskDuration': None,- 'steps': 0,- 'laminarTaskLink': laminar_task_link, # Add field for task-specific Laminar link- }+ if 'success' in judgement.lower().split('status:')[1]: # This is the official criteria for success+ evaluation = {+ 'task_id': task_folder.name,+ 'judgement': judgement,+ 'success': True,+ 'error': None,+ 'score': 1.0,+ }+ else: # This is the official criteria for failure+ evaluation = {+ 'task_id': task_folder.name,+ 'judgement': judgement,+ 'success': False,+ 'error': None,+ 'score': 0.0,+ }- def stage_completed(self, stage: Stage, data: Any = None):- """Mark stage as completed and update server payload"""- self.completed_stages.add(stage)- if data is not None:- self.stage_data[stage] = data- self._auto_update_payload()+ # Save the Online_Mind2Web_evaluation into the result.json file+ result['Online_Mind2Web_evaluation'] = evaluation+ async with await anyio.open_file(result_file, 'w') as f:+ await f.write(json.dumps(result, indent=2))- def stage_failed(self, stage: Stage, error: StageError):- """Mark stage as failed and update server payload"""- self.failed_stages[stage] = error- self._auto_update_payload()+ return evaluation- def has_execution_data(self) -> bool:- """Check if we have execution data from either loading existing or completing execution"""- return Stage.LOAD_EXISTING in self.completed_stages or Stage.FORMAT_HISTORY in self.completed_stages-- def execution_succeeded(self) -> bool:- """Check if execution pipeline succeeded"""- return (- Stage.LOAD_EXISTING in self.completed_stages or Stage.FORMAT_HISTORY in self.completed_stages- ) and not self._has_execution_failures()-- def _has_execution_failures(self) -> bool:- """Check if any execution-related stages failed"""- execution_stages = {Stage.SETUP_BROWSER, Stage.RUN_AGENT, Stage.FORMAT_HISTORY}- return any(stage in self.failed_stages for stage in execution_stages)-- def _auto_update_payload(self):- """Automatically update server_payload based on current state"""- # Update execution data if available- if Stage.LOAD_EXISTING in self.completed_stages:- existing_data = self.stage_data[Stage.LOAD_EXISTING]- self.server_payload.update(- {- 'actionHistory': existing_data.get('action_history', []),- 'finalResultResponse': existing_data.get('final_result_response', 'None'),- 'selfReportCompleted': existing_data.get('self_report_completed', False),- 'selfReportSuccess': existing_data.get('self_report_success', None),- 'completeHistory': existing_data.get('complete_history', []),- 'taskDuration': existing_data.get('task_duration'),- 'steps': existing_data.get('steps', 0),- 'tokensUsed': existing_data.get('tokensUsed', 0),+ except Exception as err:+ return {+ 'task_id': task_folder.name,+ 'judgement': None,+ 'success': False,+ 'error': f'{type(err).__name__}: {err}',+ 'score': 0.0,}- )- elif Stage.FORMAT_HISTORY in self.completed_stages:- formatted_data = self.stage_data[Stage.FORMAT_HISTORY]- self.server_payload.update(- {- 'actionHistory': formatted_data.get('action_history', []),- 'finalResultResponse': formatted_data.get('final_result_response', 'None'),- 'selfReportCompleted': formatted_data.get('self_report_completed', False),- 'selfReportSuccess': formatted_data.get('self_report_success', None),- 'completeHistory': formatted_data.get('complete_history', []),- 'taskDuration': formatted_data.get('task_duration'),- 'steps': formatted_data.get('steps', 0),- 'tokensUsed': formatted_data.get('tokensUsed', 0),- }- )- # Update evaluation data if available- if Stage.EVALUATE in self.completed_stages:- eval_data = self.stage_data[Stage.EVALUATE]- judgement = eval_data.get('judgement')- self.server_payload.update(- {- 'onlineMind2WebEvaluationJudgement': judgement if judgement is not None else 'None',- 'onlineMind2WebEvaluationError': eval_data.get('error'),- 'onlineMind2WebEvaluationSuccess': eval_data.get('success', False),- 'onlineMind2WebEvaluationScore': eval_data.get('score', 0.0),+ else:+ # Use the new comprehensive judge system (default)+ logger.info(f'Task {task_folder.name}: Using comprehensive judge evaluation')++ # Check if comprehensive judge result already exists+ if result.get('comprehensive_judge_evaluation'):+ existing_eval = result['comprehensive_judge_evaluation']+ return {+ 'task_id': task_folder.name,+ 'judgement': existing_eval.get('reasoning', 'Comprehensive evaluation completed'),+ 'success': existing_eval.get('passed', False),+ 'error': None,+ 'score': existing_eval.get('final_score', 0) / 100.0, # Convert to 0-1 scale+ 'comprehensive_evaluation': existing_eval,}- )- # Update failure states- self._update_failure_states()-- def _update_failure_states(self):- """Update server payload based on failed stages"""- # Check for browser/execution failures- for stage, error in self.failed_stages.items():- if stage in {Stage.SETUP_BROWSER, Stage.RUN_AGENT}:- self.server_payload['browserCrash'] = True- if error.error_type == 'timeout':- self.server_payload['browserCrashReason'] = f'{stage.value} timed out: {error.message}'- elif error.error_type == 'cancelled':- self.server_payload['browserCrashReason'] = f'{stage.value} was cancelled: {error.message}'- else:- self.server_payload['browserCrashReason'] = f'{stage.value} failed: {error.message}'-- # Update evaluation failures- elif stage == Stage.EVALUATE:- if error.error_type == 'timeout':- self.server_payload['onlineMind2WebEvaluationJudgement'] = 'Evaluation Timed Out'- self.server_payload['onlineMind2WebEvaluationError'] = 'Evaluation process timed out'- elif error.error_type == 'cancelled':- self.server_payload['onlineMind2WebEvaluationJudgement'] = 'Evaluation Cancelled'- self.server_payload['onlineMind2WebEvaluationError'] = 'Evaluation was cancelled'- else:- self.server_payload['onlineMind2WebEvaluationJudgement'] = 'Evaluation Process Error'- self.server_payload['onlineMind2WebEvaluationError'] = f'Evaluation Error: {error.message}'+ try:+ # Run comprehensive judge evaluation+ comprehensive_result = await evaluate_task_with_comprehensive_judge(+ task_folder=task_folder, model=model, max_images=10+ )- def mark_cancelled(self):- """Mark task as cancelled"""- self.server_payload.update(- {- 'finalResultResponse': 'Task was cancelled',- 'onlineMind2WebEvaluationJudgement': 'Task Cancelled',- 'onlineMind2WebEvaluationError': 'Task was cancelled',- 'onlineMind2WebEvaluationSuccess': False,- 'onlineMind2WebEvaluationScore': 0.0,- }- )- self.local_error = 'Task cancelled'-- def mark_critical_error(self, error_msg: str):- """Mark task as having critical error"""- self.server_payload.update(- {- 'finalResultResponse': f'Critical Error: {error_msg}',- 'onlineMind2WebEvaluationJudgement': 'Critical System Error',- 'onlineMind2WebEvaluationError': f'Critical flow error: {error_msg}',- 'onlineMind2WebEvaluationSuccess': False,- 'onlineMind2WebEvaluationScore': 0.0,- }- )- self.local_error = f'Critical flow error: {error_msg}'+ if comprehensive_result.get('error'):+ return {+ 'task_id': task_folder.name,+ 'judgement': None,+ 'success': False,+ 'error': comprehensive_result['error'],+ 'score': 0.0,+ }- def mark_server_save_failed(self, error_msg: str):- """Mark server save as failed"""- if self.local_error:- self.local_error += f'; Server save failed: {error_msg}'- else:- self.local_error = f'Server save failed: {error_msg}'+ comp_eval = comprehensive_result.get('comprehensive_judge')+ if comp_eval:+ return {+ 'task_id': task_folder.name,+ 'judgement': comp_eval.get('reasoning', 'Comprehensive evaluation completed'),+ 'success': comp_eval.get('passed', False),+ 'error': None,+ 'score': comp_eval.get('final_score', 0) / 100.0, # Convert to 0-1 scale+ 'comprehensive_evaluation': comp_eval,+ }+ else:+ return {+ 'task_id': task_folder.name,+ 'judgement': None,+ 'success': False,+ 'error': 'Comprehensive judge failed to return results',+ 'score': 0.0,+ }- def get_local_status(self) -> dict:- """Return local processing status"""- success = self.execution_succeeded() and (- Stage.EVALUATE in self.completed_stages or not self.has_execution_data() or Stage.EVALUATE in self.failed_stages- )- return {'task_id': self.task_id, 'success': success and not self.local_error, 'error': self.local_error}+ except Exception as err:+ logger.error(f'Comprehensive judge evaluation failed for {task_folder.name}: {err}')+ return {+ 'task_id': task_folder.name,+ 'judgement': None,+ 'success': False,+ 'error': f'Comprehensive judge error: {type(err).__name__}: {err}',+ 'score': 0.0,+ }++ except Exception as err:+ return {+ 'task_id': task_folder.name,+ 'judgement': None,+ 'success': False,+ 'error': f'{type(err).__name__}: {err}',+ 'score': 0.0,+ }async def run_stage(stage: Stage, stage_func, timeout: int | None = None):@@ -1357,9 +1314,9 @@ async def run_agent_with_browser(@observe(name='evaluate_task_result', span_type='EVALUATOR') # type: ignore[arg-type]-async def evaluate_task_result(eval_model: BaseChatModel, task_folder: Path) -> dict:+async def evaluate_task_result(eval_model: BaseChatModel, task_folder: Path, use_mind2web: bool = False) -> dict:"""Evaluate the task result"""- return await judge_task_result(eval_model, task_folder, score_threshold=3)+ return await judge_task_result(eval_model, task_folder, score_threshold=3, use_mind2web=use_mind2web)def save_result_to_server(convex_url: str, secret_key: str, payload: dict) -> bool:@@ -1421,6 +1378,7 @@ async def run_task_with_semaphore(planner_interval: int = 1,include_result: bool = False,highlight_elements: bool = True,+ use_mind2web_judge: bool = False,) -> dict:"""Clean pipeline approach for running tasks"""task_start_time = time.time()@@ -1573,7 +1531,7 @@ async def run_task_with_semaphore(try:logger.info(f'Task {task.task_id}: Evaluation starting.')evaluation = await run_stage(- Stage.EVALUATE, lambda: evaluate_task_result(eval_model, task_folder), timeout=300+ Stage.EVALUATE, lambda: evaluate_task_result(eval_model, task_folder, use_mind2web_judge), timeout=300)task_result.stage_completed(Stage.EVALUATE, evaluation)logger.info(f'Task {task.task_id}: Evaluation completed.')@@ -1752,6 +1710,7 @@ async def run_multiple_tasks(planner_interval: int = 1,include_result: bool = False,highlight_elements: bool = True,+ use_mind2web_judge: bool = False,) -> dict:"""Run multiple tasks in parallel and evaluate results.@@ -1829,6 +1788,7 @@ async def run_multiple_tasks(planner_interval=planner_interval,include_result=include_result,highlight_elements=highlight_elements,+ use_mind2web_judge=use_mind2web_judge,)for task in tasks_to_run),@@ -2104,6 +2064,7 @@ async def run_evaluation_pipeline(include_result: bool = False,laminar_eval_id: str | None = None,highlight_elements: bool = True,+ use_mind2web_judge: bool = False,) -> dict:"""Complete evaluation pipeline that handles Laminar setup and task execution in the same event loop@@ -2154,6 +2115,7 @@ async def run_evaluation_pipeline(planner_interval=planner_interval,include_result=include_result,highlight_elements=highlight_elements,+ use_mind2web_judge=use_mind2web_judge,)@@ -2221,6 +2183,7 @@ if __name__ == '__main__':default=None,help='Existing Laminar evaluation ID to use (if not provided, a new evaluation will be created)',)+ parser.add_argument('--use-mind2web-judge', action='store_true', help='Use original judge')args = parser.parse_args()@@ -2449,6 +2412,7 @@ if __name__ == '__main__':include_result=args.include_result,laminar_eval_id=args.laminar_eval_id,highlight_elements=args.highlight_elements,+ use_mind2web_judge=args.use_mind2web_judge,))