Skip to content

The agent that grows with you

style: ruff lint + format on the eval scripts (encoding args, formatting)

Teknium21aa327c6972
diff --git a/evals/browser_use/orchestrate.py b/evals/browser_use/orchestrate.py
index f1d1d8cdc3e..010a1966a6b 100644
--- a/evals/browser_use/orchestrate.py
+++ b/evals/browser_use/orchestrate.py
@@ -11,6 +11,7 @@ Usage:
python3 orchestrate.py [--tasks tasks/hard.json] [--models m1,m2] \
[--arms base,pr,prns] [--reps 3]
"""
+
import argparse
import itertools
import json
@@ -36,12 +37,12 @@ args = parser.parse_args()
os.makedirs(os.path.dirname(args.results), exist_ok=True)
ARMS = args.arms.split(",")
MODELS = args.models.split(",")
-TASKS = list(json.load(open(args.tasks)).keys())
+TASKS = list(json.load(open(args.tasks, encoding="utf-8")).keys())
REPS = list(range(1, args.reps + 1))
done = set()
if os.path.exists(args.results):
- for line in open(args.results):
+ for line in open(args.results, encoding="utf-8"):
try:
r = json.loads(line)
done.add((r["arm"], r["task"], r["model"], r["rep"]))
@@ -55,7 +56,12 @@ def reset_browser_state():
code = "cdp('Network.clearBrowserCookies')\nprint('cleared')\n"
try:
subprocess.run(
- ["browser-use"], input=code, text=True, capture_output=True, timeout=120, env=ENV
+ ["browser-use"],
+ input=code,
+ text=True,
+ capture_output=True,
+ timeout=120,
+ env=ENV,
)
except Exception:
pass
@@ -85,22 +91,33 @@ for arm, task, model, rep in cells:
rec = None
for line in (proc.stdout or "").splitlines():
if line.startswith("RESULT_JSON:"):
- rec = json.loads(line[len("RESULT_JSON:"):])
+ rec = json.loads(line[len("RESULT_JSON:") :])
if rec is None:
rec = {
- "arm": arm, "task": task, "model": model, "rep": rep,
- "ok": False, "error": "no-result",
+ "arm": arm,
+ "task": task,
+ "model": model,
+ "rep": rep,
+ "ok": False,
+ "error": "no-result",
"stderr_tail": (proc.stderr or "")[-800:],
"stdout_tail": (proc.stdout or "")[-400:],
}
except subprocess.TimeoutExpired:
rec = {
- "arm": arm, "task": task, "model": model, "rep": rep,
- "ok": False, "error": f"orchestrator-timeout-{args.run_timeout}s",
+ "arm": arm,
+ "task": task,
+ "model": model,
+ "rep": rep,
+ "ok": False,
+ "error": f"orchestrator-timeout-{args.run_timeout}s",
}
rec["cell_wall_s"] = round(time.time() - t0, 1)
- with open(args.results, "a") as f:
+ with open(args.results, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
- print(f" -> ok={rec.get('ok')} err={rec.get('error')} wall={rec.get('cell_wall_s')}s", flush=True)
+ print(
+ f" -> ok={rec.get('ok')} err={rec.get('error')} wall={rec.get('cell_wall_s')}s",
+ flush=True,
+ )
print("BATTERY COMPLETE", flush=True)
diff --git a/evals/browser_use/orchestrate_cloud.py b/evals/browser_use/orchestrate_cloud.py
index 2cef2e923c6..5d2aa614f11 100644
--- a/evals/browser_use/orchestrate_cloud.py
+++ b/evals/browser_use/orchestrate_cloud.py
@@ -14,6 +14,7 @@ Usage:
Per cell: provision a session, export its CDP endpoint via BENCH_CDP_URL /
BU_CDP_WS, run single_run.py (pr arm), close the session. Resume-safe.
"""
+
import argparse
import itertools
import json
@@ -26,7 +27,9 @@ import urllib.request
ROOT = os.environ.get("BUBENCH_ROOT", os.path.dirname(os.path.abspath(__file__)))
PY = sys.executable
ENV_BASE = {**os.environ}
-ENV_BASE["PATH"] = os.path.expanduser("~/.local/bin") + os.pathsep + ENV_BASE.get("PATH", "")
+ENV_BASE["PATH"] = (
+ os.path.expanduser("~/.local/bin") + os.pathsep + ENV_BASE.get("PATH", "")
+)
parser = argparse.ArgumentParser()
parser.add_argument("--backend", required=True, choices=["nous-cloud", "browserbase"])
@@ -40,12 +43,12 @@ args = parser.parse_args()
RESULTS = args.results or os.path.join(ROOT, "results", f"results_{args.backend}.jsonl")
os.makedirs(os.path.dirname(RESULTS), exist_ok=True)
MODELS = args.models.split(",")
-TASKS = list(json.load(open(args.tasks)).keys())
+TASKS = list(json.load(open(args.tasks, encoding="utf-8")).keys())
REPS = list(range(1, args.reps + 1))
done = set()
if os.path.exists(RESULTS):
- for line in open(RESULTS):
+ for line in open(RESULTS, encoding="utf-8"):
try:
r = json.loads(line)
done.add((r["task"], r["model"], r["rep"]))
@@ -66,14 +69,18 @@ class NousCloud:
return sess, {"BENCH_CDP_URL": sess["cdp_url"]}
def close(self, sess):
- self._prov.close_session(sess.get("bb_session_id") or sess.get("session_name", ""))
+ self._prov.close_session(
+ sess.get("bb_session_id") or sess.get("session_name", "")
+ )
class Browserbase:
def create(self, name):
req = urllib.request.Request(
"https://api.browserbase.com/v1/sessions",
- data=json.dumps({"projectId": os.environ["BROWSERBASE_PROJECT_ID"]}).encode(),
+ data=json.dumps({
+ "projectId": os.environ["BROWSERBASE_PROJECT_ID"]
+ }).encode(),
headers={
"x-bb-api-key": os.environ["BROWSERBASE_API_KEY"],
"Content-Type": "application/json",
@@ -82,14 +89,18 @@ class Browserbase:
)
with urllib.request.urlopen(req, timeout=30) as resp:
sess = json.load(resp)
- return sess, {"BU_CDP_WS": sess["connectUrl"], "BENCH_CDP_URL": sess["connectUrl"]}
+ return sess, {
+ "BU_CDP_WS": sess["connectUrl"],
+ "BENCH_CDP_URL": sess["connectUrl"],
+ }
def close(self, sess):
req = urllib.request.Request(
f"https://api.browserbase.com/v1/sessions/{sess['id']}",
- data=json.dumps(
- {"projectId": os.environ["BROWSERBASE_PROJECT_ID"], "status": "REQUEST_RELEASE"}
- ).encode(),
+ data=json.dumps({
+ "projectId": os.environ["BROWSERBASE_PROJECT_ID"],
+ "status": "REQUEST_RELEASE",
+ }).encode(),
headers={
"x-bb-api-key": os.environ["BROWSERBASE_API_KEY"],
"Content-Type": "application/json",
@@ -115,10 +126,14 @@ for task, model, rep in cells:
sess, extra_env = provider.create(f"bubench-{task}-{rep}")
except Exception as e: # noqa: BLE001
rec = {
- "arm": f"pr-{args.backend}", "task": task, "model": model, "rep": rep,
- "ok": False, "error": f"session-create: {e}",
+ "arm": f"pr-{args.backend}",
+ "task": task,
+ "model": model,
+ "rep": rep,
+ "ok": False,
+ "error": f"session-create: {e}",
}
- with open(RESULTS, "a") as f:
+ with open(RESULTS, "a", encoding="utf-8") as f:
f.write(json.dumps(rec) + "\n")
continue
env = {**ENV_BASE, **extra_env, "BUBENCH_TASKS": args.tasks}
@@ -126,20 +141,30 @@ for task, model, rep in cells:
try:
proc = subprocess.run(
[PY, os.path.join(ROOT, "single_run.py"), "pr", task, model, str(rep)],
- capture_output=True, text=True, timeout=args.run_timeout, env=env,
+ capture_output=True,
+ text=True,
+ timeout=args.run_timeout,
+ env=env,
)
rec = None
for line in (proc.stdout or "").splitlines():
if line.startswith("RESULT_JSON:"):
- rec = json.loads(line[len("RESULT_JSON:"):])
+ rec = json.loads(line[len("RESULT_JSON:") :])
if rec is None:
rec = {
- "task": task, "model": model, "rep": rep, "ok": False,
- "error": "no-result", "stderr_tail": (proc.stderr or "")[-600:],
+ "task": task,
+ "model": model,
+ "rep": rep,
+ "ok": False,
+ "error": "no-result",
+ "stderr_tail": (proc.stderr or "")[-600:],
}
except subprocess.TimeoutExpired:
rec = {
- "task": task, "model": model, "rep": rep, "ok": False,
+ "task": task,
+ "model": model,
+ "rep": rep,
+ "ok": False,
"error": f"timeout-{args.run_timeout}s",
}
finally:
@@ -149,8 +174,11 @@ for task, model, rep in cells:
print(f" close warning: {e}", flush=True)
rec["arm"] = f"pr-{args.backend}"
rec["cell_wall_s"] = round(time.time() - t0, 1)
- with open(RESULTS, "a") as f:
+ with open(RESULTS, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
- print(f" -> ok={rec.get('ok')} err={rec.get('error')} wall={rec.get('cell_wall_s')}s", flush=True)
+ print(
+ f" -> ok={rec.get('ok')} err={rec.get('error')} wall={rec.get('cell_wall_s')}s",
+ flush=True,
+ )
print("CLOUD BATTERY COMPLETE", flush=True)
diff --git a/evals/browser_use/report.py b/evals/browser_use/report.py
index b77b88d00ce..8273f7a5adc 100644
--- a/evals/browser_use/report.py
+++ b/evals/browser_use/report.py
@@ -6,6 +6,7 @@ Usage:
Groups by (model, arm): ok-rate, token mean/median, tool calls, wall clock,
and token delta vs the ``base`` arm of the same model when present.
"""
+
import json
import statistics
import sys
@@ -15,7 +16,7 @@ from collections import defaultdict
def main(paths):
rows = []
for p in paths:
- for line in open(p):
+ for line in open(p, encoding="utf-8"):
try:
rows.append(json.loads(line))
except Exception:
@@ -38,7 +39,7 @@ def main(paths):
hdr = f"{'model':<34} {'arm':<16} {'ok':>7} {'tok_mean':>9} {'tok_med':>8} {'calls':>6} {'wall_s':>7} {'vs base':>8}"
print(hdr)
print("-" * len(hdr))
- for (model, arm) in sorted(cells):
+ for model, arm in sorted(cells):
rs = cells[(model, arm)]
oks = [r for r in rs if r.get("ok")]
n_ok, n = len(oks), len(rs)
@@ -60,7 +61,9 @@ def main(paths):
if errs:
print(f"\nerrors: {len(errs)}")
for r in errs[:10]:
- print(f" {r.get('model')}/{r.get('arm')}/{r.get('task')}/rep{r.get('rep')}: {r['error'][:120]}")
+ print(
+ f" {r.get('model')}/{r.get('arm')}/{r.get('task')}/rep{r.get('rep')}: {r['error'][:120]}"
+ )
if __name__ == "__main__":
diff --git a/evals/browser_use/single_run.py b/evals/browser_use/single_run.py
index 04aabdd08d4..411ca4a194b 100644
--- a/evals/browser_use/single_run.py
+++ b/evals/browser_use/single_run.py
@@ -23,6 +23,7 @@ the browser (no web_extract shortcuts).
Prints one line: ``RESULT_JSON:{...}`` consumed by orchestrate.py.
"""
+
import json
import os
import re
@@ -38,7 +39,7 @@ PR_TREE = os.environ["BUBENCH_PR_TREE"]
WT = {"base": BASE_TREE, "pr": PR_TREE, "prns": PR_TREE}[ARM]
TASKS_PATH = os.environ.get("BUBENCH_TASKS", os.path.join(ROOT, "tasks", "hard.json"))
-TASKS = json.load(open(TASKS_PATH))
+TASKS = json.load(open(TASKS_PATH, encoding="utf-8"))
task = TASKS[TASK_KEY]
home = tempfile.mkdtemp(prefix=f"buhome-{ARM}-")
@@ -57,7 +58,7 @@ cfg = {
}
import yaml
-with open(os.path.join(hh, "config.yaml"), "w") as f:
+with open(os.path.join(hh, "config.yaml"), "w", encoding="utf-8") as f:
yaml.safe_dump(cfg, f)
os.environ["HERMES_HOME"] = hh
# Strip web-fetch shortcuts: every arm must drive the browser.
@@ -65,7 +66,9 @@ os.environ.pop("BROWSER_USE_API_KEY", None)
for k in ("FIRECRAWL_API_KEY", "NOUS_API_KEY", "TAVILY_API_KEY", "SERPER_API_KEY"):
os.environ.pop(k, None)
os.environ["BU_CDP_URL"] = cdp
-os.environ["PATH"] = os.path.expanduser("~/.local/bin") + os.pathsep + os.environ.get("PATH", "")
+os.environ["PATH"] = (
+ os.path.expanduser("~/.local/bin") + os.pathsep + os.environ.get("PATH", "")
+)
sys.path.insert(0, WT)
import logging
@@ -119,7 +122,11 @@ final = ""
messages = []
try:
result = agent.run_conversation(task["prompt"])
- final = (result.get("final_response") or "") if isinstance(result, dict) else str(result)
+ final = (
+ (result.get("final_response") or "")
+ if isinstance(result, dict)
+ else str(result)
+ )
messages = result.get("messages", []) if isinstance(result, dict) else []
except Exception as e: # noqa: BLE001
error = f"{type(e).__name__}: {e}"
@@ -130,15 +137,21 @@ tool_calls = []
for m in messages:
if isinstance(m, dict) and m.get("role") == "assistant":
for tc in m.get("tool_calls") or []:
- fn = (tc.get("function") or {}).get("name") if isinstance(tc, dict) else None
+ fn = (
+ (tc.get("function") or {}).get("name") if isinstance(tc, dict) else None
+ )
if fn:
tool_calls.append(fn)
def _ok(text: str) -> bool:
if task.get("oracle_all"):
- return all(re.search(re.escape(x), text, re.IGNORECASE) for x in task["oracle_all"])
- return any(re.search(re.escape(x), text, re.IGNORECASE) for x in task.get("oracle_any", []))
+ return all(
+ re.search(re.escape(x), text, re.IGNORECASE) for x in task["oracle_all"]
+ )
+ return any(
+ re.search(re.escape(x), text, re.IGNORECASE) for x in task.get("oracle_any", [])
+ )
out = {
@@ -151,7 +164,9 @@ out = {
"prompt_tokens": getattr(agent, "session_prompt_tokens", 0),
"completion_tokens": getattr(agent, "session_completion_tokens", 0),
"total_tokens": getattr(agent, "session_total_tokens", 0),
- "api_calls": len([m for m in messages if isinstance(m, dict) and m.get("role") == "assistant"]),
+ "api_calls": len([
+ m for m in messages if isinstance(m, dict) and m.get("role") == "assistant"
+ ]),
"tool_calls": len(tool_calls),
"tool_call_names": tool_calls,
"browser_schema_chars": schema_desc_len,