Files
stitch/tools-dev/needle/run_eval.py
T
thekhalidsha 61409cb444 Initial import: Stitch 0.4.3 (versionCode 16)
The project's first commit, six days and 16 releases after it started. Everything
up to this point existed only as files on one machine, with no history and no undo.

Contents: single Gradle module, 62 Kotlin files (11,244 lines) and the Needle 2 JNI
bridge, 70 tools, 87 passing unit tests, and the five documents in docs/ plus
DEVELOPMENT_HISTORY.md and README.md.

Not tracked: build outputs (build/, .cxx/, .gradle/), the release APKs in dist/
(~800 MB, rebuildable), local.properties, and .claude/settings.local.json — all
machine-specific. The prebuilt libneedle.a files (38 MB) *are* tracked on purpose,
so a checkout builds without depending on Hugging Face still serving them.
2026-09-25 14:23:14 +05:30

72 lines
3.6 KiB
Python
Executable File

#!/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 <needle-binary> <tools.json> [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}")