RefinedNeuro commited on
Commit
c1280af
·
verified ·
1 Parent(s): 3daf0b1

AgentDeliveryBench: tasks+harness+README

Browse files
Files changed (1) hide show
  1. agent_eval.py +152 -0
agent_eval.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AgentEval — the unit test BFCL/AIME missed.
2
+
3
+ The 2026-06-29 reality check showed our models pass BFCL multi_turn (backend-state correct) while
4
+ FAILING as real agents: they make tool calls but never state the answer and loop. BFCL scores
5
+ state; users need a delivered answer. This harness scores what matters end-to-end:
6
+
7
+ - did the agent state the CORRECT final answer? (regex/value on the final natural-language msg)
8
+ - did it TERMINATE cleanly within a turn budget (no looping)?
9
+ - (optional) did it leave the correct artifact?
10
+
11
+ A faithful-but-light agent loop over the Ollama OpenAI-compatible endpoint with a real sandboxed
12
+ toolset (write_file/read_file/run_python). Model-agnostic: works for our Hermes models AND Qwen
13
+ (ollama parses both into OpenAI tool_calls; we also fall back to parsing raw <tool_call>).
14
+
15
+ task success = answer_correct AND terminated. The aggregate success rate is the new gate canary.
16
+
17
+ Usage: python agent_eval.py <ollama_model> [--tasks agent_tasks.json] [--max-turns 8] [--out x.json]
18
+ """
19
+ import sys, os, json, re, argparse, tempfile, subprocess, shutil, requests
20
+
21
+ OLLAMA = os.environ.get("AGENTEVAL_URL", "http://127.0.0.1:11434/v1/chat/completions")
22
+
23
+ TOOLS = [
24
+ {"type": "function", "function": {"name": "write_file", "description": "Write text to a file (creates parent dirs).",
25
+ "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}}, "required": ["path", "content"]}}},
26
+ {"type": "function", "function": {"name": "read_file", "description": "Read a file's contents.",
27
+ "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}},
28
+ {"type": "function", "function": {"name": "run_python", "description": "Run a Python3 script string; returns stdout+stderr.",
29
+ "parameters": {"type": "object", "properties": {"code": {"type": "string"}}, "required": ["code"]}}},
30
+ ]
31
+ SYS = ("You are a helpful agent with tools (write_file, read_file, run_python). Use them to complete "
32
+ "the user's task, then give a FINAL natural-language answer that explicitly states the result. "
33
+ "Do not repeat tool calls once you have what you need — stop and answer.")
34
+
35
+
36
+ def exec_tool(name, args, sandbox):
37
+ try:
38
+ if name == "write_file":
39
+ p = os.path.join(sandbox, args["path"].lstrip("/"))
40
+ os.makedirs(os.path.dirname(p) or sandbox, exist_ok=True)
41
+ open(p, "w").write(args.get("content", ""))
42
+ return f"wrote {len(args.get('content',''))} bytes to {args['path']}"
43
+ if name == "read_file":
44
+ p = os.path.join(sandbox, args["path"].lstrip("/"))
45
+ return open(p).read()
46
+ if name == "run_python":
47
+ r = subprocess.run([sys.executable, "-c", args["code"]], cwd=sandbox,
48
+ capture_output=True, text=True, timeout=20)
49
+ return (r.stdout + r.stderr)[:2000] or "(no output)"
50
+ except Exception as e:
51
+ return f"ERROR: {e}"
52
+ return "ERROR: unknown tool"
53
+
54
+
55
+ def parse_raw_toolcalls(content):
56
+ """Fallback: parse Hermes <tool_call>{...}</tool_call> if model didn't use native tool_calls."""
57
+ out = []
58
+ for m in re.finditer(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", content or "", re.S):
59
+ try:
60
+ o = json.loads(m.group(1))
61
+ out.append((o["name"], o.get("arguments", {}) or {}))
62
+ except Exception:
63
+ pass
64
+ return out
65
+
66
+
67
+ def run_task(model, task, max_turns, temp=0.3):
68
+ sandbox = tempfile.mkdtemp(prefix="ageval_")
69
+ msgs = [{"role": "system", "content": SYS}, {"role": "user", "content": task["prompt"]}]
70
+ seen_calls, looped, final = set(), False, ""
71
+ try:
72
+ for turn in range(max_turns):
73
+ r = requests.post(OLLAMA, json={"model": model, "messages": msgs, "tools": TOOLS,
74
+ "temperature": temp, "stream": False}, timeout=180).json()
75
+ m = r["choices"][0]["message"]
76
+ calls = []
77
+ for tc in (m.get("tool_calls") or []):
78
+ fn = tc["function"]; a = fn["arguments"]
79
+ a = json.loads(a) if isinstance(a, str) else a
80
+ calls.append((fn["name"], a))
81
+ if not calls:
82
+ calls_raw = parse_raw_toolcalls(m.get("content"))
83
+ calls = calls_raw
84
+ if not calls:
85
+ final = m.get("content") or ""
86
+ break # agent terminated with a final answer
87
+ # loop detection: identical (name,args) seen before
88
+ msgs.append({"role": "assistant", "content": m.get("content") or "", "tool_calls": m.get("tool_calls")})
89
+ for name, a in calls:
90
+ sig = name + json.dumps(a, sort_keys=True)[:200]
91
+ if sig in seen_calls:
92
+ looped = True
93
+ seen_calls.add(sig)
94
+ res = exec_tool(name, a, sandbox)
95
+ msgs.append({"role": "tool", "content": str(res)[:2000]})
96
+ else:
97
+ looped = True # hit max_turns without a final answer
98
+ # score
99
+ want = task["answer"]
100
+ ans_ok = bool(re.search(rf"(?<![\w]){re.escape(str(want))}(?![\w])", final.replace(",", ""), re.I)) if final else False
101
+ # avoid trivially-correct from echoing the task: require it's in the FINAL msg only (already)
102
+ artifact_ok = True
103
+ if "artifact" in task:
104
+ ap = os.path.join(sandbox, task["artifact"]["path"].lstrip("/"))
105
+ artifact_ok = os.path.exists(ap) and (task["artifact"].get("contains", "") in (open(ap).read() if os.path.exists(ap) else ""))
106
+ success = ans_ok and not looped
107
+ return dict(id=task["id"], difficulty=task.get("difficulty", "?"), answer_ok=ans_ok,
108
+ terminated=not looped, artifact_ok=artifact_ok,
109
+ success=success, turns=turn + 1, final=final[:200])
110
+ except Exception as e: # a bad task must never kill the whole suite
111
+ return dict(id=task["id"], difficulty=task.get("difficulty", "?"), answer_ok=False,
112
+ terminated=False, artifact_ok=False, success=False, turns=-1,
113
+ final=f"HARNESS_ERROR: {str(e)[:150]}")
114
+ finally:
115
+ shutil.rmtree(sandbox, ignore_errors=True)
116
+
117
+
118
+ def main():
119
+ ap = argparse.ArgumentParser()
120
+ ap.add_argument("model")
121
+ ap.add_argument("--tasks", default="agent_tasks.json")
122
+ ap.add_argument("--max-turns", type=int, default=8)
123
+ ap.add_argument("--out", default=None)
124
+ a = ap.parse_args()
125
+ tasks = json.load(open(a.tasks))
126
+ rows = [run_task(a.model, t, a.max_turns) for t in tasks]
127
+ n = len(rows)
128
+ succ = sum(r["success"] for r in rows)
129
+ ans = sum(r["answer_ok"] for r in rows)
130
+ term = sum(r["terminated"] for r in rows)
131
+ print(f"=== AgentEval — {a.model} ({n} tasks) ===")
132
+ order = {"easy": 0, "medium": 1, "hard": 2, "really_hard": 3, "expert": 4}
133
+ for r in sorted(rows, key=lambda r: order.get(r["difficulty"], 9)):
134
+ flag = "PASS" if r["success"] else "FAIL"
135
+ print(f" [{flag}] {r['difficulty']:11s} {r['id']:14s} ans={int(r['answer_ok'])} "
136
+ f"term={int(r['terminated'])} turns={r['turns']} | {r['final'][:55].replace(chr(10),' ')}")
137
+ # per-difficulty breakdown
138
+ print(" --- by difficulty (success rate) ---")
139
+ by = {}
140
+ for r in rows:
141
+ by.setdefault(r["difficulty"], []).append(r["success"])
142
+ for d in ["easy", "medium", "hard", "really_hard", "expert"]:
143
+ if d in by:
144
+ v = by[d]; print(f" {d:11s}: {sum(v)}/{len(v)} = {sum(v)/len(v):.2f}")
145
+ print(f"SUCCESS {succ}/{n}={succ/n:.3f} | answer_ok {ans}/{n} | terminated {term}/{n}")
146
+ if a.out:
147
+ json.dump(dict(model=a.model, success=succ / n, rows=rows), open(a.out, "w"))
148
+ return succ / n
149
+
150
+
151
+ if __name__ == "__main__":
152
+ main()