AgentDeliveryBench / agent_eval.py
RefinedNeuro's picture
AgentDeliveryBench: tasks+harness+README
c1280af verified
Raw
History Blame Contribute Delete
7.82 kB
"""AgentEval — the unit test BFCL/AIME missed.
The 2026-06-29 reality check showed our models pass BFCL multi_turn (backend-state correct) while
FAILING as real agents: they make tool calls but never state the answer and loop. BFCL scores
state; users need a delivered answer. This harness scores what matters end-to-end:
- did the agent state the CORRECT final answer? (regex/value on the final natural-language msg)
- did it TERMINATE cleanly within a turn budget (no looping)?
- (optional) did it leave the correct artifact?
A faithful-but-light agent loop over the Ollama OpenAI-compatible endpoint with a real sandboxed
toolset (write_file/read_file/run_python). Model-agnostic: works for our Hermes models AND Qwen
(ollama parses both into OpenAI tool_calls; we also fall back to parsing raw <tool_call>).
task success = answer_correct AND terminated. The aggregate success rate is the new gate canary.
Usage: python agent_eval.py <ollama_model> [--tasks agent_tasks.json] [--max-turns 8] [--out x.json]
"""
import sys, os, json, re, argparse, tempfile, subprocess, shutil, requests
OLLAMA = os.environ.get("AGENTEVAL_URL", "http://127.0.0.1:11434/v1/chat/completions")
TOOLS = [
{"type": "function", "function": {"name": "write_file", "description": "Write text to a file (creates parent dirs).",
"parameters": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}}},
{"type": "function", "function": {"name": "read_file", "description": "Read a file's contents.",
"parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}},
{"type": "function", "function": {"name": "run_python", "description": "Run a Python3 script string; returns stdout+stderr.",
"parameters": {"type": "object", "properties": {"code": {"type": "string"}}, "required": ["code"]}}},
]
SYS = ("You are a helpful agent with tools (write_file, read_file, run_python). Use them to complete "
"the user's task, then give a FINAL natural-language answer that explicitly states the result. "
"Do not repeat tool calls once you have what you need — stop and answer.")
def exec_tool(name, args, sandbox):
try:
if name == "write_file":
p = os.path.join(sandbox, args["path"].lstrip("/"))
os.makedirs(os.path.dirname(p) or sandbox, exist_ok=True)
open(p, "w").write(args.get("content", ""))
return f"wrote {len(args.get('content',''))} bytes to {args['path']}"
if name == "read_file":
p = os.path.join(sandbox, args["path"].lstrip("/"))
return open(p).read()
if name == "run_python":
r = subprocess.run([sys.executable, "-c", args["code"]], cwd=sandbox,
capture_output=True, text=True, timeout=20)
return (r.stdout + r.stderr)[:2000] or "(no output)"
except Exception as e:
return f"ERROR: {e}"
return "ERROR: unknown tool"
def parse_raw_toolcalls(content):
"""Fallback: parse Hermes <tool_call>{...}</tool_call> if model didn't use native tool_calls."""
out = []
for m in re.finditer(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", content or "", re.S):
try:
o = json.loads(m.group(1))
out.append((o["name"], o.get("arguments", {}) or {}))
except Exception:
pass
return out
def run_task(model, task, max_turns, temp=0.3):
sandbox = tempfile.mkdtemp(prefix="ageval_")
msgs = [{"role": "system", "content": SYS}, {"role": "user", "content": task["prompt"]}]
seen_calls, looped, final = set(), False, ""
try:
for turn in range(max_turns):
r = requests.post(OLLAMA, json={"model": model, "messages": msgs, "tools": TOOLS,
"temperature": temp, "stream": False}, timeout=180).json()
m = r["choices"][0]["message"]
calls = []
for tc in (m.get("tool_calls") or []):
fn = tc["function"]; a = fn["arguments"]
a = json.loads(a) if isinstance(a, str) else a
calls.append((fn["name"], a))
if not calls:
calls_raw = parse_raw_toolcalls(m.get("content"))
calls = calls_raw
if not calls:
final = m.get("content") or ""
break # agent terminated with a final answer
# loop detection: identical (name,args) seen before
msgs.append({"role": "assistant", "content": m.get("content") or "", "tool_calls": m.get("tool_calls")})
for name, a in calls:
sig = name + json.dumps(a, sort_keys=True)[:200]
if sig in seen_calls:
looped = True
seen_calls.add(sig)
res = exec_tool(name, a, sandbox)
msgs.append({"role": "tool", "content": str(res)[:2000]})
else:
looped = True # hit max_turns without a final answer
# score
want = task["answer"]
ans_ok = bool(re.search(rf"(?<![\w]){re.escape(str(want))}(?![\w])", final.replace(",", ""), re.I)) if final else False
# avoid trivially-correct from echoing the task: require it's in the FINAL msg only (already)
artifact_ok = True
if "artifact" in task:
ap = os.path.join(sandbox, task["artifact"]["path"].lstrip("/"))
artifact_ok = os.path.exists(ap) and (task["artifact"].get("contains", "") in (open(ap).read() if os.path.exists(ap) else ""))
success = ans_ok and not looped
return dict(id=task["id"], difficulty=task.get("difficulty", "?"), answer_ok=ans_ok,
terminated=not looped, artifact_ok=artifact_ok,
success=success, turns=turn + 1, final=final[:200])
except Exception as e: # a bad task must never kill the whole suite
return dict(id=task["id"], difficulty=task.get("difficulty", "?"), answer_ok=False,
terminated=False, artifact_ok=False, success=False, turns=-1,
final=f"HARNESS_ERROR: {str(e)[:150]}")
finally:
shutil.rmtree(sandbox, ignore_errors=True)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("model")
ap.add_argument("--tasks", default="agent_tasks.json")
ap.add_argument("--max-turns", type=int, default=8)
ap.add_argument("--out", default=None)
a = ap.parse_args()
tasks = json.load(open(a.tasks))
rows = [run_task(a.model, t, a.max_turns) for t in tasks]
n = len(rows)
succ = sum(r["success"] for r in rows)
ans = sum(r["answer_ok"] for r in rows)
term = sum(r["terminated"] for r in rows)
print(f"=== AgentEval — {a.model} ({n} tasks) ===")
order = {"easy": 0, "medium": 1, "hard": 2, "really_hard": 3, "expert": 4}
for r in sorted(rows, key=lambda r: order.get(r["difficulty"], 9)):
flag = "PASS" if r["success"] else "FAIL"
print(f" [{flag}] {r['difficulty']:11s} {r['id']:14s} ans={int(r['answer_ok'])} "
f"term={int(r['terminated'])} turns={r['turns']} | {r['final'][:55].replace(chr(10),' ')}")
# per-difficulty breakdown
print(" --- by difficulty (success rate) ---")
by = {}
for r in rows:
by.setdefault(r["difficulty"], []).append(r["success"])
for d in ["easy", "medium", "hard", "really_hard", "expert"]:
if d in by:
v = by[d]; print(f" {d:11s}: {sum(v)}/{len(v)} = {sum(v)/len(v):.2f}")
print(f"SUCCESS {succ}/{n}={succ/n:.3f} | answer_ok {ans}/{n} | terminated {term}/{n}")
if a.out:
json.dump(dict(model=a.model, success=succ / n, rows=rows), open(a.out, "w"))
return succ / n
if __name__ == "__main__":
main()