Tool selection, execution and observation
medium 6 minTool use crosses a boundary from generated proposals to effects controlled by the host.
Write the order. Check the badge. File the receipt.
A clerk writes a proposed order, a gatekeeper checks the signer’s badge, and the cashier files the outcome.
Video lesson · Chapter 1 of 4
A refund written in pencil
Theory
Read or listen first. About 2 min.
What it is
Tool use crosses a boundary from generated proposals to effects controlled by the host. Selection, argument validation, authorization, execution and recording are distinct operations. A result is an observation only after the tool has actually returned it.
Why it exists
For writes, design the retry and review behavior before optimizing the prompt. A duplicate refund is a correctness error even when both requests select the right tool and contain individually valid arguments.
A model proposes a refund and the host checks it
Inside this chapter
Chapter sources- Function Calling (Tool Use)
- In function calling the model proposes a tool name and structured arguments. The application validates them, checks authorization, executes a permitted operation and returns the result. A generated call has no effect by itself. Persist the result of a write before retrying an interrupted conversation.
The model never executes anything; it emits a structured request that your code may or may not honour. That split is the whole safety story: validation, authorisation and execution all live in code you control. Persist write results as soon as they return, because if the conversation is interrupted and retried, the model may propose the same call again and you want to answer from the record.
Example. Return a refund proposal for a read-only fixture. The expected ledger balance stays unchanged even if all argument types validate.
Another example. Against a read-only fixture, the model proposes
refund(42, 24). The fixture returns a canned result and the ledger balance stays unchanged, which is exactly what the test asserts.A proposal becomes an effect only through the runtime
The model writes text that looks like a call. Only the runtime can make it happen. - What Is a Tool?
- A tool is an externally implemented operation exposed through a contract. Define its input, output, failure cases and side effects. A model can request “find order 42,” while the tool gateway independently checks whose order it is and returns a structured observation.
A tool is a promise from your code to the model about what an operation does. The schema covers inputs, but the contract also needs outputs, the distinct ways it can fail and what it changes in the world. Those failure cases drive the next decision: an empty result means ask or explain, a timeout means maybe retry, a denial means stop.
Example. A tool returns no matching order. Classify that as a successful empty lookup rather than a timeout or an authorization failure.
JSON{ "name": "find_order", "description": "Look up one order owned by the signed-in customer.", "input_schema": { "type": "object", "properties": { "order_id": { "type": "string" } }, "required": ["order_id"] }, "returns": "order | not_found", "errors": ["timeout", "access_denied"], "side_effects": "none"}A tool contract: inputs, outputs, failure cases and side effects. not_foundis a successful empty lookup, not an error. - Tool Selection & Tool Routing
- Route among tools using clear names, descriptions and schemas. Similar tools become easier to confuse as the catalog grows. Evaluate both incorrect selections and failures to invoke a needed tool. A router may also abstain or request clarification when required arguments are missing.
Selection quality depends on names, descriptions and schemas being distinct. As the catalogue grows, near-duplicates such as quote and issue get confused more often, so evaluate both kinds of miss: calling the wrong tool and failing to call a needed one. Let the model abstain or ask when a required argument is missing rather than inventing one.
Example. Offer both quote_refund and issue_refund. A user asking “How much?” should select the quote and never modify the ledger.
Another example. A help-desk agent with
search_kb,search_ticketsandcreate_ticketshould search before creating. An eval set with 50 "is there a known issue" questions catches it creating duplicate tickets.Quote or issue: the question decides
A wrong selection here is not cosmetic: picking issue_refundwould move money. - Safe Tool Execution
- Validate tool arguments, authorize the operation for the current principal and constrain its effects. For consequential writes, use scoped approval and idempotency. Treat model output as a proposal. Permissions must be enforced even when the generated arguments match the schema perfectly.
Treat every proposed call as untrusted input from a user who can be persuaded. Schema validation catches malformed arguments, but a perfectly typed request for someone else's order is still forbidden. For writes, bind approval to the exact arguments and attach an idempotency key so retries cannot double the effect.
Example. Approve a write for one order ID, then substitute another ID in a fixture. Authorization must bind to the exact proposed operation.
Gates between proposal and effect - 1Proposalissue_refund(42, 24 USD)
- 2Schema validationtypes and ranges
- 3Authorise principalorder 42 is theirs
- 4Approval bound to argsreviewer saw 42 and 24
- 5Execute with keyoperation key 19/42
- 6Record resultbefore replying
Passing the schema is the first gate, not the last. Swapping order 42 for 43 must fail at authorisation.
- Observability from Tools
- Trace each tool call with a run ID, tool version, duration, outcome and safe result summary. Distinguish validation rejection, access denial, timeout and successful empty results. These outcomes should produce different next decisions. Redact sensitive arguments before they enter telemetry.
Record outcomes as a small fixed set: validation_rejected, access_denied, timeout, success_empty and success. Each calls for a different next step, and lumping them into "error" makes both the agent and your dashboards worse. Split latency into queue and service time, and redact sensitive arguments before they reach logs.
Example. A tool contributes 200 ms of service time after 800 ms in a queue. Separate these spans before tuning the underlying lookup.
One traced tool call
Field Value Why it matters run_id / tool version run-7f3 / find_order v3 joins the call to its run and code queue wait 800 ms time before the tool started service time 200 ms time the tool actually worked outcome success_empty differs from timeout or denied result summary 0 orders, ID redacted useful without leaking data Illustrative numbers from the example. Tuning the lookup would not touch the 800 ms queue.
How it works
Step through the idea, or press Play.
Tool proposal. refund(order 42, 24 USD)
Understand it
Worked example
A model proposes a refund and the host checks it
- 1
refund(order 42, 24 USD)
The proposal identifies a tool and arguments. It has not issued a refund, even if the JSON is syntactically perfect.
- 2
Schema valid · approval missing
The gateway checks ownership, amount limits and required approval. Keep this decision outside the model.
- 3
No payment changed
Return a typed approval-required result. The next model response can ask for review without claiming the refund already happened.
Follow the handoffs
// model proposal{ "name": "refund", "arguments": { "order_id": "42", "amount": 24, "currency": "USD" } }// typed result returned by the host{ "status": "approval_required", "order_id": "42", "amount": 24, "ledger_changed": false }The execution gate for the refund
Summary
The whole topic in one minute.
Checking a scoped idempotency record prevents duplicated effects when a request is retried after an ambiguous response.
For writes, design the retry and review behavior before optimizing the prompt. A duplicate refund is a correctness error even when both requests select the right tool and contain individually valid arguments.