File size: 3,978 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
#!/usr/bin/env python3
"""PlanBench Blocksworld (task 1) with LLM agents: official one-shot prompt, then LLM-Modulo repair.

For each agent and instance: call 1 = official PlanBench one-shot query (comparable to published
numbers). If the validator rejects the plan, its exact error is fed back (up to `--repairs` more
calls). Resumable: results/planbench/<agent>.jsonl
"""
import argparse
import json
import random
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 blocksworld as bw  # noqa: E402
from robotics.llm.providers import LLMError, chat  # noqa: E402

AGENTS = {
    "gpt-oss-120b@groq": ("groq", "openai/gpt-oss-120b", 3.0),
    "qwen3.8-27b@groq": ("groq", "qwen/qwen3.8-27b", 2.0),
    "qwen3.8-27b@cerebras": ("cerebras", "qwen-3.8-27b", 2.0),
    "gemini-3.1-flash-lite": ("gemini", "gemini-3.1-flash-lite", 4.5),
    "gemma-4-31b": ("gemini", "gemma-4-31b-it", 4.5),
}
SYSTEM = ("You solve blocksworld planning problems. Reply with the plan only, one action per line, in exactly "
          "the same format as the example plan, and finish with [PLAN END].")


def subset(n, seed=0):
    ins = bw.load()
    random.Random(seed).shuffle(ins)
    return sorted(ins[:n], key=lambda i: int(i["instance_id"]))


def run_agent(name, instances, repairs, 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)["instance_id"] for line in open(path) if not json.loads(line).get("error_api")}
    for ins in instances:
        if ins["instance_id"] in done:
            continue
        msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": ins["query"]}]
        attempts, err_api = [], None
        t = time.perf_counter()
        for k in range(repairs + 1):
            try:
                text, _ = chat(msgs, providers=[prov], model=model, max_tokens=6000, retries_per_provider=6,
                               backoff=8.0, timeout=240)
            except LLMError as e:
                err_api = str(e)[:150]
                break
            v = bw.validate(ins["query"], text)
            attempts.append({"plan": [f"{a} {' '.join(x)}" for a, x in bw.parse_plan(text)], "reached": v["reached"],
                             "error": v["error"], "n_unmet": len(v["unmet"])})
            if v["reached"]:
                break
            msgs += [{"role": "assistant", "content": text},
                     {"role": "user", "content": bw.feedback(v) + " Write a corrected complete plan in the same "
                                                                  "format, ending with [PLAN END]."}]
            time.sleep(pace)
        gt_len = len([x for x in ins["ground_truth_plan"].splitlines() if x.strip()])
        rec = {"instance_id": ins["instance_id"], "agent": name, "attempts": attempts, "gt_len": gt_len,
               "oneshot": bool(attempts and attempts[0]["reached"]),
               "modulo": bool(attempts and attempts[-1]["reached"]), "calls": len(attempts),
               "latency_s": round(time.perf_counter() - t, 1), "error_api": err_api}
        with path.open("a") as f:
            f.write(json.dumps(rec) + "\n")
        time.sleep(pace)
    print("done", name, flush=True)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("agents", nargs="*")
    ap.add_argument("--n", type=int, default=100)
    ap.add_argument("--repairs", type=int, default=3)
    a = ap.parse_args()
    inst = subset(a.n)
    Path("results/planbench").mkdir(parents=True, exist_ok=True)
    names = a.agents or list(AGENTS)
    ths = [threading.Thread(target=run_agent, args=(n, inst, a.repairs, "results/planbench")) for n in names]
    for t in ths:
        t.start()
    for t in ths:
        t.join()


if __name__ == "__main__":
    main()