06 · Tool calls for agents
Teach a 1.5B model to emit one tool call a program can check. On functions it never saw in training it stopped calling tools it should not and wrote better values, lifting the pass rate from 80.2% to 88.4%, but its call rate fell 8 points as it began asking questions instead.
- Part 2
- Train
- Model
Qwen/Qwen2.5-1.5B-Instruct- Data
- Glaive function-calling v2 (Apache-2.0), split by function
- Hardware
- One T4, in Google Colab
An agent, in the sense used in these lessons, is a system in which a model chooses actions in a loop: read the situation, pick a tool, see the result, pick again. This lesson does not build that loop. It trains the one step inside it that a fine-tune can improve and a program can check: given a few function definitions and a request, write one call in the right form, or write no call when the request needs none. Qwen2.5-1.5B-Instruct from lesson 2 is the model; its own chat template already knows how to ask for a tool.
The result first, then how it was reached; the exact setup, time and cost are in How it was built at the end. Training lifted the pass rate from 80.2% to 88.4%, by teaching the model restraint and better values, at the price of a lower call rate:
Training fixed abstention and values but lost calls: the call rate fell 8 points while the right-value rate rose
Pass rate, %, on the same 500 held-out examples, before (○) and after (●) training; shaded bar: 95% interval of the tuned result
1Call examples (300): four stages
Cumulative: a call counts at a stage only if it passed the earlier ones
aNo-call examples: stayed silent
The right output is plain text, not a call
bEvery output in lessons 1 to 5 was something a person had to read. A tool call is different, because the reader is an API: it either parses and runs, or it fails. That makes the task unusually measurable, and it has a clear record, mostly in research and in one production system:
| Source | Model and method | What it showed | Status |
|---|---|---|---|
| Shopify Flow | Qwen3-32B, supervised fine-tuning on tool-call trajectories | Matched a prompted model offline; at 1% of traffic its workflow activation rate was 35% lower | Production |
| Gorilla (Berkeley) | LLaMA-7B on 16,450 API instruction pairs | 6.98% hallucinated calls on TorchHub against GPT-4's 36.55% | Research paper |
| APIGen and xLAM (Salesforce) | 1B and 7B models on 60,000 verified calls | A 7B model ranked 6th on the Berkeley function-calling leaderboard in June 2024 | Research paper |
| TinyAgent (Berkeley) | 1.1B model with LoRA on 80,000 synthetic plans | Success 12.71% to 78.89% on its own task; GPT-4-Turbo scored 79.08% | Research paper |
Shopify is the only genuine production report found; the others are published research, and each number above is the source's own. The pattern across them is the structure of this lesson: build the checker first, make the test fair, then measure each stage rather than one score.
1. A call is a contract
A tool call is a proposed operation, not a sentence describing an operation. The host can check the name and input before accepting it. A valid format and a correct business action are separate requirements.
When a person reads an answer, a small slip costs little. When an API reads a call, one misplaced quote costs the whole call. So a tool call can fail in distinct ways, in order: the text is not a call at all, the function does not exist, the arguments break the function's rules, or the arguments are valid but wrong. Each needs a different fix, and a single accuracy figure hides which one a model has.
Shopify's engineers found a fifth failure that no offline score showed. They fine-tuned Qwen3-32B to build Flow automations from a merchant's request, and it matched the prompt-based agent on their benchmark of 300 hand-crafted examples. At 1% of live traffic, though, its workflow activation rate was 35% lower. The benchmark had not covered editing existing workflows, email configuration, third-party integrations, or messages that are not requests to build a workflow at all. Their account is company-reported, and its lesson is the second half of this one: a model must also know when not to act, and a test must contain such cases.
2. How a program decides
The checker has four stages, applied in order, and a call is counted at a stage only if it passed all earlier ones:
- parse: the output is exactly one
<tool_call>block holding a JSON object withnameandarguments, and nothing else; - name: the function is one that was offered, and the one the request needs;
- schema: the arguments satisfy the function's JSON Schema, with no argument it does not declare;
- exact: the arguments equal the gold arguments, strictly (
1is nottrue,Parisis notparis).
For call examples with stage flags , the pass rate at each stage is a running product, so the rates can only fall from left to right:
A drop between two stages names the weakness. Only the last stage needs a gold answer; the first three need the function list alone, so they could run on live traffic as a guard that refuses a malformed call before it reaches an API. A request that needs no call passes when the output contains no call and is not empty.
Every way a call can be wrong stops at one stage, and three of the four stages need no gold answer
Fifteen hand-written outputs for one request (weather in Paris, in celsius) against two offered functions; each column is a stage, cumulative from left to right
2A checker is code, so it is tested before it is trusted. The notebook runs the 15 outputs above, plus three no-call cases, through asserts that fail the whole notebook if the checker disagrees with the table. Two of the rows matter most. "Same call, keys in another order" passes, because the checker compares parsed JSON rather than text; and "city": 75001 is rejected at the schema stage, before it reaches anything.
def check(output, tools, gold):
"""Four stage flags, `ok`, and `failure`: the first stage that failed."""
...
errors = set(argument_errors(call["arguments"], offered[call["name"]])) # schema + undeclared
if errors:
return fail(next(label for key, label in SCHEMA_LABELS if key in errors))
res["schema"] = True
if not strict_equal(call["arguments"], gold["arguments"]): # 1 is not True
return fail("valid arguments, wrong value")APIGen, Salesforce's data pipeline for training function-calling models, applies the same idea to training data: every generated call must pass a format check, an execution check and a semantic check before it is kept.
| Generator | Verified | Failed format | Failed execution | Failed semantic | Pass rate |
|---|---|---|---|---|---|
| DeepSeek-Coder-33B-Instruct | 13,769 | 4,311 | 15,496 | 6,424 | 34.42% |
| DeepSeek-V2-Chat (236B) | 33,659 | 817 | 3,359 | 2,165 | 84.15% |
The paper's authors say format and execution checks remove most of the poor data, and that adding data which failed them back into training hurts, more so for the smaller model (arXiv 2406.18518, table 1 and figure 5). The same checker that scores the model should also filter its training data.
3. What data, and is it clean?
The data is glaive-function-calling-v2, 112,960 chat transcripts under Apache 2.0, each with one or two function definitions in its system message. Its calls are written in a home-made form, with the arguments as a quoted string, so each target has to be parsed. The lab uses only the first assistant reply to the first user message, and only replies that are exactly one call or no call. That narrows the claim on purpose: nothing here covers several calls in a row or a conversation with tool results.
Four in ten of the 112,960 transcripts are repeats; only 45,157 survive to be sampled
Cleaning funnel, first assistant reply only: conversations kept (blue) and dropped at each step (orange), in the order the notebook applies them
3The largest loss is exact duplicates, 44,291 of the 104,378 transcripts that reached that step (42%): the same request, the same functions and the same answer. Counting them twice would put test examples into training. One cleaning rule is easy to miss: the gold call must pass the same schema checker as the model, or a correct model would be punished for a bad label. 376 gold calls failed it.
The no-call answers come in three kinds, kept apart because a model can fail them differently. The kind is read from the target text by simple rules, so it is the notebook's label, not the dataset's:
- missing value: the reply asks for something the user did not give ("How long would you like your password to be?");
- no fit: the reply apologises, because no offered function does what was asked ("I don't have the capability to book flights");
- unrelated tools: a plain chat request (an essay, a riddle) to which one or two functions from the same side of the split are added, skipping any whose name shares a word with the request. The right answer stays the original text.
The third kind is the dangerous one in practice, a model that always reaches for a tool. APIGen's authors built the same data on purpose: 8,000 "relevance detection" examples made by dropping a tool the answer calls, or a required parameter, then relabelling the answer as an empty call or a short explanation. Those two constructions are this lab's no-fit and missing-value kinds.
Salesforce’s APIGen pipeline checks synthetic calls in stages: validate the format, execute the function, then judge whether the outcome addresses the request. Salesforce reports releasing 60,000 examples as xLAM-60k. In the lab, keep those checks distinct. A valid call can run and still act on the wrong entity. APIGen paper · Salesforce xLAM-60k dataset card
4. Is the test fair?
The data has about 1,000 function names, and a few (calculate_bmi, calculate_age, convert_currency) appear thousands of times. A random split would test almost only functions seen in training, and measure recall. So the split is by function: each name goes to one side by a hash, 15% test, 5% validation, 80% train; an example takes the side of the functions it lists, and one that lists functions from two sides is dropped (2,846 were). At most two examples share a request text, and a request found on the test side is removed from training. Before sampling, the pool held:
| Kind | Test | Validation | Train |
|---|---|---|---|
| Call | 677 | 153 | 6,646 |
| Missing value | 234 | 124 | 2,215 |
| No fit | 98 | 9 | 219 |
| Plain chat (becomes unrelated tools) | 5,216 | 1,796 | 27,553 |
From these the notebook samples 500 test examples (300 call, 80 missing value, 60 no fit, 60 unrelated tools), 200 for validation, and 4,000 for training (2,200, 800, 200 and 800). The pool holds 711 distinct functions on the train side, 33 on validation and 111 on test (the sampled sets use 646, 32 and 89), and two asserts fail the notebook if any function or request text is on two sides. Two limits remain. Differently named functions that do the same thing (a compute_bmi in train, a calculate_bmi in test) are not caught, and the test's no-fit and missing-value examples draw on few distinct requests: 49 texts for the 60 no-fit examples, 74 for the 80 missing-value ones.
5. Before training
Qwen2.5 was trained on tool calling, so this is a strong baseline. The function list goes in through the chat template's own tools= argument, and the system line says to call only when the request needs it and every required value is stated; the instruction is in the prompt, which is the fair comparison. Greedy decoding, the same checker, the same 500 examples:
| Stage or kind | Pass rate, base model |
|---|---|
| Call examples: parse, name | 100% |
| Call examples: schema | 99.7% |
| Call examples: exact | 75.7% |
| No call: missing value | 88.8% |
| No call: no fit | 98.3% |
| No call: unrelated tools | 73.3% |
| All 500 examples | 80.2% |
The base model never fails to write a call, and almost never writes one that breaks the schema. Its weakness sits at the two ends: the values (72 valid calls with a wrong value) and restraint (26 calls where none was right). One of those, from the notebook:
request: Find the length of each side of this right triangle. 30, 60
gold : (no call)
model : <tool_call> {"name": "generate_random_number", "arguments": {"min": 1, ...}} </tool_call>Offered a function that does not fit, it used it. The gap to close is 80.2% overall, and it is made of values and restraint, not of format.
6. What training changes
The method is lesson 4's: LoRA of rank 16 on every linear layer, fp16, learning rate 2e-4 on a cosine schedule, one epoch, loss on the answer only. Three details differ, each for a reason.
The function list differs in every example, and the dataset library cannot store lists of dictionaries whose keys vary, so the template is applied once and TRL receives a prompt string and a completion string. Because the prompt already ends with the assistant header, that header is masked too, so the loss falls only on the call and the end-of-turn token. With the completion tokens plus that token:
Prompts now average about 320 tokens with the function list, so the batch is 4 with 4 accumulation steps (still 16 effective), and group_by_length puts similar lengths in a batch to cut padding.
config = SFTConfig(
per_device_train_batch_size=4, gradient_accumulation_steps=4, # effective batch 16
num_train_epochs=1, learning_rate=2e-4, lr_scheduler_type="cosine", warmup_ratio=0.03,
fp16=True, bf16=False, # a T4 has no bfloat16
gradient_checkpointing=True, group_by_length=True,
max_length=512, # every kept example fits: nothing is truncated
completion_only_loss=True, # loss on the completion only
)
trainer = SFTTrainer(model=model, args=config, train_dataset=train_ds, eval_dataset=val_ds,
processing_class=tok, peft_config=lora)Two checks run before training. One asserts that, for 25 calls, prompt + completion + <|im_end|> is exactly what Qwen's own template writes for an assistant message with a tool call, so the model is taught the format it already knows rather than a new one. The other collates four examples and counts the labels set to −100: those equal the prompt tokens, and the tokens trained on equal the completion plus one, so the loss sees the call and nothing else.
Validation loss stops improving at step 100, and the run costs 21 minutes and 7.3 GB on a T4
LoRA, rank 16 on all linear layers, 4,000 examples, one epoch of 250 optimizer steps, loss on the answer tokens only
4Loss on 200 validation examples
Mean loss per answer token at every 50th step
aWhat the run used
Training, then answering 500 prompts
bThe training run took 21.2 minutes. Validation loss was 0.30 at step 50 and has settled at 0.26 to 0.27 from step 100, so the last 150 steps moved it little; whether more of the pool would help was not measured. The adapter is 73.9 MB. Answering is slower with the adapter loaded beside the base: 576 ms per example against 288 ms, since the adapter is not merged. Lesson 12 measures the serving options.
7. What changed
The adapter was saved, a fresh copy of the base model loaded it back, and the same 500 prompts were scored again. Figure 1, at the top of the page, shows every stage and kind before and after.
The overall pass rate rose from 80.2% to 88.4% (±2.8). That total is the sum of two opposite movements, and the first of them is a loss.
Restraint improved. Unrelated tools went from 73.3% to 100%, no fit from 98.3% to 100%, and missing value from 88.8% to 96.2%. The model learned that an offered tool is not an instruction to use it.
The call rate fell. On the 300 call examples, the parse stage dropped from 100% to 91.7%: 25 outputs were no longer calls. Schema fell with it, 99.7% to 91.3%.
Values improved, with a caveat. The exact stage rose from 75.7% to 81.7%, but on 300 examples the two 95% intervals (±4.9 and ±4.4) overlap, so that gain alone is not established. The better evidence is the miss count in the next section, and one derived figure: of the 275 calls the tuned model wrote, 245 matched the gold arguments (89.1%), against 227 of 300 (75.7%) for the base model. Among the calls it chose to make, the values were better.
Training fixed 50 examples and broke 9; the net gain is 41 of 500
Each of the 500 test examples by whether the base model and the tuned model passed it (call: all four stages; no call: wrote no call)
5Counted per example, 50 were fixed and 9 broken, with 392 passed by both and 49 failed by both. A 50 to 9 split among the 59 that changed is lopsided enough to read as a real net gain of 41, consistent with the ±2.8 interval on the total.
8. What is still wrong
Wrong values fell from 72 to 29 and needless calls from 26 to 3, but 25 calls became text answers
First failing stage of every miss on the 500 test examples, before (grey) and after (blue) training, count
6Wrong values fell from 72 to 29 and needless calls from 26 to 3, which is what the adapter was for. The new row is the cost: 25 examples that should have been calls were answered in text. The notebook prints four of them. All four ask a question instead of calling:
request: ... Can you play the 'Chill Vibes' playlist for me?
gold : {"name": "play_music", "arguments": {"playlist": "Chill Vibes", "shuffle": true}}
model : Sure, I can help with that. Do you want the playlist shuffled?The model did what its training data rewarded: 1,800 of the 4,000 examples (45%) are no-call answers, and 800 of those ask the user for a missing value. Here that habit is arguably reasonable, and the gold call carries a shuffle value the user never gave. This is the limit of the labels. The data was written by a language model, not by users of a real API, so gold sometimes holds an empty string or an invented default, and a clarifying question can be as defensible as the call. The exact stage is strict by design and counts those as misses; the three stages before it do not depend on gold values. The tuned model also still calls when a value is missing in 3 of 80 examples, for instance filling "cuisine": "American" that the user never said.
Hey, I want to listen to some music. Can you play the 'Chill Vibes' playlist for me?
- Gold
- {"name": "play_music", "arguments": {"playlist": "Chill Vibes", "shuffle": true}}
- Tuned
- Sure, I can help with that. Do you want the playlist shuffled?
The loss: a call became a question. The gold call holds a shuffle value the user never gave.
I want to listen to some music. Can you play something from Coldplay?
- Gold
- (no call)
- Tuned
- <tool_call> {"name": "play_music", "arguments": {"artist": "Coldplay", "genre": "pop"}} </tool_call>
Still wrong: it invents a genre the user did not state, where the gold answer asks.
Find the length of each side of this right triangle. 30, 60
- Gold
- (no call)
- Base
- <tool_call> {"name": "generate_random_number", "arguments": {"min": 1, "max": 10}} </tool_call>
The failure training removed: an offered function that does not fit is used anyway.
So the honest summary is that tuning traded one error for another. It removed most calls that should not happen and improved the values of those that did, and it made the model less willing to call at all. Whether that is a good trade depends on what a wrong call costs against a needless question, which is why each stage is reported on its own.
9. What companies found
Match the prompt exactly. Shopify found that if a tool's name had a prefix in training and none at inference, the model "treated them as different tools"; tool order in the system prompt and the order of keys in tool responses also mattered. This lab's template assert is the same discipline in miniature. Shopify also reported that rewriting its JSON target as Python through a round-trip transpiler improved syntactic correctness by 22 points and semantic correctness by 13 on the same training data, and that after the 1% test email workflows made up 25% of failures. The model is retrained weekly on production conversations that an LLM judge scores highly and where the merchant activated the workflow. A full training run takes 12 hours on two nodes of H200 GPUs (all company-reported).
Fine-tuning reduces invented calls. Gorilla measured it directly, on API-documentation tasks, not a business workload:
A 7B model fine-tuned on API documentation hallucinated calls far less than GPT-4 on the same test
Zero-shot, % of test prompts, three API collections: calls matching a real API (left, higher is better) and calls to an API that does not exist (right, lower is better)
7Accuracy
Matches a real API, %
aHallucination
Calls an API that does not exist, %
bSmall models can match large ones on a narrow task. TinyAgent fine-tuned a 1.1B model with LoRA on 80,000 synthetic plans, with unrelated functions included as negative examples, which the authors found particularly effective for teaching tool choice. Success rose from 12.71% to 78.89% on its own task, where success needs the right functions and the same dependency graph; GPT-4-Turbo scored 79.08%. The 4-bit 1.1B model was 0.68 GB and answered in 2.9 s on the authors' laptop demo. It is a research result, not a production system.
Vendor tutorials show the recipe, not a customer. Two AWS posts fine-tune small models for tool use. One reports Amazon Nova Micro's tool-call accuracy rising from 75.8% to 95% on a synthetic set of 8 tools with 120 test questions. The other trains Qwen3-1.7B with supervised fine-tuning and then DPO, taking accuracy from 41.57% to 60.43% and then 71.06%. Both are the vendor's own numbers on small synthetic sets, so read them as walkthroughs. The second leads into lesson 7, because DPO trains on pairs of better and worse answers.
What to keep
| Base | Tuned | |
|---|---|---|
| All 500 examples passed | 80.2% | 88.4% (±2.8) |
| Call examples: exact | 75.7% | 81.7% (±4.4) |
| Call examples: parse | 100% | 91.7% |
| No call: unrelated tools | 73.3% | 100% |
| Time per answer | 288 ms | 576 ms, adapter unmerged |
The product is an adapter of 73.9 MB, loaded on the original Qwen2.5-1.5B-Instruct. Prompts must be built the same way: tools= in the chat template and the same system line. The results hold for one call per answer, one user turn and labels written by a language model. They say nothing about calls in a sequence, about tool results fed back, or about real users.
If you have a task like this one:
- Measure the untuned model stage by stage first. Here it never failed to write a call; its gaps were values and restraint, so format training would have bought little.
- Train on cases where the right answer is no call. Unrelated tools went from 73.3% to 100% with 800 such examples in 4,000; a training set of calls only would not teach it.
- Report each stage and kind separately. The total rose 8.2 points while the call rate fell 8.3, and a single score would have hidden the trade.
- Split the test by function name, not by example. A few functions appear thousands of times, so a random split would measure recall of seen functions.
- Decide what a wrong call costs against a needless question before choosing the mix of no-call examples; this mix moved the model towards asking.
Next to try, not tested here:
- The 25 lost calls: use fewer missing-value no-call examples than the 800 used, or score a clarifying question as correct when the gold call holds a value the user never stated.
- The 29 remaining wrong values: check how many are gold labels that hold an empty string or an invented default, and clean them.
- The 576 ms per answer: merge the adapter into the base weights before serving (lesson 12 measures the options).
How it was built
| Item | Setting |
|---|---|
| Base model | Qwen/Qwen2.5-1.5B-Instruct, fp16 (1,562,179,072 parameters) |
| Data | glaive-function-calling-v2 at one pinned commit, first assistant reply only. 4,000 train (2,200 call, 800 missing value, 200 no fit, 800 unrelated tools), 200 validation (100, 50, 0, 50), 500 test (300, 80, 60, 60); split by function name |
| Test | 500 held-out examples. Pass rate per stage (parse, name, schema, exact) on call examples; a no-call example passes when the output holds no call |
| Method | LoRA, rank 16, alpha 32, dropout 0.05, target modules all linear layers, 18,464,768 trainable parameters (1.18%) |
| Training | 1 epoch, 250 optimizer steps, batch 4 with 4 accumulation steps (effective 16), learning rate 2e-4 with a cosine schedule and 0.03 warm-up, fp16, gradient checkpointing, group_by_length, max length 512, loss on the completion only, seed 42 |
| Decoding | Greedy, batches of 16, at most 160 new tokens, same system line and tools= template for both systems |
| Hardware | Colab T4. transformers 4.51.3, peft 0.15.2, accelerate 1.6.0, trl 0.19.1, datasets 3.6.0, jsonschema 4.23.0 |
Time and cost. Training took 21.2 minutes including the validation passes, at about 1,010 padded tokens per second over 1,279,719 real tokens (about 1,282,132 padded). Peak GPU memory was 7.26 GB allocated and 9.59 GB reserved. The adapter is 73.9 MB. Answering took 288 ms per example for the base model and 576 ms with the adapter loaded beside it, unmerged. Every pass rate comes from the 500-example test set; the 200-example validation set feeds only the loss curve in Figure 4, and the Gorilla numbers in Figure 7 are the paper's own.
Run it yourself
The notebook runs in about 40 minutes on a free Colab T4: 21 minutes of training, two generation passes of 500 prompts, and the data preparation. Its sections map to this page: 1 is the data, 2 is the checker, 3 is the split and the prompts, 4 is the baseline, 5 is training, 6 is what changed, 7 is what is still wrong and 8 is what to keep. Three changes to try:
- Remove the 800 unrelated-tools examples from
TRAIN_MIX. Does the no-call rate on unrelated tools fall back towards 73.3%, and does the call rate recover? - Score a version that counts a clarifying question as correct when the gold call holds a value the user never stated. How much of the 8.3-point call-rate drop disappears?
- Merge the adapter into a 16-bit copy and time the same 500 prompts. How much of the 576 ms does merging recover?
Lesson 7 moves to preference tuning, which trains on pairs of better and worse answers.
How is this page?
Last updated on