Datasets:
File size: 5,828 Bytes
1a7314a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | """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()
|