FinanceGym / run_eval.py
Machivelli's picture embodied-analysis's picture
Duplicate from embodied-analysis/FinanceGym
14a6861
Raw History Blame Contribute Delete
18.9 kB
#!/usr/bin/env python3
"""Run and score OpenRouter models on the FinanceGym test split.
The output is resumable: one JSONL file is maintained per model and existing
task/rollout pairs are skipped. Each API call requests one completion because
OpenRouter providers do not consistently support ``n > 1``.
Example:
python scripts/run_openrouter_rollouts.py data/test-*.parquet
python scripts/run_openrouter_rollouts.py data/test-*.parquet --limit 2
"""
from __future__ import annotations
import argparse
import base64
import glob
import json
import os
import random
import re
import sys
import threading
import time
from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
from difflib import SequenceMatcher
from pathlib import Path
from typing import Any
import requests
try:
import pyarrow.parquet as pq
except ImportError:
sys.exit("Missing dependency: install with `python -m pip install pyarrow requests`.")
DEFAULT_MODELS = [
"moonshotai/kimi-k2.6",
"moonshotai/kimi-k3",
"qwen/qwen3.8-max",
"bytedance-seed/seed-2-1-turbo"
]
OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
TRANSIENT_HTTP = {408, 409, 425, 429, 500, 502, 503, 504, 522, 524}
SYSTEM_PROMPT = (
"You are a GUI agent operating a computer via screenshots. At each step, "
"decide the next UI action and call the `computer_use` tool with the "
"appropriate action and arguments. Coordinates are on a 0-999 grid. Call "
"the tool exactly once per step; do not output the action as plain text."
)
COORD_TOL = 50.0
CLICK_VERBS = {
"left_click", "right_click", "double_click", "triple_click", "mouse_move",
"left_mouse_down", "left_mouse_up",
}
WRITE_LOCK = threading.Lock()
PRINT_LOCK = threading.Lock()
def load_key(env_file: Path) -> str:
for name in ("OPENROUTER_API_KEY", "OPENROUTER_KEY"):
if os.environ.get(name):
return os.environ[name].strip().strip("\"'")
if env_file.exists():
for raw in env_file.read_text().splitlines():
line = raw.strip()
for name in ("OPENROUTER_API_KEY", "OPENROUTER_KEY"):
if line.startswith(name + "="):
return line.split("=", 1)[1].strip().strip("\"'")
raise SystemExit(f"No OPENROUTER_KEY or OPENROUTER_API_KEY found in env or {env_file}")
def data_url(image: Any) -> str:
if isinstance(image, dict):
blob = image.get("bytes")
if blob is None and image.get("path"):
blob = Path(image["path"]).read_bytes()
else:
blob = image
if isinstance(blob, memoryview):
blob = blob.tobytes()
if not isinstance(blob, bytes):
raise TypeError(f"Unsupported image value: {type(image)!r}")
return "data:image/jpeg;base64," + base64.b64encode(blob).decode("ascii")
def openai_messages(row: dict[str, Any]) -> list[dict[str, Any]]:
images = row["images"]
messages: list[dict[str, Any]] = []
for source in row["messages"]:
parts = []
for part in source.get("content") or []:
if part.get("type") == "text":
parts.append({"type": "text", "text": part.get("text") or ""})
elif part.get("type") == "image":
parts.append({
"type": "image_url",
"image_url": {"url": data_url(images[part["image_index"]])},
})
message: dict[str, Any] = {"role": source["role"], "content": parts}
if source.get("tool_calls"):
message["tool_calls"] = source["tool_calls"]
if source.get("tool_call_id") is not None:
message["tool_call_id"] = source["tool_call_id"]
messages.append(message)
if messages and messages[0]["role"] == "system":
messages[0] = {"role": "system", "content": SYSTEM_PROMPT}
else:
messages.insert(0, {"role": "system", "content": SYSTEM_PROMPT})
return messages
def parse_actions(message: dict[str, Any]) -> list[dict[str, Any]]:
actions = []
for call in message.get("tool_calls") or []:
fn = call.get("function") or {}
value = fn.get("arguments")
try:
value = json.loads(value) if isinstance(value, str) else value
except json.JSONDecodeError:
continue
if isinstance(value, dict):
actions.append(value)
if actions:
return actions
content = message.get("content") or ""
if isinstance(content, list):
content = " ".join(p.get("text", "") for p in content if isinstance(p, dict))
for match in re.finditer(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", content, re.S):
try:
value = json.loads(match.group(1))
value = value.get("arguments", value)
value = json.loads(value) if isinstance(value, str) else value
if isinstance(value, dict):
actions.append(value)
except (json.JSONDecodeError, AttributeError):
pass
return actions
def coord_score(a: Any, b: Any) -> float:
try:
distance = ((float(a[0]) - float(b[0])) ** 2 + (float(a[1]) - float(b[1])) ** 2) ** 0.5
return max(0.0, 1.0 - distance / COORD_TOL)
except (TypeError, ValueError, IndexError):
return 0.0
def pair_score(pred: dict[str, Any], gt: dict[str, Any]) -> float:
if pred.get("action") != gt.get("action"):
return 0.0
verb = gt.get("action")
values = []
if verb in CLICK_VERBS or "coordinate" in gt:
values.append(coord_score(pred.get("coordinate"), gt.get("coordinate")))
if verb == "type":
a, b = str(pred.get("text") or "").strip(), str(gt.get("text") or "").strip()
values.append(1.0 if a == b else 0.9 if a.lower() == b.lower() else SequenceMatcher(None, a, b).ratio())
if verb == "key":
a, b = [str(x).lower() for x in pred.get("keys") or []], [str(x).lower() for x in gt.get("keys") or []]
remaining, common = list(b), 0
for key in a:
if key in remaining:
common += 1
remaining.remove(key)
values.append(common / (max(len(a), len(b)) or 1))
if verb == "scroll" and pred.get("pixels") is not None and gt.get("pixels") is not None:
p, g = float(pred["pixels"]), float(gt["pixels"])
same_direction = (p >= 0) == (g >= 0)
magnitude = 1.0 - min(1.0, abs(p - g) / (abs(g) + 1e-6))
values.append((0.5 if same_direction else 0.0) + 0.5 * max(0.0, magnitude))
if verb == "terminate":
values.append(float(pred.get("status") == gt.get("status")))
return sum(values) / len(values) if values else 1.0
def normalize_drags(actions: list[dict[str, Any]]) -> list[dict[str, Any]]:
out, index = [], 0
while index < len(actions):
action = actions[index]
if (index + 2 < len(actions) and action.get("action") == "left_mouse_down"
and actions[index + 1].get("action") == "mouse_move"
and actions[index + 2].get("action") == "left_mouse_up"):
out.append({"action": "drag", "start": action.get("coordinate"),
"end": actions[index + 2].get("coordinate") or actions[index + 1].get("coordinate")})
index += 3
elif action.get("action") == "left_click_drag":
out.append({"action": "drag", "start": None, "end": action.get("coordinate")})
index += 1
else:
out.append(action)
index += 1
return out
def score(message: dict[str, Any], ground_truth: str) -> tuple[float, list[dict[str, Any]]]:
pred = normalize_drags(parse_actions(message))
gt = normalize_drags(json.loads(ground_truth))
if not gt or not pred:
return 0.0, pred
total = 0.0
for index, expected in enumerate(gt):
if index >= len(pred):
continue
actual = pred[index]
if expected.get("action") == actual.get("action") == "drag":
values = [coord_score(actual.get("end"), expected.get("end"))]
if actual.get("start") is not None and expected.get("start") is not None:
values.append(coord_score(actual["start"], expected["start"]))
total += sum(values) / len(values)
else:
total += pair_score(actual, expected)
return total / max(len(gt), len(pred)), pred
def retry_delay(response: requests.Response | None, attempt: int, maximum: float) -> float:
"""Honor Retry-After, otherwise use capped exponential backoff + full jitter."""
if response is not None:
value = response.headers.get("Retry-After")
if value:
try:
return min(maximum, max(0.0, float(value)))
except ValueError:
pass
if response.status_code == 429:
# Provider-wide TPM limits need a materially longer pause than a
# transport failure; short retries create a thundering herd.
low = min(maximum, 10.0 * (2.0 ** attempt))
high = min(maximum, 20.0 * (2.0 ** attempt))
return random.uniform(low, max(low, high))
ceiling = min(maximum, 2.0 ** attempt)
return random.uniform(0.5, max(0.5, ceiling))
def api_call(key: str, payload: dict[str, Any], timeout: int, retries: int,
max_backoff: float) -> tuple[dict[str, Any] | None, str | None, bool]:
"""Return (response, error, retryable).
OpenRouter may route successive requests to different providers. Transient
statuses are retried here; if exhausted, retryable=True ensures a later
program invocation attempts the rollout again.
"""
headers = {"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
last_error = None
retryable = True
for attempt in range(retries):
response = None
try:
response = requests.post(OPENROUTER_URL, headers=headers, json=payload, timeout=timeout)
if response.status_code == 200:
body = response.json()
if body.get("choices"):
return body, None, False
last_error = f"empty response: {str(body)[:300]}"
else:
last_error = f"HTTP {response.status_code}: {response.text[:500]}"
retryable = response.status_code in TRANSIENT_HTTP
if not retryable:
break
except (requests.Timeout, requests.ConnectionError) as exc:
last_error = f"{type(exc).__name__}: {exc}"
retryable = True
except requests.RequestException as exc:
last_error = f"{type(exc).__name__}: {exc}"
retryable = False
break
if attempt + 1 < retries:
delay = retry_delay(response, attempt, max_backoff)
with PRINT_LOCK:
print(f" retry {attempt + 1}/{retries - 1} in {delay:.1f}s: {last_error[:180]}", flush=True)
time.sleep(delay)
return None, last_error, retryable
def count_rows(paths: list[str], limit: int) -> int:
total = sum(pq.ParquetFile(path).metadata.num_rows for path in paths)
return min(total, limit) if limit else total
def iter_rows(paths: list[str], limit: int):
task_id = 0
for path in paths:
parquet = pq.ParquetFile(path)
for batch in parquet.iter_batches(batch_size=8):
for row in batch.to_pylist():
row["task_id"] = task_id
yield row
task_id += 1
if limit and task_id >= limit:
return
def safe_name(model: str) -> str:
return re.sub(r"[^A-Za-z0-9._-]+", "__", model)
def normalized_tools(value: Any) -> list[dict[str, Any]]:
"""Return provider-portable JSON Schema for the dataset's native tools."""
tools = json.loads(value) if isinstance(value, str) else value
# Round-trip so the Parquet row is never mutated across model calls.
tools = json.loads(json.dumps(tools))
for tool in tools:
properties = (((tool.get("function") or {}).get("parameters") or {})
.get("properties") or {})
for name, schema in properties.items():
if schema.get("type") == "array" and "items" not in schema:
schema["items"] = {"type": "number" if name == "coordinate" else "string"}
return tools
def completed_keys(path: Path) -> set[tuple[int, int]]:
done = set()
if path.exists():
for line in path.read_text().splitlines():
try:
item = json.loads(line)
# Failed attempts remain eligible on the next invocation.
if item.get("ok") and item.get("score") is not None:
done.add((int(item["task_id"]), int(item["rollout"])))
except (json.JSONDecodeError, KeyError, ValueError):
pass
return done
def run_one(key: str, model: str, row: dict[str, Any], rollout: int, args: argparse.Namespace) -> dict[str, Any]:
payload = {
"model": model,
"messages": openai_messages(row),
"tools": normalized_tools(row["tools"]),
"tool_choice": "auto",
"temperature": args.temperature,
"max_tokens": args.max_tokens,
}
body, error, retryable = api_call(
key, payload, args.timeout, args.retries, args.max_backoff
)
if body:
message = body["choices"][0].get("message") or {}
value, actions = score(message, row["ground_truth"])
return {"task_id": row["task_id"], "rollout": rollout, "score": value,
"ok": True, "actions": actions, "message": message,
"usage": body.get("usage")}
return {"task_id": row["task_id"], "rollout": rollout, "score": None,
"ok": False, "retryable": retryable, "error": error}
def summarize(path: Path, model: str) -> dict[str, Any]:
records = [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
good = [r for r in records if r.get("ok") and r.get("score") is not None]
task_scores: dict[int, list[float]] = {}
for item in good:
task_scores.setdefault(item["task_id"], []).append(float(item["score"]))
per_task = [sum(values) / len(values) for values in task_scores.values()]
return {"model": model, "successful_rollouts": len(good), "total_records": len(records),
"tasks_with_success": len(task_scores),
"average_score": sum(per_task) / len(per_task) if per_task else None}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", nargs="+", help="Input Parquet file(s); shell globs are accepted")
parser.add_argument("--models", nargs="+", default=DEFAULT_MODELS)
parser.add_argument("--rollouts", type=int, default=1)
parser.add_argument("--output-dir", type=Path, default=Path("openrouter_rollouts"))
parser.add_argument("--env-file", type=Path, default=Path.home() / ".env")
parser.add_argument("--concurrency", type=int, default=8)
parser.add_argument("--temperature", type=float, default=1.0)
parser.add_argument("--max-tokens", type=int, default=2048)
parser.add_argument("--timeout", type=int, default=300)
parser.add_argument("--retries", type=int, default=5)
parser.add_argument("--max-backoff", type=float, default=60.0,
help="Maximum seconds between API retries")
parser.add_argument("--limit", type=int, default=0, help="Only run the first N tasks (smoke tests)")
args = parser.parse_args()
if args.rollouts < 1 or args.concurrency < 1:
parser.error("--rollouts and --concurrency must be positive")
paths = sorted({p for pattern in args.input for p in (glob.glob(pattern) or [pattern])})
missing = [p for p in paths if not Path(p).is_file()]
if missing:
parser.error("Input file(s) not found: " + ", ".join(missing))
key = load_key(args.env_file)
row_count = count_rows(paths, args.limit)
args.output_dir.mkdir(parents=True, exist_ok=True)
print(f"Found {row_count} test tasks in {len(paths)} file(s)", flush=True)
summaries = []
for model in args.models:
path = args.output_dir / f"{safe_name(model)}.jsonl"
done = completed_keys(path)
pending_count = row_count * args.rollouts - len(done)
print(f"{model}: completed={len(done)} pending={pending_count}", flush=True)
with path.open("a", encoding="utf-8") as output, ThreadPoolExecutor(max_workers=args.concurrency) as pool:
futures = {}
completed = 0
def collect(future) -> None:
nonlocal completed
try:
record = future.result()
except Exception as exc:
task_id, rollout = futures[future]
record = {"task_id": task_id, "rollout": rollout, "score": None,
"ok": False, "retryable": True,
"error": f"{type(exc).__name__}: {exc}"}
output.write(json.dumps(record, ensure_ascii=False) + "\n")
output.flush()
completed += 1
if completed % 25 == 0 or completed == pending_count:
print(f" {model}: {completed}/{pending_count} new rollouts", flush=True)
for row in iter_rows(paths, args.limit):
for rollout in range(args.rollouts):
if (row["task_id"], rollout) in done:
continue
while len(futures) >= args.concurrency * 2:
finished, _ = wait(futures, return_when=FIRST_COMPLETED)
for future in finished:
collect(future)
del futures[future]
future = pool.submit(run_one, key, model, row, rollout, args)
futures[future] = (row["task_id"], rollout)
while futures:
finished, _ = wait(futures, return_when=FIRST_COMPLETED)
for future in finished:
collect(future)
del futures[future]
result = summarize(path, model)
summaries.append(result)
print(json.dumps(result, ensure_ascii=False), flush=True)
summary_path = args.output_dir / "summary.json"
combined = {}
if summary_path.exists():
try:
combined = {item["model"]: item for item in json.loads(summary_path.read_text())}
except (json.JSONDecodeError, KeyError, TypeError):
combined = {}
combined.update({item["model"]: item for item in summaries})
summary_path.write_text(json.dumps(list(combined.values()), indent=2) + "\n")
print(f"Summary written to {summary_path}")
if __name__ == "__main__":
main()