16.1 Function Calling & Tool Use
A language model can propose a calculation, database lookup, or file edit. A tool-using application can actually perform it and return observable evidence. Function calling structures that proposal; the application’s executor decides whether it is valid and authorized. Fluent intent, valid JSON, and permission to act are three separate properties.
OpenAI’s 2023 API release is one influential structured-function interface [1]. It is a historical example, not a claim that every current provider uses the same message format. Model revisions can change tool protocols and reasoning requirements; see the dated contracts in Chapter 17.6.
1. The Tool Loop
- Render the user’s request and tool definitions using the serving model’s native protocol.
- Receive an assistant call proposal with a tool name, arguments, and call identifier.
- Validate its schema, authorization, destination, budget, and preconditions.
- Execute through a bounded tool adapter; record its actual effects.
- Return a correlated result or typed error through the native tool-result format.
- Let the policy revise its plan or answer; verify the final outcome independently.
A call proposal is not executable code supplied by the model. Avoid evaluating arbitrary strings when a narrow typed adapter can implement the requested action. Parallel calls are safe only when their state dependencies and side effects permit it; repeated calls need idempotency or reconciliation.
Source: AI-generated illustration of the proposal–execution–result loop. Authorization is an executor responsibility.
2. Schema Validity and Action Authorization
Schema validation checks types, required fields, enums, bounds, and additional-property rules. For an inclusive numeric interval, the rule is simply
where and are declared minimum and maximum, and is the indicator. Exclusive bounds require strict inequalities. An enum check is for allowed set . Use the actual JSON Schema validator’s semantics: Python booleans, integer coercion, nulls, and stringified numbers are common mismatches with hand-written checks.
A schema-valid transfer can still use the wrong account, exceed the user’s authorized amount, or reach an unapproved endpoint. These are policy and precondition checks. Enforce them with trusted state at the moment of execution, not only when constructing the prompt. Unknown tools and unexpected argument fields should fail closed according to the declared contract.
Return actionable, bounded errors without exposing credentials or privileged state. Retrying a malformed read request differs from retrying a payment with an unknown completion status. Query transaction state and use idempotency keys before repeating a write.
3. Learning the Protocol
Tool-use SFT represents assistant proposals, external results, and subsequent assistant responses as a native multi-turn conversation. Do not invent <call> delimiters or copy another tokenizer’s role tokens. Toolformer supplies an earlier self-supervised route: retain candidate calls when the returned information improves prediction of subsequent text [2]. That filtering criterion is not an authorization policy or evidence that a tool-using agent is safe.
For training, pin input policy/adapter, tokenizer/template, tool schemas, provenance and immutable manifests; group related conversations before splits and quarantine evaluation prompts and siblings. Supervise intended assistant-generated spans, including call syntax and responses. Exclude user prompts, externally supplied tool results, padding, and post-terminal positions. Verify BOS/EOS, add_generation_prompt, truncation, response caps, and packing isolation; variable-length batch reductions must use explicit valid-token counts.
LoRA can lower trainable-state cost but does not guarantee preservation of base reasoning or safety. Declare target modules, rank/scaling, optimizer schedule, sequence length, precision/sharding, and memory for parameters, gradients, optimizer, activations, temporary buffers, collectives, checkpoints, and evaluation. The complete training/checkpoint/release contracts are in Chapter 9.1 and Chapter 15.5; tool capability alone is not a reason to bypass them.
4. Tool Outputs Are Untrusted Evidence
A retrieved page, email, repository file, or tool error can contain instructions. Treat that content as evidence with provenance, not permission to change the agent’s task or privileges. Escaping text or requiring JSON does not remove indirect prompt injection. The executor must enforce action boundaries independently.
Keep secrets out of model context where possible. Scope tool credentials to allowed resources, bound network destinations and redirects, isolate code execution, and require the authorization appropriate to the action. A failed request must not grant permission to use a new destination or tool. Chapter 16.6 develops recovery and recent evidence about alternate paths.
5. Evaluate the Complete Workflow
Unit-test schema and policy enforcement with valid, malformed, out-of-range, ambiguous, and adversarial calls. Then test end-to-end tasks with tool errors, delayed results, duplicate calls, stale state, and malicious outputs. Distinguish correct proposals, attempted unauthorized actions, executor blocks, actual effects, and verified task success.
Track call/argument validity, policy violations, recovery rate, repeated-run reliability, tokens, latency, cost, and base-capability/safety slices. Training additionally needs token-normalized loss, nonfinite/overflow counts, gradient/activation norms, throughput, MFU, data wait, and collective/straggler telemetry with reconstructable batch IDs. Pin the model/template/tool/safety/code bundle and checkpoint the exact data and conversation cursor.
Predeclare abort thresholds, observation window, owner, and last-known-good bundle. A rollback cannot undo an already completed external transaction; it needs reconciliation or compensation. Use paired offline evidence and bounded canaries, and rehearse rollback before widening access. The useful outcome is a correctly completed authorized task, not merely syntactically valid JSON.
Quizzes
Quiz 1: Why is a valid JSON tool call not proof of a safe action?
It may violate authorization, destination, resource, or state preconditions while satisfying every schema field. The executor needs independent policy checks.
Quiz 2: Does an inclusive range allow its endpoints?
Yes. The rule is a ≤ x ≤ b. A product of sign functions would incorrectly reject equality; exclusive bounds require a different contract.
Quiz 3: Which spans should tool-use SFT normally exclude from policy loss?
User prompts, external tool results, padding, and post-terminal positions. Preserve explicit masks for assistant proposals and intended assistant responses using the native template.
Quiz 4: Why must a timed-out write be reconciled before retry?
Timeout does not prove the write failed. Repeating it can duplicate an effect; inspect transaction state and use an idempotency contract.
Quiz 5: What should be measured when malicious tool content requests a new privilege?
The model’s attempted action, the executor’s policy decision, and the actual effect. A correct final answer does not erase an unauthorized attempt.
References
- OpenAI. (2023). Function Calling and Other API Updates. OpenAI.
- Schick, T., et al. (2023). Toolformer: Language Models Can Teach Themselves to Use Tools. arXiv:2302.04761.