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59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
#!/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()