Tool use: when does a call earn its place in the text?
工具使用
Recompute Toolformer-style loss filtering with a hand-specified toy model, and see why a kept call can still agree with a stale sentence.
tool-useA calculator is useful only at the right moment
A language model that has read a great deal of text can still add two four-digit numbers incorrectly, cannot know today’s date, and has never seen a company’s private customer list. The MRKL paper lists these gaps as missing current information, missing proprietary information and unreliable symbolic reasoning, and observes that its own and other large models produced confident wrong answers on four-digit addition. Section 1 A calculator, a calendar or a database query fixes each gap cheaply.
The hard part is not the tool but the decision around it. Where in a sentence should the call happen? Which tool, with which input? Does the returned text actually help? A call placed where the model already knows the answer wastes time; a call whose input already contains the answer adds nothing; a call returning a wrong value makes things worse.
Tool use here means a model producing a request for an external program and then continuing with that program’s output in its context. This article follows the self-supervised route of Toolformer, which lets the model propose calls and keeps only the calls that make the following text easier to predict. Section 2 We rebuild the filtering arithmetic with a tiny hand-specified probability model so every number can be checked by hand. No language model is trained or queried.
Insert, execute, filter
Calls as text. Toolformer requires every tool’s input and output to be representable as text. A call c is a pair of an API name and an input. It is written into the text in one of two linearized forms, without and with its result r:
The special markers are realized in practice with ordinary token sequences for an opening bracket, a closing bracket and an arrow, so the vocabulary is unchanged. Section 2 and footnote 1
Sampling candidates. For each tool the authors write a prompt with a few examples of the call format. For a text x, the model’s probability of starting a call at position i is computed, positions above a sampling threshold are kept (at most k of them), and up to m calls are sampled at each kept position:
Samples that never close the call are discarded. The sampled calls are then executed by whatever system implements the tool. Section 2
Filtering by loss reduction. Let z be a prefix given to the model and w a sequence of weights. The weighted cross-entropy over the tokens from position i onward is
Two quantities are compared. L⁺ gives the model the call together with its result. L⁻ is the better of two alternatives: no call at all, or the call without its result. A call is kept only if it reduces the loss by at least a filtering threshold τ_f:
The minimum matters. If the call’s input alone already makes the next tokens predictable, the result is not what helped, and the call should not be credited. Section 2
During filtering the call is supplied as a prefix rather than inserted at position i, because the not-yet-finetuned model has never seen calls in mid-sentence and an insertion would disturb its predictions. For finetuning, kept calls are inserted at their positions and the model is trained on the augmented text with the ordinary language-modelling objective. At inference, decoding pauses when the model emits the arrow, the tool is called, the response and closing marker are inserted, and decoding resumes. Section 2 and footnote 3
The paper’s experiments use GPT-J as the model, a subset of CCNet as the text, and five tools: a question-answering model, a Wikipedia search engine, a calculator restricted to the four arithmetic operations with results rounded to two decimals, a machine-translation model and a calendar that returns the current date. Sections 3–4.1 The authors argue that because the augmented data contain the same texts apart from inserted calls, finetuning on them should not reduce the model’s generality. Section 2 That is an argument from data construction; the paper tests it with perplexity measurements in a later section that we did not read, and it should not be read as a guarantee of no forgetting.
Inference-time choice, as a decision. Training decides where calls appear in data; at run time a system still has to decide whether to call. The following rule is this article’s own teaching model, not a method from Toolformer or MRKL; it is deliberately simple, used only for the exercises, and compares the probability that the answer is right with and without the tool against the call’s cost κ expressed in the same units:
MRKL’s router faces a version of this decision and adds another cost: when the chosen module is symbolic, the router must extract its discrete arguments from text, which the paper says has to be trained carefully. Section 3
Six calls, one toy model
To compute L⁺ and L⁻ exactly, we replace the language model with a two-part toy. Without a prefix, each continuation token x has a fixed base probability b(x). With a prefix, a fraction λ = 0.7 of probability mass is spread evenly over the distinct tokens in the prefix, so a token is copied only if it appears there; the remaining 0.3 follows the base probability:
where D(z) is the set of distinct tokens in the prefix z. We use weights 1, 0.5 and 0.25 for the first three continuation tokens. These choices are ours, not the paper’s. The six candidate calls are synthetic and each targets one situation:
- calculator-sum: the text continues “42 points” after the call “17 + 25”.
- qa-new-fact: a question-answering call returns “Varnia”, which the base model finds unlikely.
- input-leaks-answer: the question itself contains “Ivo Prand”, the tokens that follow.
- wrong-tool-result: the tool returns 1968, but the text says 1970.
- tool-agrees-with-stale-text: the tool returns 1960, matching a sentence that, in this fictional setting, is out of date.
- already-predictable: the base model already gives the next token, 100, probability 0.6.
"""Original Toolformer-style filtering arithmetic with a hand-specified toy model; no LM is trained."""
import json
import math
COPY = 0.7
WEIGHTS = [1.0, 0.5, 0.25]
# Each synthetic case: candidate call, its returned text, continuation tokens after the call position,
# and the toy model's no-tool probability for each continuation token.
CASES = [
dict(name='calculator-sum', api='Calculator', arg='17 + 25', result='42',
tokens=['42', 'points'], base=[0.01, 0.5]),
dict(name='qa-new-fact', api='QA', arg='Which country has Elsk as capital ?', result='Varnia',
tokens=['Varnia', '.'], base=[0.002, 0.9]),
dict(name='input-leaks-answer', api='QA', arg='Did Ivo Prand design it ?', result='Yes',
tokens=['Ivo', 'Prand', '.'], base=[0.01, 0.05, 0.9]),
dict(name='wrong-tool-result', api='QA', arg='When did Tarn Mill close ?', result='1968',
tokens=['1970', '.'], base=[0.002, 0.9]),
dict(name='tool-agrees-with-stale-text', api='QA', arg='When did Brask Station open ?', result='1960',
tokens=['1960', '.'], base=[0.002, 0.9]),
dict(name='already-predictable', api='QA', arg='At what Celsius temperature does water boil ?',
result='100', tokens=['100', 'degrees'], base=[0.6, 0.8]),
]
THRESHOLDS = [0.25, 0.5, 1.0, 2.0]
def prefix(case, with_result):
tokens = [case['api'], '('] + case['arg'].split() + [')']
return tokens + ['->'] + case['result'].split() if with_result else tokens
def prob(token, base, context):
"""Copy mass is split over distinct context tokens; the rest follows the no-tool model."""
if not context:
return base
distinct = set(context)
return COPY * (token in distinct) / len(distinct) + (1 - COPY) * base
def loss(case, context):
return -sum(w * math.log(prob(x, b, context))
for w, x, b in zip(WEIGHTS, case['tokens'], case['base']))
def score(case):
plain = loss(case, [])
call_only = loss(case, prefix(case, False))
with_result = loss(case, prefix(case, True))
minus = min(plain, call_only)
return dict(name=case['name'], L_none=round(plain, 4), L_call_only=round(call_only, 4),
L_plus=round(with_result, 4), L_minus=round(minus, 4),
reduction=round(minus - with_result, 4),
kept={str(t): minus - with_result >= t for t in THRESHOLDS})
def augmented_text(case):
"""Text used for finetuning keeps the original tokens and inserts the call at position i."""
return ' '.join(['...', '[' + case['api'] + '(' + case['arg'] + ')', '->', case['result'] + ']']
+ case['tokens'])
if __name__ == '__main__':
rows = [score(case) for case in CASES]
kept = {str(t): [r['name'] for r in rows if r['kept'][str(t)]] for t in THRESHOLDS}
print(json.dumps({'synthetic': True, 'copy_mass': COPY, 'weights': WEIGHTS, 'rows': rows,
'kept_by_threshold': kept,
'example_augmented_text': augmented_text(CASES[0])}, indent=1))
| Case | L none | L call only | L plus | L minus | Reduction | Kept at τ_f = 1 |
|---|---|---|---|---|---|---|
| calculator-sum | 4.9517 | 6.7577 | 3.3510 | 4.9517 | 1.6008 | yes |
| qa-new-fact | 6.2673 | 8.0732 | 3.4860 | 6.2673 | 2.7813 | yes |
| input-leaks-answer | 6.1294 | 4.0322 | 4.3073 | 4.0322 | −0.2751 | no |
| wrong-tool-result | 6.2673 | 8.0732 | 8.0732 | 6.2673 | −1.8060 | no |
| tool-agrees-with-stale-text | 6.2673 | 8.0732 | 3.3999 | 6.2673 | 2.8674 | yes |
| already-predictable | 0.6224 | 2.4284 | 2.1667 | 0.6224 | −1.5443 | no |
For thresholds 0.25, 0.5 and 1.0 the same three calls survive: calculator-sum, qa-new-fact and tool-agrees-with-stale-text. At 2.0 only qa-new-fact and tool-agrees-with-stale-text remain. The finetuning text for the first case becomes the original tokens with the call and its result inserted before “42 points”.
Reading the rows:
input-leaks-answer is the reason for the minimum in L⁻. The call without its result already puts “Ivo” and “Prand” into the prefix, dropping the loss from 6.1294 to 4.0322. Adding the result “Yes” only spreads copy mass over one more token and raises the loss to 4.3073. The reduction is negative and the call is rejected. Comparing L⁺ only against the no-call loss would have credited the result with an improvement of 1.8221 that the input produced.
wrong-tool-result is rejected because the returned 1968 attracts copy mass while the actual 1970 receives only its base share. The loss with the result equals the call-only loss here, since neither prefix contains the target token.
tool-agrees-with-stale-text is kept at every threshold tested, with a larger reduction than the genuinely new fact. The filter rewards agreement with the corpus continuation; it has no access to whether that continuation is true. If the training text is stale, the model is taught to call a tool that repeats the stale value.
already-predictable is rejected because the base model was already right. In this toy, any prefix diverts mass from tokens not in it, so the call actually hurts. That penalty is an artifact of the crude copy model; the qualitative point, that there is little to gain where the model is already confident, does not depend on it.
What the filter cannot see
The toy model has no context sensitivity beyond token overlap, and its copy rule penalizes every prefix token that is not the target. Real language models use far richer context; the paper’s actual losses come from GPT-J. Only the logic of the filter carries over from this example, not the magnitudes.
A kept call improves prediction of the corpus text. It does not show that the tool’s output is correct, that the call is cheap, or that the final answer to a user’s question is right. The paper’s own measure of usefulness is downstream task performance and perplexity, reported in experimental sections we did not check.
The filter decides calls one position at a time. It does not train the model to chain calls, use one tool’s output as another’s input, or interact with a tool over several turns; those are the subjects of agent architectures and ReAct-style loops. Tools that cause side effects, such as booking or payment, raise permission and retry questions that a loss criterion cannot address; see the function-calling article.
Is this call worth keeping?
-
Why does Toolformer compare L⁺ with the minimum of the no-call loss and the call-without-result loss, rather than with the no-call loss alone?
Answer: A call contributes two things to the prefix: its input and its result. If the input alone already makes the continuation predictable, the improvement is not due to the tool’s answer. Taking the minimum credits the call only for the extra reduction that the result provides. In our input-leaks-answer case, comparison with the no-call loss alone would show a spurious improvement of 1.8221; with the minimum the reduction is −0.2751 and the call is rejected.
-
Reproduce L none and L plus for qa-new-fact by hand. The base probabilities of “Varnia” and ”.” are 0.002 and 0.9, the weights are 1 and 0.5, λ = 0.7, and the prefix with result has 12 distinct tokens of which “Varnia” is one and ”.” is not.
Answer: Without a prefix, L = −(ln 0.002 + 0.5 ln 0.9) = 6.2146 + 0.0527 = 6.2673. With the prefix, p(Varnia) = 0.7/12 + 0.3 × 0.002 = 0.05893 and p(.) = 0.3 × 0.9 = 0.27, so L = −(ln 0.05893 + 0.5 ln 0.27) = 2.8314 + 0.6547 = 3.4860. The reduction against L⁻ = 6.2673 is 2.7813, matching the program.
-
The tool-agrees-with-stale-text call has a larger reduction than qa-new-fact. Does a higher reduction mean the tool is more trustworthy? What would you add to the pipeline if stale training text is a concern?
Answer: No. The reduction measures how much the result helps predict the given text. Here it is larger only because the shorter question spreads copy mass over fewer tokens. If the text is stale, a tool repeating the stale value scores well. Possible additions include filtering or dating the training corpus, checking tool outputs against a trusted source for a sample of kept calls, and evaluating the finetuned model on questions whose current answer differs from older text.
-
An assistant can answer arithmetic questions itself with probability 0.2 of being right, or call a calculator that is right with probability 0.99; for general-knowledge questions the numbers are 0.6 and 0.85 using a search tool. If a call costs κ = 0.3 in accuracy units, which calls does the simple decision rule make? What changes if κ = 0.1?
Answer: Using this article’s teaching rule (not a rule from either paper): arithmetic: 0.99 − 0.2 = 0.79 > 0.3, so call. Knowledge: 0.85 − 0.6 = 0.25, below 0.3, so answer directly. With κ = 0.1 both gains exceed the cost and both call. These probabilities are assumed for the exercise, not measured; in practice they must be estimated per question type, and a tool’s accuracy depends on the arguments the model extracts.
Tool learning as data selection
Toolformer turns tool learning into a data-selection problem: generate many possible calls, execute them, and keep the ones that pass a loss criterion. Section 2 We read physical pages 2 to 4 of the 17-page arXiv v1, covering the approach, the filtering equations, the five tools and the start of the experimental setup; the downstream results, scaling analysis and appendix prompts were not checked.
MRKL approaches the same gap from the system side, with a router and separately built expert modules, and stresses that crossing from neural text to symbolic arguments is where the engineering effort goes. Sections 1 and 3 When reading later tool-use work, check which of these two decisions a method actually learns, where to call and what arguments to pass, and how it measures whether the call helped.
Make a prediction, then check
A call's input already contains the following tokens, and adding the result does not lower the loss further. What does Toolformer's filter do?
Learning objectives
- Recompute Toolformer's weighted loss and L+/L− filter and explain why the minimum over no call and call-only is used.
- Judge what a kept call does and does not show, and compare calling versus answering with a simple cost rule.
Prerequisites & connections
Explore related knowledge →References
- Toolformer: Language Models Can Teach Themselves to Use Tools — arXiv v1
Timo Schick; Jane Dwivedi-Yu; Roberto Dessì; Roberta Raileanu; Maria Lomeli; Luke Zettlemoyer; Nicola Cancedda; Thomas Scialom · 2023 - MRKL Systems: A modular, neuro-symbolic architecture that combines large language models, external knowledge sources and discrete reasoning — arXiv v1
Ehud Karpas; Omri Abend; Yonatan Belinkov; Barak Lenz; Opher Lieber; Nir Ratner; Yoav Shoham; et al. (AI21 Labs) · 2022
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Claude · 2026-12-02 · Independent AI check (Claude subagent, not the author); this is not a human or expert review. Ran example.py with CPython 3.12.4 and compared with example.stdout.txt (identical); confirmed both code blocks are byte-identical to example.py and all table values match. Hand-computed qa-new-fact (6.2673 and 3.4860 with 12 distinct prefix tokens), calculator-sum L plus (3.3510 with 8 distinct tokens), the 1.8221 spurious gain for input-leaks-answer, the 11-versus-12 distinct-token explanation in exercise 3 and the exercise 4 decisions. Rendered Toolformer arXiv v1 physical pages 2–4 at 130 dpi with pdftoppm and compared every display equation (e(c), e(c,r), p_i, I, L_i(z), L+, L−, keep rule) and footnotes 1–3 against the images: all consistent. Confirmed the five tools, two-decimal calculator, GPT-J and CCNet on page 4. Re-read MRKL v1 pages 1–5 by text extraction for the four-digit-addition and argument-extraction claims. Compared zh and en section by section. Did not read Toolformer results, perplexity section or appendix.
- Program output, code-block identity and table numbers verified; exercises 2–4 hand-checked.
- Toolformer equations and footnotes 1–3 checked against rendered page images; all consistent.
- The inference-time cost rule is now explicitly labelled as the article's teaching model, not attributed to Toolformer or MRKL.
- zh and en align section by section.
Source locations checked:
- Toolformer: Language Models Can Teach Themselves to Use Tools — arXiv v1 · arXiv v1 dated2023-02-09, 17 pages. Read page1 identity and full text extraction of physical pages2–4: call linearization, position sampling/threshold, execution, weighted loss and L+/L− filtering, prefix rather than insertion (footnote3), finetuning and inference pause, five tools, start of4.1 (GPT-J, CCNet, heuristics). Writer checked equations from text extraction; the independent checker re-checked every equation against rendered page images of physical pages2–4 (130 dpi) and found them consistent; results, perplexity section and appendix unread.
- MRKL Systems: A modular, neuro-symbolic architecture that combines large language models, external knowledge sources and discrete reasoning — arXiv v1 · arXiv v1 submitted2022-05-01, title page dated2022-05-03, 19 pages. Read text of physical pages1–5: abstract, Section1 limitations, modules/router design and six author-claimed benefits, Section2 Jurassic-X note, Section3 and start of3.1 (argument extraction). The design figure extracted only as a letter and was not viewed; rest of Section3 onward unread. Benefits are author claims, not measurements.
Related topics