advanced32 min studyLesson 67 in Engineering

Tool use and structured generation

Separate grammar-constrained output, schema validation, semantic checks, authorization, and side-effect execution.

On this page

What you’ll understand

  • Explain how grammar constraints restrict a token distribution without proving meaning.
  • Design a validated tool-call boundary with explicit permissions and failure states.
  • Measure format validity, executable correctness, and task success separately.

A language model can propose a structured operation such as a search query or a calendar update. The proposal is data produced by a probabilistic program, not permission to execute arbitrary work. A reliable tool interface turns that proposal into a series of explicit checks and bounded actions. Structured generation helps the output meet a representation contract, while application code remains responsible for meaning, authorization, side effects, and whether the requested task was actually accomplished.

A grammar controls representation

A decoder can restrict each next-token distribution to tokens allowed by a grammar and the already generated prefix. This can make malformed outputs less likely or prevent them within the supported grammar, but compatibility depends on the implementation and supported schema features. JSON syntax is only the first layer. A syntactically valid object can omit a necessary field, contain an impossible date, or name a resource that does not exist. Keep each kind of validation visible rather than calling every failure a formatting issue.

JSON Schema can describe types, required fields, enumerated choices, and other structural constraints. Merely listing a property does not require its presence; the schema must declare that requirement. Reject or explicitly handle unknown fields according to the interface contract. Cross-field business rules may need ordinary code, such as ensuring an end time follows a start time. A schema-valid amount can still exceed an account's limit, and a schema-valid identifier can still refer to another user's private resource.

p′(t∣s)=p(t∣s)1{t∈A(s)}∑u∈A(s)p(u∣s)p'(t\mid s)=\frac{p(t\mid s)\mathbf{1}\{t\in A(s)\}}{\sum_{u\in A(s)}p(u\mid s)}
A(s) is the set of tokens permitted after prefix s, and the denominator must be positive. Grammar masking changes the sampling distribution; it does not establish factual or business validity of the completed object.↔ Scroll wide equations horizontally.

Execution needs an application-owned trust boundary

Expose a narrow tool registry with names, argument types, bounded result sizes, and explicit error responses. Parse the model output into typed application data, validate it, and perform authorization using trusted user and workload identity. Do not let a model-supplied user identifier determine whose permissions apply. Retrieved text and tool responses can contain adversarial instructions; carry them as untrusted observations rather than allowing them to redefine the application's available capabilities or permission checks.

Read-only search and a payment operation have different failure consequences. For side effects, use the confirmation or approval policy required by the application and scope each operation to a resource and amount. Assign idempotency keys and persist execution state so a network timeout does not cause an unbounded duplicate action. A timeout can mean the result is unknown, not that the action failed. Reconcile with the authoritative service before retrying an operation that may already have committed.

Measure the complete operation, not just the JSON

Toolformer studies learning when and how to use tools, but a learned calling policy does not replace an application's correctness boundary. Evaluate argument accuracy, authorized execution, task completion, and recovery from unavailable tools. A tool invocation can return HTTP success while producing irrelevant search results. Conversely, a deliberate refusal to perform an unauthorized request can be a successful system outcome. Define expected behavior for each case before assigning scores.

Log a trace with proposal, validation result, authorized operation, execution identifier, result summary, and final response. Redact secrets and private content according to the logging policy. Give errors a bounded, machine-readable form so the model can correct a field without seeing a stack trace or internal credentials. Limit attempts, tokens, elapsed time, and tool response size. When the budget is exhausted, expose a clear unresolved state rather than fabricating a successful result from a partially completed workflow.

P(success)=P(F)P(V∣F)P(A∣F,V)P(S∣F,V,A)P(\mathrm{success})=P(F)P(V\mid F)P(A\mid F,V)P(S\mid F,V,A)
F is acceptable format, V valid semantics, A authorized successful execution, and S task completion. This is a conditional factorization of staged success, not an independence assumption or a claim that these events are sufficient for every application.↔ Scroll wide equations horizontally.

Locate failures in a tool-call funnel

On 100 test tasks, 95 proposals parse, 90 pass semantic checks, 80 execute successfully with authorization, and 72 complete the task. Each count is a subset of the preceding count.

  1. Format validity is 95/100 = 95%. Semantic validity conditional on parsing is 90/95, approximately 94.74%, rather than 90% of parsed proposals.

  2. Execution success conditional on semantic validity is 80/90, approximately 88.89%. Task success conditional on execution is 72/80 = 90%.

  3. Multiply 0.95 × (90/95) × (80/90) × (72/80) to obtain 0.72. Overall task success is 72%, even though format validity was 95%.

The result

The largest remaining loss is not established by the format score. Inspect each failed transition before deciding whether to improve decoding, argument understanding, execution, or task planning.

Explore the model

Interactive lab

Interactive lab · reliability

Availability is only one gate

Vary replica count and unavailable replicas to inspect remaining nodes and the majority threshold floor(n/2)+1. This is a quorum-availability diagram, not a tool executor, permission checker, or proof of transaction correctness.

Availability is only one gateA replica count and a majority threshold, without a consensus protocol. Playback highlights fixed replica states. Having a majority alone does not establish linearizability, durability or failure independence. Current readings: Available replicas: 4 of 5; Majority needed: 3; Majority available?: Yes. All parameters are adjustable with the labeled controls below.Majority available · need 3 of 5Playback highlights fixed statesR1 · upR2 · upR3 · upR4 · upR5 · downCyan mark: majority threshold
AvailableUnavailableMajority threshold
Available replicas
4 of 5
Majority needed
3
Majority available?
Yes
t = 0 s

A replica count and a majority threshold, without a consensus protocol. Playback highlights fixed replica states. Having a majority alone does not establish linearizability, durability or failure independence. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forAn available component can still receive an invalid or unauthorized operation; availability and application correctness need distinct checks.

Check your understanding

A generated transfer request passes its JSON Schema. What should the application conclude?

Try it yourself

A booking tool times out after receiving a request with idempotency key K. Why is immediately issuing the same booking under a fresh key unsafe, and what should the client do?

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

A timeout describes the client's observation, not necessarily the server's commit state.

Compare with the solution

The first request may already have committed, so a fresh key can create a second booking. Query the authoritative operation or booking state using K when supported, or retry according to the service's documented idempotency contract with the same logical key. Keep the outcome pending until reconciled; do not equate an unknown response with a failed side effect.

Take it with you

  • Grammar and schema constraints describe representation, not truth or permission.
  • Applications own authorization, idempotency, and side-effect execution.
  • Evaluate staged correctness and final task completion with bounded recovery.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.