#!/usr/bin/env python3 """Runs eval_set.tsv through the Needle CLI with the app's tool catalog and reports routing accuracy. Usage: run_eval.py [threshold] tools.json is written by the unit test ProviderFormatTest.exportToolCatalog (app/build/needle-tools.json). Expected tool "-" means no on-device tool should be used (the request should go to the AI). """ import json, subprocess, sys, tempfile, os, re needle, tools = sys.argv[1], sys.argv[2] thr = float(sys.argv[3]) if len(sys.argv) > 3 else 0.6 here = os.path.dirname(os.path.abspath(__file__)) sysf = tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) sysf.write("date: 2026-09-19 Sat 14:30; locale: en-US; device: phone; battery: 62%; assistant: Stitch") sysf.close() idx = os.path.join(tempfile.gettempdir(), "needle-eval.idx") required = {t["name"]: set(t["parameters"].get("required", [])) for t in json.load(open(tools))} # The app's own safety checks (written by the unit tests): Needle's pick only runs if they pass. rules_path = os.path.join(os.path.dirname(tools), "needle-safety.json") rules = json.load(open(rules_path)) if os.path.exists(rules_path) else None def app_blocks(prompt, name): if not rules: return None p = prompt.strip().lower() if re.fullmatch(rules["small_talk"], p): return "small talk" if re.search(rules["negation"], prompt, re.I): return "negated" ev = rules["evidence"].get(name) if name != "-" and (ev is None or not re.search(ev, prompt, re.I)): return "no evidence" return None def matches(args, expect): for kv in filter(None, expect.split(",")): k, v = kv.split("=", 1) got = str(args.get(k, "")).lower() if got != v.lower() and v.lower() not in got: return False return True right_tool = right_args = acted = acted_wrong = 0 rows = [l.rstrip("\n").split("\t") for l in open(os.path.join(here, "eval_set.tsv")) if l.strip()] for prompt, want, *rest in rows: expect = rest[0] if rest else "" out = subprocess.run([needle, "--tools", tools, "--tool-index", idx, "--system", sysf.name, "--prompt", prompt], capture_output=True, text=True).stdout j = json.loads(out) calls = j.get("function_calls") or [] conf = j.get("confidence") or 0 ung = (j.get("validation") or {}).get("ungrounded") or [] name = calls[0]["name"] if calls else "-" args = dict(calls[0]["arguments"]) if calls else {} # Same rule as Agent.decide(): drop made-up optional args, reject made-up required ones. bad = [] for path in ung: fn, _, arg = path.partition(".") if fn != name: continue if arg in required.get(name, ()): bad.append(arg) else: args.pop(arg, None) args = {k: v for k, v in args.items() if v != "" or k in required.get(name, ())} missing = [k for k in required.get(name, ()) if str(args.get(k, "")).strip() == ""] tool_ok = name == want args_ok = tool_ok and matches(args, expect) blocked = app_blocks(prompt, name) if calls else None would_act = bool(calls) and conf >= thr and not bad and not missing and not blocked right_tool += tool_ok right_args += args_ok acted += would_act acted_wrong += would_act and not args_ok mark = "✓" if args_ok else ("~" if tool_ok else "✗") act = "ACT " if would_act else ("blk " if blocked else "ai ") print(f"{mark} {act}{conf:4.2f} {prompt[:40]:40} → {name} {json.dumps(args)[:70]}{' GUESSED' + str(bad) if bad else ''}") n = len(rows) print(f"\ntool {right_tool}/{n} · tool+args {right_args}/{n} · acts on-device {acted}/{n} (wrong: {acted_wrong}) at threshold {thr}")