File size: 3,630 Bytes
99e41a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
#!/usr/bin/env python3
"""ERQA with hosted VLM agents (OpenAI-compatible endpoints), one thread per agent, resumable.

  GROQ_API_KEY=... CEREBRAS_API_KEY=... GEMINI_API_KEY=... python scripts/erqa_api_agents.py [agent ...]
Writes results/erqa/<agent>.jsonl with the raw reply and the extracted letter.
"""
import base64  # noqa: I001
import io
import json
import re
import sys
import threading
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from robotics.benchmarks import erqa  # noqa: E402
from robotics.llm.providers import LLMError, chat  # noqa: E402

AGENTS = {
    "gemini-3.1-flash-lite": ("gemini", "gemini-3.1-flash-lite", 4.5),
    "gemini-3.5-flash-lite": ("gemini", "gemini-3.5-flash-lite", 4.5),
    "gemma-4-31b": ("gemini", "gemma-4-31b-it", 4.5),
    "qwen3.8-27b@groq": ("groq", "qwen/qwen3.8-27b", 2.0),
    "qwen3.8-27b@cerebras": ("cerebras", "qwen-3.8-27b", 2.0),
    "gemini-robotics-er-2 (SOTA ref)": ("gemini", "gemini-robotics-er-2-preview", 6.0),
}
SUFFIX = "\nThink briefly, then give the final answer on the last line as 'Answer: <letter>'."


def b64(img, max_side=640):
    im = img.copy()
    im.thumbnail((max_side, max_side))
    buf = io.BytesIO()
    im.save(buf, "JPEG", quality=85)
    return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()


def to_openai(content):
    out = []
    for c in content:
        out.append({"type": "text", "text": c["text"]} if c["type"] == "text"
                   else {"type": "image_url", "image_url": {"url": b64(c["image"])}})
    return out


def extract(text, opts):
    text = re.sub(r"<think>.*?</think>", "", text or "", flags=re.S)
    m = re.findall(r"Answer\s*[::]\s*\(?([A-H])\b", text)
    if m and m[-1] in opts:
        return m[-1]
    m = re.findall(r"\b([A-H])\b", text[-80:])
    for x in reversed(m):
        if x in opts:
            return x
    return None


def run_agent(name, items, outdir):
    prov, model, pace = AGENTS[name]
    path = Path(outdir) / (re.sub(r"[^A-Za-z0-9.@-]+", "_", name) + ".jsonl")
    done = set()
    if path.exists():
        done = {json.loads(line)["id"] for line in open(path) if json.loads(line)["pred"] is not None}
    for it in items:
        if it["id"] in done:
            continue
        msgs = [{"role": "user", "content": to_openai(erqa.interleave(it, SUFFIX))}]
        t = time.perf_counter()
        try:
            text, _ = chat(msgs, providers=[prov], model=model, max_tokens=8192, retries_per_provider=6,
                           backoff=8.0, timeout=180)
        except LLMError as e:
            text = f"ERROR {str(e)[:150]}"
        pred = extract(text, it["options"])
        with path.open("a") as f:
            f.write(json.dumps({"id": it["id"], "type": it["type"], "answer": it["answer"], "options": it["options"],
                                "pred": pred, "agent": name, "latency_s": round(time.perf_counter() - t, 2),
                                "raw": text[-600:]}) + "\n")
        time.sleep(pace)
    print("done", name, flush=True)


def main():
    names = sys.argv[1:] or [n for n in AGENTS if "SOTA" not in n]   # SOTA ref: free daily quota exhausted
    items = erqa.load()
    import random
    random.Random(0).shuffle(items)   # representative coverage at any point (file order clusters by type)
    Path("results/erqa").mkdir(parents=True, exist_ok=True)
    ths = [threading.Thread(target=run_agent, args=(n, items, "results/erqa")) for n in names]
    for t in ths:
        t.start()
    for t in ths:
        t.join()


if __name__ == "__main__":
    main()