{"slug": "fine-tuning-a-model-on-your-agent-traces-a-practical-guide", "title": "Fine-Tuning a Model on Your Agent Traces: A Practical Guide", "summary": "A practical guide for ML engineers and CTOs argues that fine-tuning a smaller model on successful agent traces — a form of distillation — can cut the cost of routine agent traffic, citing a May 2026 step-rejection fine-tuning paper that added 2.4 points on SWE-bench Verified from training on successful runs and 3.7 points, reaching 32.2%, when individual steps were filtered with a critic model. A December 2025 study on on-policy expert corrections reported a relative 14% gain at 7B parameters and 13% at 32B over plain imitation on SWE-bench Verified, while a 2025 study on distilling LLM agents found 0.5B to 3B parameter agent-distilled models performed competitively with 1.5B to 7B chain-of-thought distilled models across eight tasks. The guide distinguishes supervised fine-tuning, distillation and reinforcement fine-tuning, and warns that long tasks are where student models break, citing an October 2026 progress-aware distillation paper.", "body_md": "## On this page 14\n\nYour agent runs on a frontier model, and most of what it does is routine. Look up the order, call the refund tool, write a two-line reply. You pay frontier prices for every one of those steps. Meanwhile your trace logs hold thousands of runs where the agent did the job right, each one a worked example of the task. Fine-tuning on agent traces turns those runs into training data for a smaller model that can take the routine traffic. This guide is for ML engineers and CTOs running agents in production. It explains how distillation and fine-tuning relate, what recent research says about training on agent runs, and the pipeline from raw traces to a student model you can trust, with Python you can run and the tools worth using in late 2026.\n\n## Distillation vs fine-tuning: the same training step, different data\n\nThe two terms get used as if they were rivals. They are not. Most of the time, distillation is fine-tuning with a particular kind of data.\n\n**Supervised fine-tuning (SFT)** trains a model on examples of correct responses. Hugging Face’s [TRL documentation](https://huggingface.co/docs/trl/sft_trainer) calls it the simplest and most common way to adapt a language model to a dataset: the model learns to predict each token of the target response.\n\n**Distillation** transfers knowledge from a larger model, the teacher, to a smaller, cheaper one, the student. That is how [Amazon Bedrock defines it](https://docs.aws.amazon.com/bedrock/latest/userguide/model-distillation.html), and the idea goes back to Hinton and colleagues’ 2015 paper on compressing large models into small ones.\n\nOpenAI’s [distillation guide](https://developers.openai.com/api/docs/guides/distillation) shows how the two meet in practice. You capture a large model’s responses, filter them, then fine-tune a smaller model on what is left. So when your traces come from a frontier model doing the work, fine-tuning a small model on them is distillation.\n\n**Reinforcement fine-tuning** is the different one. The model is not shown the right answer. It tries the task, a grader or the environment scores the attempt, and the model learns from the score.\n\n| Method | Training data | You need | Use it when | \n|---|---|---|---|\n| SFT on human-written examples | Responses written or corrected by people | Labeling time | No good model output exists yet | \n| Distillation (SFT on teacher traces) | Successful runs by a larger model | A trace store and an outcome signal | A frontier agent already does the job and you want it cheaper | \n| Reinforcement fine-tuning | Scores from a grader or environment | A reliable reward and an environment to run tasks in | You can check answers automatically and want to beat the teacher | \n\nThis guide covers the middle row, because it is where most production teams start. Your agent is already generating the data.\n\n## What research says about training on agent runs\n\nThe results are real, but modest. Read the numbers before you promise anyone a frontier model at a tenth of the price.\n\n- **Filtering for success helps, and finer filtering helps more.** A May 2026 paper on[step rejection fine-tuning](https://arxiv.org/abs/2605.10674) found that training on successful runs added 2.4 points on SWE-bench Verified. Filtering individual steps with a critic model added 3.7, reaching 32.2%.\n- **Correcting the student’s own mistakes beats pure copying.** A December 2025 study on[on-policy expert corrections](https://arxiv.org/abs/2512.14895) reports a relative 14% gain at 7B and 13% at 32B over plain imitation on SWE-bench Verified.\n- **Small agents can match bigger non-agent models.** A 2025 study on[distilling LLM agents](https://arxiv.org/abs/2505.17612) found agent-distilled models of 0.5B to 3B parameters performed competitively with chain-of-thought distilled models of 1.5B to 7B across eight tasks.\n- **Long tasks are where students break.** An October 2026 paper on[progress-aware distillation](https://arxiv.org/abs/2610.19439) found that SFT-distilled small agents tend to stall and loop on long trajectories, across eight small models from 0.6B to 8B.\n\nThe pattern for production: a fine-tuned student can take short, well-defined tasks. Keep long, open-ended runs on the teacher, at least until your own evaluation says otherwise.\n\n## The pipeline from production traces to a deployable student\n\nSix steps, with a hard boundary in the middle. Personal data must be removed before traces leave your production environment for training.\n\n```\nProduction agent (teacher: frontier model)\n   |  traces: OpenTelemetry GenAI spans, Langfuse, LangSmith or Phoenix\n   v\nTrace store  &lt;---  outcome labels from your systems\n   |               (ticket resolved, tests passed, human approved)\n   v\n1. Filter: complete runs with a successful outcome only\n   v\n2. Scrub personal data            ===== trust boundary: production data ends here =====\n   v\n3. Convert to chat JSONL with tools and tool calls\n   v\n4. Split by task: train set and held-out evaluation set\n   v\n5. LoRA fine-tune the student (TRL, Unsloth or Axolotl)\n   v\n6. Evaluate against the teacher -&gt; shadow traffic -&gt; router sends routine tasks to the student\n```\n\n### Step 1: Capture traces you can train on\n\nA useful trace holds the whole conversation: the system prompt, the tool definitions, every tool call with its arguments, every tool result and the final answer. Many tracing setups drop some of these by default.\n\nThe [OpenTelemetry GenAI agent conventions](https://github.com/open-telemetry/semantic-conventions-genai/blob/main/docs/gen-ai/gen-ai-agent-spans.md) are still marked as in development. Message content (`gen_ai.input.messages`) is opt-in and, in the spec’s own words, likely to contain sensitive data, so check that your setup records it at all.\n\nObservability tools differ in export formats. LangSmith exports datasets as JSONL or in OpenAI’s fine-tuning format, Phoenix exports OpenAI fine-tuning JSONL, and Langfuse exports CSV or JSON that you convert yourself. Whichever you use, check that tool calls survive the export before you build on it.\n\n### Step 2: Keep only the runs that succeeded\n\nFilter on an outcome your business records, not on the model’s own claim that it finished. A support ticket that stayed closed, a pull request whose tests passed, a draft a human approved without edits. That is rejection sampling: keep the runs that passed, discard the rest.\n\nAlso drop exact duplicates, which over-weight your most common request, and check the balance of task types. A dataset that is 90% password resets trains a password-reset model.\n\n### Step 3: Scrub personal data before training\n\nModels can memorize training data and repeat it. A customer’s email address in a tool result can come back out of the student months later, in someone else’s conversation. Remove personal data before the traces leave production, and keep the scrubbed copy as the only training input.\n\n### Step 4: Convert traces to a tool-calling dataset\n\nTRL’s `SFTTrainer` supports tool calling. Each row holds a `messages` list, with `tool_calls` on assistant turns and `tool` messages for results, plus a `tools` column with the JSON schemas the agent had. Together AI’s fine-tuning service accepts the same conversational shape.\n\nThe script below does steps 2 to 4. It expects one JSON object per line, with `task_id`, `outcome`, `tools` and `messages` in the OpenAI chat format, which most tracing exports can be mapped to:\n\n```\n# prepare_traces.py: turn exported agent traces into a TRL tool-calling dataset.\n# Python 3.10+, standard library only.\n# Usage: python prepare_traces.py traces.jsonl\nimport hashlib\nimport json\nimport re\nimport sys\n\n# Outcomes your system records when a run did the job (not the model's own claim)\nSUCCESS = {\"resolved\", \"approved\", \"tests_passed\"}\nEVAL_SHARE = 10  # percent of tasks held out for evaluation\n\n# A minimum, not a PII solution: emails, phone numbers and card-like numbers\nPATTERNS = [\n    (re.compile(r\"[\\w.+-]+@[\\w-]+\\.[\\w.-]+\"), \"<EMAIL>\"),\n    (re.compile(r\"\\b(?:\\d[ -]?){13,16}\\b\"), \"<CARD>\"),\n    (re.compile(r\"\\+?\\d[\\d ()-]{8,}\\d\"), \"<PHONE>\"),\n]\n\ndef scrub(text):\n    for pattern, token in PATTERNS:\n        text = pattern.sub(token, text)\n    return text\n\ndef clean_message(message):\n    out = {\"role\": message[\"role\"]}\n    if message.get(\"content\"):\n        out[\"content\"] = scrub(message[\"content\"])\n    if message.get(\"tool_calls\"):\n        out[\"tool_calls\"] = [\n            {\n                \"type\": \"function\",\n                \"function\": {\n                    \"name\": call[\"function\"][\"name\"],\n                    # Arguments as a JSON string keep one column type across\n                    # tools, so the datasets loader does not choke on mixed shapes\n                    \"arguments\": scrub(json.dumps(call[\"function\"][\"arguments\"])),\n                },\n            }\n            for call in message[\"tool_calls\"]\n        ]\n    if message[\"role\"] == \"tool\" and message.get(\"name\"):\n        out[\"name\"] = message[\"name\"]\n    return out\n\ndef usable(trace):\n    messages = trace.get(\"messages\", [])\n    return (\n        trace.get(\"outcome\") in SUCCESS\n        and messages\n        and messages[-1][\"role\"] == \"assistant\"\n        and messages[-1].get(\"content\")\n    )\n\ndef held_out(task_id):\n    # Split by task, not by row, so near-identical runs of one task\n    # never land on both sides of the split\n    digest = hashlib.sha256(task_id.encode()).hexdigest()\n    return int(digest, 16) % 100 < EVAL_SHARE\n\ndef main(path):\n    seen, counts = set(), {\"read\": 0, \"kept\": 0, \"train\": 0, \"eval\": 0}\n    with open(path) as src, open(\"train.jsonl\", \"w\") as train, open(\n        \"eval.jsonl\", \"w\"\n    ) as evaluation:\n        for line in src:\n            counts[\"read\"] += 1\n            trace = json.loads(line)\n            if not usable(trace):\n                continue\n            row = {\n                \"messages\": [clean_message(m) for m in trace[\"messages\"]],\n                \"tools\": trace[\"tools\"],\n            }\n            # Drop exact duplicates, which over-weight common requests\n            key = hashlib.sha256(json.dumps(row, sort_keys=True).encode()).hexdigest()\n            if key in seen:\n                continue\n            seen.add(key)\n            counts[\"kept\"] += 1\n            target = \"eval\" if held_out(trace[\"task_id\"]) else \"train\"\n            (evaluation if target == \"eval\" else train).write(json.dumps(row) + \"\\n\")\n            counts[target] += 1\n    print(counts)\n\nif __name__ == \"__main__\":\n    main(sys.argv[1])\n```\n\nThe regular expressions are a floor, not a privacy program. Names, addresses and account numbers in free text need a proper PII detection step, and regulated data needs your compliance team’s sign-off on what may be used for training at all.\n\n### Step 5: Train a LoRA adapter on the student\n\nLoRA trains a small set of extra weights instead of the whole model, so a 4B student fits on one GPU and the adapter file stays small. This script uses TRL with PEFT. It needs `pip install \"trl>=1.19\" peft datasets` and a GPU with roughly 24 GB of memory for a 4B model in bf16:\n\n```\n# train_student.py: LoRA fine-tune a small model on the prepared traces.\nfrom datasets import load_dataset\nfrom peft import LoraConfig\nfrom trl import SFTConfig, SFTTrainer\n\n# The student. Any chat model with tool-calling support in its chat template works.\nBASE_MODEL = \"Qwen/Qwen3-4B-Instruct-2507\"\n\ndata = load_dataset(\"json\", data_files={\"train\": \"train.jsonl\", \"eval\": \"eval.jsonl\"})\n\nconfig = SFTConfig(\n    output_dir=\"student-lora\",\n    num_train_epochs=2,\n    per_device_train_batch_size=1,\n    gradient_accumulation_steps=8,\n    learning_rate=1e-4,\n    bf16=True,\n    max_length=8192,\n    gradient_checkpointing=True,\n    # Learn the agent's own turns only, not the tool results it was given\n    assistant_only_loss=True,\n    eval_strategy=\"epoch\",\n    logging_steps=10,\n)\n\ntrainer = SFTTrainer(\n    model=BASE_MODEL,\n    args=config,\n    train_dataset=data[\"train\"],\n    eval_dataset=data[\"eval\"],\n    peft_config=LoraConfig(\n        r=16,\n        lora_alpha=32,\n        lora_dropout=0.05,\n        target_modules=\"all-linear\",\n        task_type=\"CAUSAL_LM\",\n    ),\n)\ntrainer.train()\ntrainer.save_model(\"student-lora\")\n```\n\n`assistant_only_loss` matters more than any other setting here. Without it, the student also learns to predict tool results, which teaches it to invent order totals instead of asking for them. It needs a chat template that marks assistant turns, and TRL’s SFT documentation shows how to check. If the template lacks the markers, TRL stops with an error instead of training on the wrong tokens.\n\nHow much data is enough? Vendors set low floors. OpenAI accepted as few as 10 examples and suggested starting around 50, and Google’s Vertex AI suggests 100. Those floors teach a format. A multi-step agent needs many runs of every task type you want the student to handle, and your held-out evaluation, not a rule of thumb, tells you when you have enough.\n\n### Step 6: Prove the student before it takes traffic\n\nRun the held-out tasks through both the teacher and the student, and compare four numbers:\n\n- **Task success rate** , judged by the same outcome signal you filtered on\n- **Tool-call validity:** the arguments parse, the right tool is called, no invented IDs\n- **Steps per task** , because a student that loops will show it here first\n- **Cost and latency per task** , which is why you started\n\nThen run the student in shadow mode on live traffic, logging its answers without sending them. When it holds up, put a router in front: routine task types go to the student, and anything long, unfamiliar or low-confidence goes to the teacher. The teacher keeps generating fresh traces from the hard cases, which become the next training round.\n\nRetrain when your tools change. A trace that calls last quarter’s `issue_refund` schema teaches the student an API that no longer exists. Version each dataset by the tool schemas it was recorded with.\n\n## Open-source tools for fine-tuning on agent traces\n\nThe open-source stack is mature enough that you rarely need to write a training loop. As of late November 2026:\n\n| Tool | What it does well | Notes | \n|---|---|---|\n| [TRL](https://github.com/huggingface/trl/releases) (v1.19) | SFT with tool calling, GRPO, a distillation trainer | Hugging Face’s library, the reference point for the others | \n| [Unsloth](https://github.com/unslothai/unsloth/releases) | Fast, memory-efficient LoRA training on one GPU | Trains Gemma 4 tool-calling data in Gemma’s own format | \n| [Axolotl](https://github.com/axolotl-ai-cloud/axolotl/releases) | Config-file driven training runs | Added full-turn labeling for tool-calling SFT in October | \n| [verl](https://github.com/volcengine/verl/releases) | Reinforcement learning at scale | Multi-turn agentic rollouts | \n| [Agent Lightning](https://github.com/microsoft/agent-lightning) (Microsoft) | Captures an agent’s model calls through a gateway and trains on them | MIT license, v1.0 in August 2026, no changes to agent code | \n| [OpenPipe ART](https://github.com/OpenPipe/ART) | Reinforcement training for multi-step agents | Automatic rewards for tasks without a hand-written grader | \n\nSkip torchtune for new work. Its maintainers say development wound down in 2025.\n\n### Managed fine-tuning is shrinking\n\nIf your plan depends on a hosted fine-tuning service, check it again. OpenAI’s [supervised fine-tuning page](https://developers.openai.com/api/docs/guides/supervised-fine-tuning) says the service no longer accepts new users. Eligible existing customers can create jobs until December 15, 2026, and fine-tunes of the gpt-4.1 family shut down on January 14, 2027. Fireworks has stopped accepting new managed SFT and DPO jobs.\n\nOthers remain. Amazon Bedrock distills between its own Nova and Llama models and can reuse your invocation logs as training data, but its documentation says [distillation is not available for Anthropic models](https://docs.aws.amazon.com/bedrock/latest/userguide/prequisites-model-distillation.html). Google’s Vertex AI tunes Gemini Flash and Flash-Lite models. Together AI accepts tool-calling datasets and bills per token processed.\n\nThe durable route is an open-weight student trained with open-source tools. The weights are yours, and a vendor’s product decision cannot switch them off. Our [beginner’s guide to open-source language models](https://lightrains.com/blogs/open-source-language-models-beginners-guide/) covers choosing one.\n\n## When not to fine-tune at all\n\nFine-tuning is the expensive option. Rule out the cheaper ones first.\n\n- **Route to a cheaper hosted model.** If a smaller model from the same provider already handles the routine tasks with a good prompt, you get most of the savings with no training pipeline.[Controlling AI agent budgets](https://lightrains.com/blogs/ai-agent-budgets-cost-control/) covers routing and cost limits.\n- **Give the small model memory instead of training.** The August 2026[agent memory distillation](https://arxiv.org/abs/2608.07169) paper built a memory from successful runs of a larger model and handed it to 4B to 8B students with no training. It reported a 27.2-point gain on AppWorld. That is a lighter first experiment.\n- **Fix retrieval.** If the agent fails because it lacks facts, training will not fix it.[RAG vs fine-tuning](https://lightrains.com/blogs/rag-vs-fine-tuning-enterprise-ai/) covers that decision.\n\nFine-tuning also loses when volume is low, because the savings never cover the pipeline, and when your tools change every sprint, because each change sends you back to retraining.\n\n## Where this approach breaks down\n\n**Long, open-ended tasks.** The research above shows small students stalling on long trajectories. Route those to the teacher.\n\n**Copying the teacher’s habits.** A success filter checks the outcome, not how the agent got there. A run that succeeded after three unnecessary tool calls teaches the student to make three unnecessary tool calls. Step-level filtering helps, and so does reviewing a sample of the training set by hand.\n\n**Terms of use.** Many model providers restrict using their outputs to train other models. Check your teacher’s terms before you build a dataset from its traces.\n\n**Privacy and consent.** Customer conversations were collected to serve the customer, not to train models. Make sure your privacy policy and contracts cover that use, or keep the data out.\n\n## Running agent fine-tuning with Lightrains\n\nLightrains builds and runs production agents, and a trained student is one way to keep their costs in check as traffic grows. The [AI infrastructure and optimization](https://lightrains.com/services/ai-infrastructure-optimization/) work covers model serving, routing and monitoring, which is where a student model slots in.\n\n[AI agent development](https://lightrains.com/services/ai-agent-development/) covers the agent itself, with the guardrails described in [AI agent guardrails for production](https://lightrains.com/blogs/ai-agent-guardrails-production-systems/).\n\nWhen traces cannot leave your environment, the whole pipeline can run on [private and on-premises infrastructure](https://lightrains.com/services/private-on-premises-ai/).\n\nIf your agent’s model bill is growing faster than its traffic, [talk to Lightrains](https://lightrains.com/get-a-free-quote/?ref=blog-agent-traces). Bring a week of traces and your outcome data, and the first question to answer is whether you need fine-tuning at all.\n\nThis article originally appeared on lightrains.com\n\n##### Leave a comment\n\nTo make a comment, please send an e-mail using the button below. Your e-mail address won't be shared and will be deleted from our records after the comment is published. If you don't want your real name to be credited alongside your comment, please specify the name you would like to use. If you would like your name to link to a specific URL, please share that as well. Thank you.\n\n[Comment via email](https://lightrains.com/cdn-cgi/l/email-protection#3e565b5252517e525759564a4c5f57504d105d5153014d4b5c545b5d4a036c7b041e7857505b136a4b505750591e5f1e73515a5b521e51501e67514b4c1e7f595b504a1e6a4c5f5d5b4d041e7f1e6e4c5f5d4a575d5f521e794b575a5b)", "url": "https://wpnews.pro/news/fine-tuning-a-model-on-your-agent-traces-a-practical-guide", "canonical_source": "https://lightrains.com/blogs/fine-tune-model-agent-traces/", "published_at": "2026-11-25 04:30:00+00:00", "updated_at": "2026-11-26 05:45:05.644598+00:00", "lang": "en", "topics": ["artificial-intelligence", "large-language-models", "ai-agents", "machine-learning", "ai-research"], "entities": ["Hugging Face", "TRL", "Amazon Bedrock", "OpenAI", "Hinton"], "also_reported_by": [], "takeaway": "Fine-tune a smaller student model on successful frontier-agent traces, and filter individual steps with a critic model rather than only whole runs: step-rejection fine-tuning added 3.7 points on SWE-bench Verified (reaching 32.2%) versus 2.4 points for run-level filtering.", "recommendation": {"advice": "Filter agent traces at the step level with a critic model before fine-tuning a smaller student, not just whole successful runs; the cited paper gained 3.7 points on SWE-bench Verified versus 2.4 for run-level filtering.", "playbook": "training-data", "playbook_url": "https://wpnews.pro/playbooks/training-data"}, "alternates": {"html": "https://wpnews.pro/news/fine-tuning-a-model-on-your-agent-traces-a-practical-guide", "markdown": "https://wpnews.pro/news/fine-tuning-a-model-on-your-agent-traces-a-practical-guide.md", "text": "https://wpnews.pro/news/fine-tuning-a-model-on-your-agent-traces-a-practical-guide.txt", "jsonld": "https://wpnews.pro/news/fine-tuning-a-model-on-your-agent-traces-a-practical-guide.jsonld"}}