Skip to content

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

Refactor evaluate_tasks.py to run agent tasks in separate subprocesses, enhancing isolation and error handling. Introduce argparse for task selection and improve logging management during task execution.

Magnus Müller592b9afbcecf
diff --git a/tests/ci/evaluate_tasks.py b/tests/ci/evaluate_tasks.py
index 75db79708..6154ae83e 100644
--- a/tests/ci/evaluate_tasks.py
+++ b/tests/ci/evaluate_tasks.py
@@ -1,12 +1,17 @@
"""
-Runs all agent tasks in parallel (up to 10 at a time) and prints a big score summary.
+Runs all agent tasks in parallel (up to 10 at a time) using separate subprocesses.
+Each task gets its own Python process, preventing browser session interference.
Does not fail on partial failures (always exits 0).
"""
+import argparse
import asyncio
import glob
+import json
+import logging
import os
import sys
+import warnings
import aiofiles
import yaml
@@ -20,7 +25,11 @@ from browser_use.browser.session import BrowserSession
# --- CONFIG ---
MAX_PARALLEL = 10
-TASK_DIR = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(__file__), '../agent_tasks')
+TASK_DIR = (
+ sys.argv[1]
+ if len(sys.argv) > 1 and not sys.argv[1].startswith('--')
+ else os.path.join(os.path.dirname(__file__), '../agent_tasks')
+)
TASK_FILES = glob.glob(os.path.join(TASK_DIR, '*.yaml'))
@@ -29,8 +38,15 @@ class JudgeResponse(BaseModel):
explanation: str
-async def run_task(task_file, semaphore):
- async with semaphore:
+async def run_single_task(task_file):
+ """Run a single task in the current process (called by subprocess)"""
+ try:
+ # Suppress all logging in subprocess to avoid interfering with JSON output
+ logging.getLogger().setLevel(logging.CRITICAL)
+ for logger_name in ['browser_use', 'telemetry', 'message_manager']:
+ logging.getLogger(logger_name).setLevel(logging.CRITICAL)
+ warnings.filterwarnings('ignore')
+
async with aiofiles.open(task_file, 'r') as f:
content = await f.read()
task_data = yaml.safe_load(content)
@@ -40,18 +56,18 @@ async def run_task(task_file, semaphore):
agent_llm = ChatOpenAI(model='gpt-4.1-mini')
judge_llm = ChatOpenAI(model='gpt-4.1-mini')
- # Each agent gets its own profile and session, with --no-sandbox
+ # Each subprocess gets its own profile and session
profile = BrowserProfile(
headless=True,
user_data_dir=None,
- args=['--no-sandbox'],
- keep_alive=False, # or just omit this line
)
session = BrowserSession(browser_profile=profile)
+
agent = Agent(task=task, llm=agent_llm, browser_session=session)
history: AgentHistoryList = await agent.run(max_steps=max_steps)
agent_output = history.final_result() or ''
- criteria = chr(10) + '- '.join(judge_context)
+
+ criteria = '\n- '.join(judge_context)
judge_prompt = f"""
You are a evaluator of a browser agent task inside a ci/cd pipeline. Here was the agent's task:
{task}
@@ -66,15 +82,100 @@ Reply in JSON with keys: success (true/false), explanation (string).
"""
structured_llm = judge_llm.with_structured_output(JudgeResponse)
judge_response = await structured_llm.ainvoke(judge_prompt)
- return {'file': os.path.basename(task_file), 'success': judge_response.success, 'explanation': judge_response.explanation}
+
+ result = {
+ 'file': os.path.basename(task_file),
+ 'success': judge_response.success,
+ 'explanation': judge_response.explanation,
+ }
+
+ # Clean up session before returning
+ await session.stop()
+
+ return result
+
+ except Exception as e:
+ # Ensure session cleanup even on error
+ try:
+ await session.stop()
+ except Exception:
+ pass
+
+ return {'file': os.path.basename(task_file), 'success': False, 'explanation': f'Task failed with error: {str(e)}'}
+
+
+async def run_task_subprocess(task_file, semaphore):
+ """Run a task in a separate subprocess"""
+ async with semaphore:
+ try:
+ # Set environment to reduce noise in subprocess
+ env = os.environ.copy()
+ env['PYTHONPATH'] = os.pathsep.join(sys.path)
+
+ proc = await asyncio.create_subprocess_exec(
+ sys.executable,
+ __file__,
+ '--task',
+ task_file,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ env=env,
+ )
+ stdout, stderr = await proc.communicate()
+
+ if proc.returncode == 0:
+ try:
+ # Parse JSON result from subprocess
+ stdout_text = stdout.decode().strip()
+ # Find the JSON line (should be the last line that starts with {)
+ lines = stdout_text.split('\n')
+ json_line = None
+ for line in reversed(lines):
+ line = line.strip()
+ if line.startswith('{') and line.endswith('}'):
+ json_line = line
+ break
+
+ if json_line:
+ result = json.loads(json_line)
+ else:
+ raise ValueError(f'No JSON found in output: {stdout_text}')
+
+ except (json.JSONDecodeError, ValueError) as e:
+ result = {
+ 'file': os.path.basename(task_file),
+ 'success': False,
+ 'explanation': f'Failed to parse subprocess result: {str(e)[:100]}',
+ }
+ else:
+ stderr_text = stderr.decode().strip()
+ result = {
+ 'file': os.path.basename(task_file),
+ 'success': False,
+ 'explanation': f'Subprocess failed (code {proc.returncode}): {stderr_text[:200]}',
+ }
+ except Exception as e:
+ result = {
+ 'file': os.path.basename(task_file),
+ 'success': False,
+ 'explanation': f'Failed to start subprocess: {str(e)}',
+ }
+
+ return result
async def main():
+ """Run all tasks in parallel using subprocesses"""
semaphore = asyncio.Semaphore(MAX_PARALLEL)
- # Create a single shared profile with keep_alive=True
- print(TASK_FILES)
- tasks = [run_task(task_file, semaphore) for task_file in TASK_FILES]
+ print(f'Found task files: {TASK_FILES}')
+
+ if not TASK_FILES:
+ print('No task files found!')
+ return 0, 0
+
+ # Run all tasks in parallel subprocesses
+ tasks = [run_task_subprocess(task_file, semaphore) for task_file in TASK_FILES]
results = await asyncio.gather(*tasks)
passed = sum(1 for r in results if r['success'])
@@ -112,6 +213,26 @@ async def main():
if __name__ == '__main__':
- passed, total = asyncio.run(main())
- print(f'PASSED={passed}')
- print(f'TOTAL={total}')
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--task', type=str, help='Path to a single task YAML file (for subprocess mode)')
+ args = parser.parse_args()
+
+ if args.task:
+ # Subprocess mode: run a single task and output ONLY JSON
+ try:
+ result = asyncio.run(run_single_task(args.task))
+ # Output ONLY the JSON result, nothing else
+ print(json.dumps(result))
+ except Exception as e:
+ # Even on critical failure, output valid JSON
+ error_result = {
+ 'file': os.path.basename(args.task),
+ 'success': False,
+ 'explanation': f'Critical subprocess error: {str(e)}',
+ }
+ print(json.dumps(error_result))
+ else:
+ # Parent process mode: run all tasks in parallel subprocesses
+ passed, total = asyncio.run(main())
+ print(f'PASSED={passed}')
+ print(f'TOTAL={total}')