Fine-Tuning Domain-Specific AI Agents: A Practical Guide
When to fine-tune a model for a domain agent instead of prompting or RAG, how to build a tool-call dataset, and how to train, test and serve LoRA adapters.
A domain-specific agent is a general model that has been taught to behave reliably inside one field: it uses your terminology, follows your output formats and calls your tools with the right arguments. Fine-tuning is one way to get there, but it is rarely the first step. This guide covers when training is worth the effort, how to shape a dataset that includes tool calls, how parameter-efficient methods such as LoRA and QLoRA keep the cost down, and how to measure and serve the result. Facts come from the Hugging Face TRL and PEFT documentation, the LoRA and QLoRA papers, OpenAI’s fine-tuning guides and the vLLM docs, all linked below.
Start with evals and prompts, not training
OpenAI’s model optimization guide describes a loop: write evals that set a baseline, prompt the model, optionally fine-tune, then rerun the evals on realistic test data and adjust. Its supervised fine-tuning guide is blunter, telling readers to set up evals before spending anything on training, because without them you cannot tell whether the tuned model beats the base one.
Prompting and retrieval should handle most of a domain agent’s knowledge. The same optimization guide recommends putting the context a model needs into the request itself, including data from private databases or information that changes minute to minute. That is retrieval-augmented generation in practice: facts that change belong in a lookup, not in model weights.
Fine-tuning earns its place when the problem is behaviour rather than knowledge. OpenAI lists these advantages over prompting alone:
| Benefit of fine-tuning | What it means for an agent |
|---|---|
| More examples than fit in one context window | The model sees many more edge cases than a few-shot prompt can hold |
| Shorter prompts | Fewer tokens per request, which can cut cost and latency at scale |
| Train on sensitive data once | Proprietary examples do not have to be resent with every call |
| A smaller model can specialise | A cheaper model can handle a narrow task a larger one was doing |
The supervised fine-tuning guide names classification, nuanced translation, producing content in a fixed format, and fixing failures to follow instructions as good fits. For agents, the last two matter most: consistent JSON, consistent tool calls.
A note on OpenAI fine-tuning in 2026
If you planned to fine-tune a hosted OpenAI model, check eligibility first. OpenAI’s supervised fine-tuning page says the company is winding down its fine-tuning platform. Newcomers are locked out, and qualifying current customers have until January 6, 2027 to launch training jobs, or less if the base model is retired first. Already-tuned models keep serving until their base model is retired; gpt-4.1-nano and its tuned versions were retired on October 23, 2026, and gpt-4.1 and gpt-4.1-mini follow on January 14, 2027. For new projects, that pushes most teams toward open-weight models and the Hugging Face tooling below.
Build the dataset
Both OpenAI and Hugging Face TRL use the same basic shape: a list of chat messages with roles. TRL’s SFTTrainer accepts plain text, prompt-completion pairs, or conversational data, and it applies the model’s chat template for you when the data is conversational.
For an agent, the examples that matter most are the ones where the assistant calls a tool. TRL’s dataset formats page shows an assistant turn that carries a tool_calls field, followed by a tool message holding the result. It also asks for an extra tools column listing the available functions as JSON schemas, which the chat template typically uses to build the system prompt. This is TRL’s own example:
messages = [
{"role": "user", "content": "Turn on the living room lights."},
{"role": "assistant", "tool_calls": [
{"type": "function", "function": {
"name": "control_light",
"arguments": {"room": "living room", "state": "on"}
}}]
},
{"role": "tool", "name": "control_light", "content": "The lights in the living room are now on."},
{"role": "assistant", "content": "Done!"}
]
# one dataset row: {"messages": messages, "tools": [json_schema]}
TRL can generate that schema from a typed Python function with docstrings using get_json_schema from Transformers. OpenAI’s JSONL format is close: one JSON object per line, with messages, tools and an assistant turn containing tool_calls.
On quantity and quality, OpenAI’s guidance is a useful default for any provider:
- The hard minimum is 10 examples. Gains often show up with 50 to 100, though the right number depends heavily on the task.
- Start with roughly 50 carefully built examples, evaluate, and only then add more. If 50 change nothing, revisit the task or prompt.
- Make examples look like real production traffic. Historical logs and expert-written answers are good raw material.
The same guide describes distillation: tune a prompt on a large model until it passes your evals, keep the outputs that meet your criteria, and use them as training data for a smaller model.
Train a LoRA adapter
Full fine-tuning updates every weight, which is expensive to train and to store per task. The LoRA paper froze the pretrained weights and added small trainable low-rank matrices to each Transformer layer. Against GPT-3 175B fine-tuned with Adam, the authors report 10,000 times fewer trainable parameters and a threefold cut in GPU memory, with quality on par with or better than full fine-tuning on the models they tested, and no added inference latency.
The QLoRA paper went further by keeping the frozen base model in 4-bit precision and backpropagating into LoRA adapters. It introduced the 4-bit NormalFloat (NF4) data type, double quantization and paged optimizers, and fine-tuned a 65B-parameter model on one 48GB GPU. The authors also found that a small, high-quality dataset could give state-of-the-art results.
In the PEFT library, a LoraConfig sets which modules to adapt and the rank r, which controls adapter size and capacity. By default PEFT adds LoRA weights to the query and value layers of attention; the LoRA developer guide notes that target_modules="all-linear" covers every linear layer, as QLoRA does. Saving writes only the adapter weights, so an adapter is a small file next to a shared base model.
TRL wires PEFT into its trainer directly. This is the adapter example from the SFTTrainer docs:
from datasets import load_dataset
from trl import SFTTrainer
from peft import LoraConfig
dataset = load_dataset("trl-lib/Capybara", split="train")
trainer = SFTTrainer(
"Qwen/Qwen3-0.6B",
train_dataset=dataset,
peft_config=LoraConfig(),
)
trainer.train()
Swap in your own conversational dataset with a tools column for an agent. Three settings from the TRL docs are worth knowing:
assistant_only_loss=TrueinSFTConfigcomputes loss only on assistant turns, so the model is not trained to imitate user or system text.- For prompt-completion data, loss on the completion only is already the default.
- When training adapters, TRL suggests a higher learning rate, around
1e-4, because only the new parameters are learning.
For background on the wider family of methods, see our PEFT tutorial, and for 4-bit loading, our quantization guide.
Evaluate before and after
Run the same eval set against the base model with your best prompt and against the tuned model. TRL’s SFTTrainer takes an eval_dataset and logs loss and mean token accuracy, which help you spot overfitting, but they do not tell you whether the agent picks the right tool. For that you need task-level checks: did it call the right function, were the arguments valid against the schema, was the final answer correct? Hold out real examples that never appear in training. Our evaluation and monitoring hub lists tools for running these checks.
QLoRA’s authors also caution that the chatbot benchmarks they examined were not reliable for judging chatbot quality. Treat public leaderboards as a weak signal and your own domain evals as the real one.
Serve the adapter
You have two main options:
- Merge. PEFT’s
merge_and_unload()folds the adapter into the base weights and returns a standalone model, which removes the overhead of loading the adapter separately. It returns a new model rather than changing the original in place. - Serve adapters on a shared base. vLLM can apply LoRA adapters per request on top of one base model. Start the server with
--lora-modules, and clients choose an adapter by passing its name as themodelin an OpenAI-compatible request:
vllm serve meta-llama/Llama-3.2-3B-Instruct \
--enable-lora \
--lora-modules sql-lora=jeeejeee/llama32-3b-text2sql-spider
The second option suits teams with several domain agents, for example one adapter for claims handling and one for contract review, on the same base model. vLLM can also load and unload adapters at runtime, but its docs warn that this has security risks and should only be used in an isolated, fully trusted environment.
Whichever route you choose, keep the tool definitions the agent sees in production the same as the ones in training data. Our post on function calling and tool use covers how models receive those schemas.
Written by AI Agents Directory
Editorial team
Facts in this guide are checked against official documentation and repositories, which are linked in the article.