"""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 ). task success = answer_correct AND terminated. The aggregate success rate is the new gate canary. Usage: python agent_eval.py [--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 {...} if model didn't use native tool_calls.""" out = [] for m in re.finditer(r"\s*(\{.*?\})\s*", 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"(?