"""Evaluation harness: Baseline vs Learned (AgentTune-distilled) policy. Both policies are scored on the HELD-OUT test split only (entity/value-disjoint from the training trajectories). Scoring is done two ways and both are reported: 1. plain deterministic metrics computed here; 2. AuditKIT (auditkit==1.1.11, Lexsi Labs) agent metrics -- ToolCallF1 (exact-args and name-only), ToolCallValidity, RedundantToolCalls and TrajectoryMatch -- called through their real public API (auditkit.Sample + metric.score(sample, output, {"trace": ...})). It also verifies the AgentTune handoff: auditkit.load_agenttune() and auditkit.episodes_from_agenttune() must parse data/trajectories.jsonl. Writes results/metrics.json and prints a full report to stdout. """ from __future__ import annotations import json import os import sys from collections import defaultdict sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import auditkit # noqa: E402 from auditkit import Sample # noqa: E402 from auditkit.metrics.agent import ( # noqa: E402 RedundantToolCalls, ToolCallF1, ToolCallValidity, TrajectoryMatch, ) from policies import BaselinePolicy, LearnedPolicy # noqa: E402 from tasks import REQUIRED_ARGS, TOOL_SCHEMAS # noqa: E402 HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.join(HERE, "..") def own_metrics(tasks, predict) -> dict: n = len(tasks) tool_ok = arg_exact = success = 0 total_calls = 0 per_tool = defaultdict(lambda: [0, 0]) for t in tasks: calls = predict(t["prompt"]) total_calls += len(calls) first = calls[0] if calls else {"name": None, "arguments": {}} is_tool = first["name"] == t["tool"] is_args = is_tool and first["arguments"] == t["arguments"] tool_ok += is_tool arg_exact += is_args success += bool(is_args and len(calls) == 1) per_tool[t["tool"]][0] += is_args per_tool[t["tool"]][1] += 1 return { "tool_selection_accuracy": round(tool_ok / n, 4), "argument_exact_match": round(arg_exact / n, 4), "task_success_rate": round(success / n, 4), "avg_calls_per_task": round(total_calls / n, 4), "per_tool_success": { k: round(v[0] / v[1], 4) for k, v in sorted(per_tool.items()) }, } def auditkit_metrics(tasks, predict) -> dict: f1_exact = ToolCallF1(arg_mode="exact") f1_name = ToolCallF1(arg_mode="name") validity = ToolCallValidity() redundant = RedundantToolCalls() traj = TrajectoryMatch(arg_mode="exact") sums: dict[str, list[float]] = defaultdict(list) for t in tasks: calls = predict(t["prompt"]) turns = [[c] for c in calls] # each call its own turn sample = Sample( input=t["prompt"], id=t["id"], tools=TOOL_SCHEMAS, expected_tool_calls=[[{"name": t["tool"], "arguments": t["arguments"]}]], actual_trace={"tool_calls": turns}, ) ctx = {"trace": {"tool_calls": turns}} out = json.dumps(calls) for metric in (f1_exact, f1_name, validity, redundant, traj): for s in metric.score(sample, out, ctx): sums[s.name].append(s.value) return {k: round(sum(v) / len(v), 4) for k, v in sorted(sums.items()) if v} def main(): with open(os.path.join(ROOT, "data", "tasks.json")) as f: bundle = json.load(f) test = bundle["test"] sft_path = os.path.join(ROOT, "data", "sft_agenttune.jsonl") learned = LearnedPolicy().fit(sft_path) baseline = BaselinePolicy() print("=" * 72) print("Lexsi Labs Track 3 -- AgentTune + AuditKIT tool-calling evaluation") print(f"auditkit version: {auditkit.__version__}") print(f"held-out test tasks: {len(test)} (entity/value-disjoint from train)") print(f"learned policy fitted on {learned.n_train} SFT trajectories") print("=" * 72) results = {"auditkit_version": auditkit.__version__, "n_test_tasks": len(test), "n_train_trajectories": learned.n_train, "split": "train/test prompts fully disjoint; entities and values " "(topics, expressions, people, symbols, cities, dates) " "disjoint across splits; template wording families shared"} for label, policy in [("baseline", baseline), ("improved", learned)]: own = own_metrics(test, policy.predict) ak = auditkit_metrics(test, policy.predict) results[label] = {"policy_metrics": own, "auditkit_metrics": ak} print(f"\n--- {label.upper()} ---") for k, v in own.items(): print(f" {k}: {v}") print(" auditkit:") for k, v in ak.items(): print(f" {k}: {v}") # ---- AgentTune -> AuditKIT handoff verification ----------------------- traj_path = os.path.join(ROOT, "data", "trajectories.jsonl") samples = auditkit.load_agenttune(traj_path) episodes = auditkit.episodes_from_agenttune(traj_path) results["auditkit_load_check"] = { "load_agenttune_samples": len(samples), "episodes_from_agenttune": len(episodes), } print("\n--- AgentTune -> AuditKIT handoff ---") print(f" load_agenttune(trajectories.jsonl) -> {len(samples)} samples") print(f" episodes_from_agenttune(...) -> {len(episodes)} episodes") os.makedirs(os.path.join(ROOT, "results"), exist_ok=True) with open(os.path.join(ROOT, "results", "metrics.json"), "w") as f: json.dump(results, f, indent=2) print("\nwrote results/metrics.json") # sanity: learned router must know every required-arg slot it predicts assert all(t in REQUIRED_ARGS for t in learned.tool_counts) return results if __name__ == "__main__": main()