"""Track P — PlanBench Blocksworld / Mystery Blocksworld (Valmeekam et al., 2023). Protocol: the official PlanBench one-shot natural-language prompt (`query`) is sent unchanged (zero-shot attempt = attempt 0). LLM-Modulo (Kambhampati et al., 2024): if the exact STRIPS validator rejects the plan, its critique is back-prompted, up to K repairs. Swarm systems combine the 4 agents: plurality vote over plans (no verifier) vs verifier-selected (any agent's validated plan) — a sound verifier makes voting obsolete. """ from __future__ import annotations import json import threading import time from collections import Counter from pathlib import Path import numpy as np import pandas as pd from robotics.llm.providers import LLMError, chat from robotics.planbench.blocksworld import parse_plan, validate AGENTS = [("groq", "openai/gpt-oss-120b"), ("groq", "qwen/qwen3.8-27b"), ("cerebras", "qwen-3.8-27b"), ("gemini", "gemini-3.1-flash-lite")] DOMAINS = ("blocksworld", "mystery_blocksworld") REPAIR = ("The plan you gave is not correct. {fb} Please give a corrected, complete plan that starts " "from the initial conditions, in the same format as the example, one action per line, " "ending with [PLAN END].") def instances(path="data/raw/planbench/task1.parquet", n_per_domain=50, seed=0): d = pd.read_parquet(path) out = [] for dom in DOMAINS: s = d[d.domain == dom].sample(n=n_per_domain, random_state=seed) out += [{"domain": dom, "id": int(r.instance_id), "query": r.query, "gt_len": len(parse_plan(r.ground_truth_plan))} for _, r in s.iterrows()] return out def solve(agent, inst, K=3): msgs = [{"role": "user", "content": inst["query"]}] attempts = [] for k in range(K + 1): text, _ = chat(msgs, providers=[agent[0]], model=agent[1], max_tokens=6000, retries_per_provider=6, backoff=8.0, timeout=180) plan = parse_plan(text) ok, fb = validate(inst["query"], inst["domain"], plan) attempts.append({"valid": ok, "feedback": fb, "n_actions": len(plan), "plan": "\n".join(" ".join(a) for a in plan), "raw": text[-3000:]}) if ok: break msgs += [{"role": "assistant", "content": text}, {"role": "user", "content": REPAIR.format(fb=fb)}] return attempts def collect(out="results/planbench/attempts.jsonl", n_per_domain=50, K=3, pace=1.0, agents=AGENTS): out = Path(out) out.parent.mkdir(parents=True, exist_ok=True) done = set() if out.exists(): for line in out.read_text().splitlines(): r = json.loads(line) if not r.get("error"): done.add((r["agent"], r["domain"], r["id"])) insts = instances(n_per_domain=n_per_domain) lock = threading.Lock() def worker(agent): name = f"{agent[0]}:{agent[1]}" for inst in insts: if (name, inst["domain"], inst["id"]) in done: continue t = time.perf_counter() try: att, err = solve(agent, inst, K), None except LLMError as e: att, err = [], str(e)[:200] rec = {"agent": name, "domain": inst["domain"], "id": inst["id"], "gt_len": inst["gt_len"], "attempts": att, "error": err, "seconds": round(time.perf_counter() - t, 1)} with lock, out.open("a") as f: f.write(json.dumps(rec) + "\n") time.sleep(pace) print("done", name, flush=True) ths = [threading.Thread(target=worker, args=(a,)) for a in agents] [t.start() for t in ths] [t.join() for t in ths] # ------------------------------------------------------------------ evaluation def load(path="results/planbench/attempts.jsonl"): recs = {} for line in open(path): r = json.loads(line) if not r.get("error") and r["attempts"]: recs[(r["agent"], r["domain"], r["id"])] = r return recs def evaluate(path="results/planbench/attempts.jsonl", K=3): from robotics.eval.stats import wilson recs = load(path) agents = [f"{a}:{m}" for a, m in AGENTS if any(k[0] == f"{a}:{m}" for k in recs)] rows = [] for dom in DOMAINS: ids = sorted({k[2] for k in recs if k[1] == dom and all((a, dom, k[2]) in recs for a in agents)}) if not ids: continue sysok = {} for a in agents: R = [recs[(a, dom, i)] for i in ids] sysok[f"{a} · zero-shot"] = ([int(r["attempts"][0]["valid"]) for r in R], 1.0) for k in range(1, K + 1): sysok[f"{a} · LLM-Modulo (≤{k} repair{'s' if k > 1 else ''})"] = ( [int(any(x["valid"] for x in r["attempts"][:k + 1])) for r in R], float(np.mean([min(len(r["attempts"]), k + 1) for r in R]))) # swarms zs = [[recs[(a, dom, i)]["attempts"][0] for a in agents] for i in ids] vote = [] for atts in zs: c = Counter(x["plan"] for x in atts if x["plan"]) top = c.most_common(1)[0][0] if c else "" vote.append(int(any(x["valid"] for x in atts if x["plan"] == top)) if top else 0) sysok["swarm · plurality vote, zero-shot (no verifier)"] = (vote, float(len(agents))) sysok["swarm · verifier-selected, zero-shot"] = ([int(any(x["valid"] for x in a)) for a in zs], float(len(agents))) sysok["swarm · verifier-selected, LLM-Modulo"] = ( [int(any(any(x["valid"] for x in recs[(a, dom, i)]["attempts"]) for a in agents)) for i in ids], float(np.mean([sum(len(recs[(a, dom, i)]["attempts"]) for a in agents) for i in ids]))) for name, (ok, calls) in sysok.items(): k = sum(ok) lo, hi = wilson(k, len(ok)) rows.append({"domain": dom, "system": name, "acc": k / len(ok), "lo": lo, "hi": hi, "n": len(ok), "llm_calls": calls, "per_instance": ok}) return rows