shantomathew's picture
ToolTune code, article and training notebook (Lexsi Track 3)
1a7314a verified
|
Raw History Blame Contribute Delete
8.51 kB
# Reliable Tool Calling from a Small Open Model: AgentTune Trajectories + AuditKIT Scoring
**Lexsi Labs AI Safety & Alignment Hackathon — Track 3: Agentic Fine-tuning**
Team lead: Shanto Mathew · Hugging Face: `shantomathew`
Toolkits chained: **AgentTune** (trajectory generation / post-training format) + **AuditKIT** 1.1.11 (evaluation) — both by Lexsi Labs.
Student model target (GPU step): Cohere Labs open weights — `CohereLabs/aya-expanse-8b`, with `CohereLabs/tiny-aya-global` as the AgentTune-native alternative.
> **Scope note — read first.** Two different things are measured/reported in this project, and they are not interchangeable:
> 1. **Measured locally (executed, real numbers below):** an *agent-policy* evaluation. A naive baseline policy and an improved policy — a router/extractor **distilled by code from the AgentTune SFT trajectories** (naive-Bayes tool router + learned cue/shape argument extractor, pure Python, no LLM) — are both scored on a held-out test split with AuditKIT's agent metrics.
> 2. **Not yet executed:** fine-tuning an actual Cohere Aya LLM on those trajectories. That is the GPU step in `train_aya_sft.ipynb` (TRL SFT / AgentTune distillation on Colab or HF Jobs). **No Cohere model has been fine-tuned in this submission so far**, and no metric below is an LLM metric.
---
## Problem
Small open models are cheap and private, but unreliable tool callers: they pick the wrong tool when a prompt contains a distractor verb ("Search the market data for the **price** of NVDA"), mangle arguments (lower-cased tickers, truncated dates, prose left inside arithmetic), and waste calls on redundant retries. For an agent platform such as AgentMart — where every action is a tool call against a marketplace API — those are exactly the failures that matter, and they are measurable.
## Approach
1. **Task suite (deterministic, verifiable).** 170 single-step tool-calling tasks over 5 tools — `search{query}`, `calculator{expression}`, `calendar_lookup{date, person}`, `price_lookup{symbol}`, `weather_lookup{city, date}` — each with exactly one gold call. Templates deliberately include distractor phrasing that hijacks naive keyword routers.
2. **Trajectories in AgentTune format.** The 130 training tasks become gold trajectories in two AgentTune-native artefacts (formats taken from the AgentTune repository, cloned at `AgentTune_ref/`):
- `data/sft_agenttune.jsonl` — SFT rows exactly as `EventLog.as_dataset_rows('sft')` emits them: `messages` + `segment_weights` + `loss_mask`, tool calls as `<tool_call>{...}</tool_call>` assistant messages with segment weight 2.0, observations masked.
- `data/trajectories.jsonl` — TrajectoryDataset records (`task`, `steps[].action.tool_calls`, `final_response`, `metadata.conversation`) — the format AgentTune's trainer writes and AuditKIT reads with **no conversion step**.
3. **Baseline policy.** Fixed-order keyword rules (first match wins, `search` cues first), sloppy extraction (whole prompt as the search query, `YYYY-MM` truncated dates, lower-cased symbols), plus a redundant duplicate call on ~25% of prompts — a plausible pre-fine-tuning agent.
4. **Improved policy (the distillation).** Fitted *by code* on the 130 SFT trajectories only: a multinomial naive-Bayes router over word unigrams+bigrams, and a per-argument extractor that learns cue tokens, stop tokens, and value shapes (date / arithmetic / upper-token / capitalised / free text) from the trajectories. Nothing about the test tasks is hand-coded.
5. **Scoring with AuditKIT.** Both policies are scored on the held-out split through AuditKIT's real API (`auditkit.Sample` + `ToolCallF1`, `ToolCallValidity`, `RedundantToolCalls`, `TrajectoryMatch`), alongside plain deterministic metrics. The AgentTune→AuditKIT handoff is verified in the same run: `auditkit.load_agenttune()` parses all 130 trajectory records and `episodes_from_agenttune()` returns 130 episodes.
**Split discipline.** Train (130) and test (40) prompts are fully disjoint, and so are the entities/values: topics, arithmetic expressions, people, ticker symbols, cities, and dates in the test split never appear in training. Template *wording families* are shared (same task distribution) — see Limitations.
## Results — real numbers from the executed run
Held-out test split, n = 40. Source: `results/metrics.json`, full console log in `RUN_OUTPUT.txt`.
| Metric | Baseline | Improved (distilled) |
|---|---|---|
| Tool-selection accuracy | 0.75 | **1.00** |
| Argument exact-match | 0.15 | **1.00** |
| Task success rate (right tool + exact args + exactly 1 call) | 0.15 | **1.00** |
| Avg calls per task (lower = leaner) | 1.275 | **1.00** |
| AuditKIT `tool_call_f1` (exact args) | 0.15 | **1.00** |
| AuditKIT `tool_call_f1` (tool name only) | 0.6833 | **1.00** |
| AuditKIT `tool_call_validity` | 1.00 | 1.00 |
| AuditKIT `redundant_tool_calls` (lower = better) | 0.1375 | **0.00** |
| AuditKIT `trajectory_strict` | 0.15 | **1.00** |
Per-tool task success (baseline → improved): search 0.00 → 1.00 · calculator 0.75 → 1.00 · calendar_lookup 0.00 → 1.00 · price_lookup 0.00 → 1.00 · weather_lookup 0.00 → 1.00.
Two honest observations from the table:
- **Validity ≠ correctness.** The baseline scores 1.00 on AuditKIT validity because its wrong arguments are still well-formed strings against the schemas (a lower-cased ticker is still a string). Only the exact-match family exposes the failure — which is why this evaluation reports both.
- **The improved policy's 1.00 is an in-distribution result.** It shows the distilled policy generalises to *unseen entities and values* under *seen task phrasing*. It does not show robustness to novel phrasing, multi-step tasks, or free-form user language — see Limitations.
## What the GPU SFT step adds
The local distillation proves the trajectory dataset teaches the target behaviour and gives a verified before/after harness. Fine-tuning Aya Expanse / Tiny Aya on the same `sft_agenttune.jsonl` (notebook: `train_aya_sft.ipynb`) is what turns that into a deployable model: a single small open-weights model that emits the tool call directly, hostable anywhere, with the AgentTune run directory (`trajectories.jsonl` + provenance) feeding AuditKIT unchanged for post-training scoring on this same test split. Per the AgentTune README, neither Aya model ships a tool-calling chat template, so the run uses AgentTune's documented fallback (tool schemas in the system prompt); Tiny Aya is gated on the Hub and needs a licence acceptance + `hf auth login`.
## Limitations
- Synthetic, single-step, template-generated tasks; 40 held-out items. Real user phrasing is messier — a natural-language test set is the obvious next step.
- Template wording families are shared across the split (only entities/values are disjoint), so the improved policy's perfect score is an upper bound for in-distribution phrasing, not a general tool-calling benchmark (it is not BFCL).
- The "improved policy" is a symbolic distillation, not a neural model; it cannot handle tasks outside the 5-tool schema. The LLM SFT step exists precisely to lift that ceiling.
- Tools are deterministic local stand-ins, not live APIs; no latency, error, or partial-result behaviour is measured.
## ROI note (estimates — clearly labelled)
*Estimates, not measurements:* a self-hosted ~8B open model on a single commodity GPU typically serves tool-calling traffic at a small fraction of the per-call price of a frontier closed API, with no per-token exposure of user data to a third party. For high-volume, narrow-schema agent traffic (the AgentMart case: a handful of tools, short prompts), the break-even against closed-API pricing is usually reached quickly; the cost is operational (hosting, updates) rather than per-call. The reliability gain measured above — task success 0.15 → 1.00 in-distribution after trajectory-based post-training — is the part of that trade this project actually measured; the dollar figures depend on deployment and are not claimed here.
## Reproduce
```bash
python3 -m venv .venv && .venv/bin/pip install auditkit==1.1.11
.venv/bin/python src/generate_data.py # tasks + AgentTune artefacts
.venv/bin/python src/evaluate.py # writes results/metrics.json
```
Full details: `README.md`. AgentTune reference clone used for the formats: `AgentTune_ref/` (github.com/lexsi-labs/AgentTune). AuditKIT: `auditkit==1.1.11` on PyPI (auditkit.lexsi.ai).