8 Applications 3 / 8
  1. In this chapter
  2. Your first agent
  3. Prompt Engineering
  4. Structured Outputs and Function Calling
  5. RAG in Practice
  6. Agents and Tool Calling in Practice
  7. Agent context and memory
  8. Agent Evaluation
  9. MCP and the Tool Ecosystem
All chapters →

Chapter 8 · Applications 8.3

Structured Outputs and Function Calling: From JSON Mode to Constrained Decoding

A program can use model output reliably through prompt conventions, JSON mode, JSON Schema constrained decoding, and validate-and-retry. This page explains how token masks guarantee a format, how function-call messages flow, and why format limits can hurt reasoning.

Intermediate 26 min read Updated Companion code ↓

After this page you will be able to

  • Say what prompt conventions, JSON mode, constrained decoding and validate-and-retry each can and cannot guarantee.
  • Explain how constrained decoding enforces a format with a vocabulary mask, and build a working constrainer step by step with the standard library.
  • Write a JSON Schema that follows the strict-mode rules, and know why a format constraint can hurt reasoning.
  • Write the message round trip of a function call and build a minimal working call loop.
On this page
  1. Four levels of control
  2. Constrained decoding
  3. Only legal tokens get through at every step
  4. How rules become an allowed set
  5. Try it: watch the mask step by step
  6. A few lines of standard-library Python
  7. Step-by-step masking changes the distribution
  8. Writing the schema: strict-mode rules and design
  9. Generate the schema from types, and mind a few traps
  10. A constraint only covers format
  11. Do format constraints hurt reasoning?
  12. Function calling
  13. The message shapes of the two APIs
  14. A minimal tool-call loop that runs
  15. A practical checklist
  16. Apply two checks to synthetic structured data
  17. Summary and exercises
  18. Exercises
  19. Further reading
  20. FAQ

To make a program use a model’s output reliably, writing “please output JSON” in the prompt is nowhere near enough. The stronger guarantee comes from decoding: at every token, mask out the tokens that would break the format. This is constrained decoding. Function calling adds a message protocol on top of it: the model only writes a function name and JSON arguments, your code runs the function, and the result goes back to the model. Keep one boundary in mind: a legal format is not correct content, and a strict format can hurt reasoning, so validation, retries and evaluation are all still needed.

Four levels of control

The four levels guarantee different things, and they can be combined.

ApproachHowGuaranteesDoes not guarantee
Prompt conventionState the format in the prompt, add one or two examplesOnly a higher probability, no guaranteeUnbalanced brackets, extra chatter, missing fields, wrong types
JSON modeTurn on the API’s JSON switch (json_object at OpenAI)The output is valid JSONThat it matches your schema
Schema constraintProvide a JSON Schema and let only legal tokens through during decoding (OpenAI Structured Outputs and strict function calling, Anthropic strict tools)Valid JSON that matches the supported subset of the schemaThat the values are right; no legal output if it is truncated or refused
Validate and retryParse, check against the schema and business rules, and on failure send the error back and let the model retryCatches and repairs syntax and semantic errorsAn extra call, and no promise that a retry succeeds

OpenAI’s documentation states the difference between the first two levels clearly: both ensure valid JSON, only Structured Outputs ensures schema adherence, and it recommends Structured Outputs over JSON mode whenever possible. JSON mode also has a trap: the conversation must explicitly ask for JSON, otherwise the model may produce an unending stream of whitespace until it reaches the token limit (the API throws an error if the word “JSON” appears nowhere in the context).

The order of preference is: use a schema constraint when you can; fall back to JSON mode when the model or API does not support it, or when your format goes beyond the supported subset of JSON Schema; and keep validation and retries at every level, because, as the rest of this page shows, a constraint only covers format.

Constrained decoding

At each step the language model outputs logits over the whole vocabulary, and softmax turns them into probabilities from which one token is sampled. Constrained decoding adds one thing: from the target format and the text written so far, it computes the set AtA_t of tokens allowed at this step, sets the logits outside the set to −∞-\infty, and then runs softmax and sampling. The renormalized probability is

p′(v)={p(v)/Z,v∈At,0,v∉At,Z=∑u∈Atp(u).p'(v)=\begin{cases} p(v)/Z, & v\in A_t,\\ 0, & v\notin A_t, \end{cases} \qquad Z=\sum_{u\in A_t}p(u).

Every step can only sample from AtA_t, so the output is always a legal prefix of the target format and cannot go wrong half-way. The real engineering difficulty is computing AtA_t quickly.

One step of constrained decoding: look up the allowed tokens, mask, sample, update the state The top row is offline: a JSON Schema or regex is compiled into a character-level automaton and indexed against the vocabulary as an index sigma that records which tokens each state allows. The bottom row is online: the language model outputs logits, every logit outside the allowed set found in sigma for the current state is set to minus infinity, softmax and sampling follow, and the chosen token updates the state for the next lookup. Constrained decoding: compile once offline, look up at every step Offline: once per schema JSON Schema / regex the format you ask for Character automaton DFA for regex, PDA for nesting Index σ state → allowed tokens Online: at every generated token Language model outputs V logits Mask logit = −∞ outside σ(q) Softmax, sample only legal tokens drawn Update state q ← σ(q, chosen token) look up σ(q) next step looks up the new q
The two phases of constrained decoding: offline, the format is compiled into an automaton and indexed; online, every step is a lookup, a mask, a sample and a state update.

How rules become an allowed set

A regular expression or a fixed template compiles into a character-level finite-state machine (DFA). A token is a string: starting from state qq, if the machine can consume its characters one by one (every character has an outgoing edge), the token is allowed, and it leaves the machine in a new state.

A token is not a character. One token can write several elements of the grammar at once; for example ": " writes the closing quote of the key, the colon, the space and the opening quote of the value, so the automaton has to walk the whole token and not just its first character.

Precomputing “which tokens each state allows and where each one leads” into an index σ\sigma is the approach of Outlines (Willard and Louf, 2023). The index depends only on the grammar and the vocabulary, so it is built once; at each step you look up the current state, which costs O(1) on average. The naive method re-checks the whole vocabulary at every step, and a vocabulary can be as large as 128k tokens (Llama 3.1, as reported in the XGrammar paper).

JSON nests without limit, and matching brackets needs a stack to remember them. That is beyond regular expressions and DFAs, so the grammar becomes a context-free grammar (CFG) run on a pushdown automaton, and the stack contents have too many combinations to precompute. XGrammar (Dong et al., 2024) splits the vocabulary into two classes: tokens that do not depend on the stack are checked and cached during preprocessing, and tokens that do depend on it are checked at run time, with a persistent stack and grammar computation overlapped with GPU execution. The paper reports that for the Llama-3.1 vocabulary under a JSON grammar, fewer than 1% of tokens depend on the stack (1134 out of 128k), a speedup of up to 100x over existing solutions, and near-zero overhead for structured generation when combined with an inference engine.

The JSON Schema you send through an API has to be processed into this kind of structure too. Anthropic’s documentation says the input_schema of a strict tool is compiled into a grammar and the compiled result is cached for up to 24 hours since last use; OpenAI’s documentation likewise warns that the first request with any schema has extra processing latency, and later requests with the same schema do not. So do not build a different schema for every request; keep it stable.

Try it: watch the mask step by step

In the widget below the vocabulary has only 30 tokens, and the target format is {"name": "<lowercase letters>+", "age": <digits>+}. The language model’s scores are hand-set illustrative values, not output of a real model.

Things to try:

  1. Turn “Constrained decoding” on and click “Generate next token” repeatedly. Watch which tokens get struck out at each step and how the remaining probability is renormalized.
  2. Turn the constraint off and generate a few times. See what the usual deviations are: opening with a pleasantry, writing a number as an English word, adding a code fence after the }.
  3. Click “Run 1000 each” at different temperatures and compare the validity rates. The higher the temperature, the more probability the model gives to illegal tokens, and the faster the unconstrained rate falls.
  4. Expand “Index σ” to see which tokens each state can take.

A few lines of standard-library Python

The same mechanism fits in plain standard-library Python. The target format and the vocabulary are the same as in the widget; the “language model” is replaced by purely random logits, so whether an output is legal depends entirely on the mask.

import json
import math
import random
from collections import Counter

# Target format: {"name": "<lowercase>+", "age": <digits>+}, built from literal text + character classes
SEGMENTS = [
    ("lit", '{"name": "'),
    ("cls", "abcdefghijklmnopqrstuvwxyz"),
    ("lit", '", "age": '),
    ("cls", "0123456789"),
    ("lit", "}"),
]


def build_dfa(segments):
    """Return (edges, accept): edges[state][char] = next state; a missing edge means illegal."""
    edges, cur = [{}], 0
    for kind, spec in segments:
        if kind == "lit":
            for ch in spec:
                edges.append({})
                edges[cur][ch] = len(edges) - 1
                cur = len(edges) - 1
        else:  # character class, at least once: after entering it we stay in a self-loop state
            edges.append({})
            loop = len(edges) - 1
            for ch in spec:
                edges[cur][ch] = loop
                edges[loop][ch] = loop
            cur = loop
    return edges, cur


VOCAB = ['{', '{"', '"', 'name', 'age', '":', '": ', '": "', '",', '", "', ' ', '}',
         'al', 'ice', 'alice', 'bob', 'Bob', 'thirty', '30', '3', '7', '42',
         'Sure', 'Here', '\n', '```', 'json', ',', ':', '<eos>']


def build_index(edges, accept, vocab):
    """index[state] = {token_id: state after consuming the token}; only tokens that fit entirely are kept."""
    index = []
    for state in range(len(edges)):
        row = {}
        for i, tok in enumerate(vocab):
            if tok == "<eos>":  # end-of-sequence is only allowed once the format is complete
                if state == accept:
                    row[i] = state
                continue
            s = state
            for ch in tok:  # a token has several characters: walk all of them
                s = edges[s].get(ch)
                if s is None:
                    break
            if s is not None:
                row[i] = s
        index.append(row)
    return index


edges, accept = build_dfa(SEGMENTS)
index = build_index(edges, accept, VOCAB)
print("DFA states:", len(edges), "vocabulary size:", len(VOCAB), "index entries:", sum(len(r) for r in index))
for state in (0, 1, 10, 21, 22, 23):
    print(f"state {state:2d} allows:", [VOCAB[i] for i in index[state]])


def sample(logits, allowed, rng):
    """Treat logits of disallowed tokens as -inf, then softmax and sample."""
    masked = [z if i in allowed else -math.inf for i, z in enumerate(logits)]
    top = max(masked)
    weights = [math.exp(z - top) for z in masked]
    return rng.choices(range(len(logits)), weights=weights)[0]


def generate(rng, constrained, max_steps):
    state, out = 0, []
    for _ in range(max_steps):
        logits = [rng.gauss(0, 2) for _ in VOCAB]  # a "language model" that knows nothing: random logits
        allowed = index[state].keys() if constrained else range(len(VOCAB))
        token = sample(logits, allowed, rng)
        if constrained:
            state = index[state][token]
        if VOCAB[token] == "<eos>":
            break
        out.append(VOCAB[token])
    return "".join(out)


def judge(text):
    """complete / prefix (legal but unfinished) / invalid."""
    s = 0
    for ch in text:
        s = edges[s].get(ch)
        if s is None:
            return "invalid"
    if s == accept:
        json.loads(text)  # a real JSON parser can read it too
        return "complete"
    return "prefix"


rng = random.Random(7)
for _ in range(3):
    print(repr(generate(rng, True, 40)))

for constrained, budget in [(False, 40), (True, 40), (True, 80)]:
    rng = random.Random(0)
    tally = Counter(judge(generate(rng, constrained, budget)) for _ in range(2000))
    print(f"constrained={constrained!s:5} up to {budget} steps:", dict(tally))
DFA states: 24 vocabulary size: 30 index entries: 49
state  0 allows: ['{', '{"']
state  1 allows: ['"']
state 10 allows: ['name', 'age', 'al', 'ice', 'alice', 'bob', 'thirty', 'json']
state 21 allows: ['30', '3', '7', '42']
state 22 allows: ['}', '30', '3', '7', '42']
state 23 allows: ['<eos>']
'{"name": "agealage", "age": 3074273730423374233}'
'{"name": "alicealicealicebobicename", "age": 42}'
'{"name": "alicenameicebob", "age": 73307}'
constrained=False up to 40 steps: {'invalid': 1928, 'prefix': 72}
constrained=True  up to 40 steps: {'complete': 1987, 'prefix': 13}
constrained=True  up to 80 steps: {'complete': 2000}

Three things to notice:

  • 24 states times 30 tokens make 720 (state, token) pairs, and only 49 of them can be walked. Each step samples only among the few tokens in index[state].
  • For a random “model” that knows nothing, without the constraint none of the 2000 runs produced a complete legal output: 1928 left the format part-way, and the other 72 emitted the end token before finishing (68 of them at the very first step), leaving a legal prefix. With the constraint, all 2000 are legal prefixes, and 1987 are complete.
  • 13 constrained runs are still incomplete because they used up the 40-step limit: the random “model” keeps wandering among letters and digits and rarely writes the end token. With the limit raised to 80, all 2000 are complete. Constrained decoding keeps every step legal; it does not promise to finish. In a real API this is max_tokens truncation, which comes up again below.

Step-by-step masking changes the distribution

Step-by-step masking looks only at the current step and never ahead, so the distribution it produces differs from “sample among all legal outputs in proportion to the model’s own probabilities”. Take the smallest example: at the first step the model writes A or B with probability 0.5 each. After A the only legal token is x, to which the model gives just 0.1 (the other 0.9 goes to illegal tokens); after B the only legal token is y, to which the model gives 0.9.

Sampling methodProbability of AxProbability of By
Normalize over the two legal sequences by model probability10%90%
Step-by-step masking50%50%

The model probabilities of the two legal sequences are 0.5×0.1=0.050.5\times0.1=0.05 and 0.5×0.9=0.450.5\times0.9=0.45, which normalize to 10% and 90%. With step-by-step masking, neither A nor B is masked at the first step, so each gets 50%; at the second step only one legal token is left and it is renormalized to 1, giving 50% against 50%.

The model “feels” that after A there is almost no legal continuation, and the mask drags it there anyway. Park et al. (2024) describe this as constrained decoding distorting the model’s distribution, and propose the ASAp algorithm to align sampling with the model’s distribution conditioned on the grammar. The practical lesson: write prompts and field descriptions so the model already tends to produce legal content, and treat the mask as a last safeguard; being forced into a low-probability branch can lower content quality.

Writing the schema: strict-mode rules and design

A schema constraint supports only a subset of JSON Schema, and providers differ in their limits. Below are the requirements of strict: true in OpenAI’s documentation as consulted in November 2026; check the official documentation for the exact limits. Anthropic’s strict tools also support only a subset, with the limits documented there.

RuleDetails
additionalPropertiesEvery object must set additionalProperties: false; keys that are not in the schema are not allowed
requiredEvery field in properties must be listed in required. To make a field optional, type it as a union with null, for example ["string", "null"]
RootMust be an object, not anyOf (a Zod discriminated union produces a top-level anyOf, so wrap it in an object)
Supported typesString, number, integer, boolean, object, array, enum and anyOf; $defs and recursive references are supported
Unsupported keywordsallOf, not, dependentRequired, dependentSchemas, if, then, else
Size limitsAt most 5000 object properties and 10 levels of nesting; property names, enum values and similar strings total at most 120,000 characters
Key orderOutput is generated in the order of the keys in the schema
When a rule is brokenThe request fails outright, so you find out in testing

Generate the schema from types, and mind a few traps

A hand-written JSON Schema tends to drift away from the types in your code, so it is safer to generate the schema from the types. The code below uses Pydantic (pip install pydantic) and adds a minimal validate-and-retry loop, with a script standing in for a real model:

import json
from typing import Literal

from pydantic import BaseModel, ConfigDict, ValidationError


class Triage(BaseModel):
    model_config = ConfigDict(extra="forbid")  # emits additionalProperties: false in the schema
    reason: str  # field order is the order of properties in the schema: reason first, then the verdict
    priority: Literal["low", "medium", "high"]
    requires_human: bool


schema = Triage.model_json_schema()
print(json.dumps(schema))
print("field order:", list(schema["properties"]), "required:", schema["required"])


class Loose(BaseModel):  # a common trap: the default schema does not meet strict-mode rules
    reason: str
    note: str | None = None


loose = Loose.model_json_schema()
print("additionalProperties without extra='forbid'?", "additionalProperties" in loose)
print("is a field with a default in required?", "note" in loose["required"])


class Fixed(BaseModel):  # the fix: optional means a union with null, and no default value
    model_config = ConfigDict(extra="forbid")
    reason: str
    note: str | None


fixed = Fixed.model_json_schema()
print("after the fix: additionalProperties =", fixed["additionalProperties"], "| is note in required?", "note" in fixed["required"])

# A script stands in for the model: chatter first (not valid JSON), then valid JSON that breaks the schema, then a correct reply
replies = iter(
    [
        'Sure, here is the result: {"priority": "high", "requires_human": true}',
        '{"priority": "urgent", "requires_human": true}',
        '{"reason": "Charged but the order shows unpaid; needs payment reconciliation", "priority": "high", "requires_human": true}',
    ]
)


def fake_model(messages):
    return next(replies)


def ask(question, max_retries=3):
    messages = [{"role": "user", "content": question}]
    for attempt in range(max_retries + 1):
        text = fake_model(messages)
        try:
            return Triage.model_validate_json(text)
        except ValidationError as e:
            errors = [f'{".".join(map(str, err["loc"])) or "<whole>"}: {err["msg"]}' for err in e.errors()]
            print(f"attempt {attempt + 1} invalid:", errors)
            messages += [
                {"role": "assistant", "content": text},
                {"role": "user", "content": "The output failed validation: " + "; ".join(errors) + ". Return only JSON that matches the schema."},
            ]
    raise RuntimeError("Still invalid after retries: escalate to a human or degrade")


print(ask("I was charged but the order shows unpaid. What should we do?"))
{"additionalProperties": false, "properties": {"reason": {"title": "Reason", "type": "string"}, "priority": {"enum": ["low", "medium", "high"], "title": "Priority", "type": "string"}, "requires_human": {"title": "Requires Human", "type": "boolean"}}, "required": ["reason", "priority", "requires_human"], "title": "Triage", "type": "object"}
field order: ['reason', 'priority', 'requires_human'] required: ['reason', 'priority', 'requires_human']
additionalProperties without extra='forbid'? False
is a field with a default in required? False
after the fix: additionalProperties = False | is note in required? True
attempt 1 invalid: ['<whole>: Invalid JSON: expected value at line 1 column 1']
attempt 2 invalid: ['reason: Field required', "priority: Input should be 'low', 'medium' or 'high'"]
reason='Charged but the order shows unpaid; needs payment reconciliation' priority='high' requires_human=True

What the output shows:

  • Only extra="forbid" produces additionalProperties: false. Without it the generated schema has no such key at all, which does not meet strict-mode requirements.
  • A field with a default value does not enter required, which also breaks strict mode. Write an optional field as str | None with no default (see Fixed): it is then both a union with null and listed in required.
  • Field order is the order of properties in the schema, which is the order in which the model generates. Putting reason before priority makes the model write the rationale before the verdict; the next section explains why that matters.
  • The key to the retry loop is sending the specific error back to the model: the first reply is not valid JSON, the second is valid JSON with a missing field and a value outside the enum. Cap the number of retries, and degrade or hand off to a human when the cap is reached.

A few schema design habits, from the OpenAI and Anthropic documentation and the experiments above:

  1. Name keys clearly and give every field a description; prefer an enum to free text.
  2. Do not make the model fill values you already know. If the order id is already in your code, do not make order_id a parameter for the model to copy.
  3. Leave an exit for irrelevant input. The model tries hard to satisfy the schema and may invent fields when the input has nothing to do with the task, so allow null, unknown or a dedicated error field.
  4. Keep the schema stable, and compare structures on an evaluation set instead of tuning by feel.

A constraint only covers format

With a schema constraint on, three kinds of problems are still yours to handle:

ProblemWhat it looks likeWhat to do
Wrong contentThe format is legal and the value is wrong: any legal name and age in the toy above passesWrite clear instructions, add examples, split the task; validate ranges and consistency with business rules; measure field-level accuracy on an evaluation set
Not finishedmax_tokens is hit and only a legal prefix comes back (13 of 2000 runs in the experiment above); in an OpenAI response status is incomplete and incomplete_details.reason is max_output_tokensCheck the status before parsing; leave enough output length; keep the schema lean so the output is shorter
RefusalWhen the model refuses for safety reasons, the output holds a refusal and does not match the schemaTreat refusal as a normal branch and check for refusal before parsing

So when parsing a response, check in this order: is the response complete (not truncated, not filtered), is it a refusal, does it parse, does it pass schema and business-rule validation. At any failure, retry with the specific reason and a limit on attempts.

Do format constraints hurt reasoning?

Sometimes. Tam et al. (2024) compared several approaches on three reasoning tasks, GSM8K, Last Letter Concatenation and Shuffled Objects: answering in natural language (NL), format-restricting instructions in the prompt (FRI), JSON mode, and OpenAI’s newer Structured Outputs (called JSON-Schema in the paper). To reduce prompt sensitivity, the paper evaluates each approach with 9 prompt combinations. Below are the exact-match scores of gpt-4o-mini-2024-07-18 (Table 2 of the paper, in %, with the standard deviation in parentheses):

TaskNatural languageFormat in promptJSON modeJSON Schema
GSM8K94.57 (3.95)87.17 (4.43)86.95 (1.36)91.71 (0.68)
Shuffled Objects82.85 (5.67)81.46 (3.71)76.43 (9.74)81.77 (6.86)
Last Letter83.11 (3.54)84.73 (2.99)76.00 (6.69)86.07 (3.33)

Every cell has a sizeable standard deviation (0.68 to 9.74), so do not over-read gaps of a few points. What is fairly clear: JSON mode is the lowest of the four approaches on all three tasks, 7.6 points below natural language on GSM8K, while JSON Schema stays close to natural language (2.9 points lower on GSM8K, 1.1 lower on Shuffled Objects, 3.0 higher on Last Letter). Four points come out of this table and the rest of the paper:

  1. On reasoning tasks, format restrictions generally cost something. On GSM8K natural language is best and JSON mode is worst; the paper’s abstract concludes that stricter format constraints generally lead to greater degradation on reasoning tasks. But JSON Schema is clearly better than JSON mode and even edges past natural language on Last Letter (86.07 against 83.11), so “constraints always hurt” does not hold.
  2. Parsing failures do not explain the whole gap. The paper measures parsing error rates: GPT-3.5 Turbo’s JSON parsing error rate on Last Letter is 0 and LLaMA 3 8B’s is only 0.15%, yet their results are still clearly worse. A few settings do have high parsing errors (for example Claude-3-Haiku at 60.07% on GSM8K with JSON), which a second call can repair syntactically; but scores also drop in settings where parsing errors are near zero.
  3. Field order is one key clue. Inspecting GPT-3.5 Turbo’s JSON-mode outputs, the paper found that 100% of the responses put the answer key before the reason key, which means answering first and inventing a rationale afterwards, so the chain of thought disappears. That explains its poor Last Letter result.
  4. The effect depends on the task. On classification tasks JSON mode does as well or better; the paper’s hypothesis is that the constraint narrows the set of possible answers, while free-form answers can add distractions.

What to do:

  • Put reasoning fields before answer fields. The math-tutor example in OpenAI’s documentation is designed this way: steps comes before final_answer, and the output is generated in the order of the keys in the schema.
  • For reasoning-heavy tasks, use two steps: answer in natural language first, then convert the answer into the target format separately. The paper calls this NL-to-Format; for most models it performs almost the same as natural language, occasionally slightly lower because the conversion makes mistakes (for example LLaMA 3 8B Instruct).
  • For classification and extraction, where the answer space is already a finite set, strict constraints are safe to use.
  • Compare on your own evaluation set instead of copying the paper’s conclusion: these are 2024 results on specific models and tasks. For evaluation methods, see LLM Evaluation Methodology.

Function calling

A function call is a structured output at heart: the model outputs a function name and a JSON arguments object; your code actually runs the function, and the result goes back to the model as a new message so it can continue. The model never executes anything, so validation, authorization and error handling all sit on your side.

The six messages of a function-call round trip Three lanes: the model API, your application and the tool or function. The application sends messages and tool definitions to the model; the model returns a tool call with a name and arguments; the application validates the arguments, checks permissions and runs the function, then sends the result or error back as a new message; the model gives the final answer or issues another tool call, which loops back to execution. One round trip of a function call: the model only asks, your code executes Model API Your application Tool / function ① Request: messages + tools ② Tool call: name + arguments ③ Validate, authorize, execute ④ Result (success or error) ⑤ Request again: result + call id ⑥ Final answer, or the next tool call The model never runs anything: it writes a name and arguments; you validate, authorize and execute
A function call is a multi-step message exchange: only your code runs in step 3; the model only ever sees the text result from step 4.

The message shapes of the two APIs

OpenAI’s function-calling documentation uses the Responses API as its example (the Chat Completions API still exists, with different field names), and Anthropic uses the Messages API. These are the key shapes in the official documentation as consulted in November 2026:

StepOpenAI (Responses API)Anthropic (Messages API)
Define a tool{"type": "function", "name", "description", "parameters", "strict"}{"name", "description", "input_schema"}, optionally with strict: true
The model asks for a callA function_call item in the output, with a call_id, a name and arguments as a JSON stringA tool_use block in the reply, with an id, a name and an already-parsed input object; stop_reason is tool_use
Return the resultAppend a function_call_output item with the same call_id and the result as a string outputIn the next user message, a tool_result block with the tool_use_id; add is_error: true on failure; tool_result blocks must come first in that message’s content
Control whether to calltool_choice: auto (default), required, a specific function, allowed_tools, nonetool_choice: auto (default), any, tool (a specific tool), none
Parallel callsSeveral calls can come back at once; parallel_tool_calls: false limits it to at most oneAlso possible; set disable_parallel_tool_use: true inside tool_choice

A few more notes:

  • OpenAI’s arguments is a string you must json.loads yourself; Anthropic’s input is already an object. Even with strict mode on, keep the parsing inside a try.
  • OpenAI’s documentation suggests having fewer than 20 functions available at a time (the documentation itself calls it a soft suggestion), because function definitions count against the context and are billed as input tokens.
  • OpenAI’s allowed_tools limits which tools can be called this turn without changing the tool list; the documentation’s reason is that keeping the list unchanged maximizes the savings from prompt caching. Anthropic’s documentation explains that any and tool prefill the assistant message, so the model does not write natural language before the tool_use block; not every model and setting supports forced tool use, and where unsupported the request errors, so use auto with a strict tool.
  • Write tool descriptions fully. Anthropic’s documentation calls the description by far the most important factor in tool performance and recommends saying what the tool does, when to use it (and when not to), what each parameter means, and any important limitations (such as what information the tool does not return), in at least 3 to 4 sentences per tool.

A minimal tool-call loop that runs

The script below stands in for the model and shows the whole loop: the model first writes a wrong argument name (simulating strict mode being off), the code returns the error as the result of that call, the model corrects itself after seeing it, and answers once it has the result. The message shapes follow the OpenAI column of the table above; for a real call, replace fake_model with client.responses.create(...).

import json

TOOLS = [
    {
        "type": "function",
        "name": "get_order_status",
        "description": "Look up the status of an order by its order id.",
        "parameters": {
            "type": "object",
            "properties": {"order_id": {"type": "string", "description": "Order id, for example A123"}},
            "required": ["order_id"],
            "additionalProperties": False,
        },
        "strict": True,
    }
]


def get_order_status(order_id: str) -> dict:
    return {"order_id": order_id, "status": "charged, awaiting confirmation"}


REGISTRY = {"get_order_status": get_order_status}


def fake_model(items):
    """A script stands in for the model: it calls once with a wrong argument name (as if strict mode were off), fixes it after seeing the error, then answers."""
    outputs = [x for x in items if x.get("type") == "function_call_output"]
    if not outputs:
        return [{"type": "function_call", "call_id": "call_1", "name": "get_order_status", "arguments": '{"order": "A123"}'}]
    if "error" in json.loads(outputs[-1]["output"]):
        return [{"type": "function_call", "call_id": "call_2", "name": "get_order_status", "arguments": '{"order_id": "A123"}'}]
    status = json.loads(outputs[-1]["output"])["status"]
    return [{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": f"Order A123 is currently: {status}."}]}]


def run_tool(call):
    """Arguments from the model are untrusted input: parse, dispatch, catch exceptions, and return errors as output too."""
    try:
        args = json.loads(call["arguments"])
        result = REGISTRY[call["name"]](**args)
    except (json.JSONDecodeError, KeyError, TypeError) as e:
        result = {"error": f"{type(e).__name__}: {e}"}
    return json.dumps(result)


def run(question, max_turns=5):
    items = [{"role": "user", "content": question}]
    for _ in range(max_turns):
        output = fake_model(items)  # for real: client.responses.create(model=..., input=items, tools=TOOLS)
        items += output
        calls = [x for x in output if x["type"] == "function_call"]
        if not calls:
            return output[-1]["content"][0]["text"], items
        for call in calls:
            items.append({"type": "function_call_output", "call_id": call["call_id"], "output": run_tool(call)})
    raise RuntimeError("max turns exceeded")


answer, items = run("What is the status of order A123?")
for x in items:
    kind = x.get("type", x.get("role"))
    detail = x.get("arguments") or x.get("output") or x.get("content")
    if kind == "message":
        detail = detail[0]["text"]
    print(f"{kind:20s} {detail}")
user                 What is the status of order A123?
function_call        {"order": "A123"}
function_call_output {"error": "TypeError: get_order_status() got an unexpected keyword argument 'order'"}
function_call        {"order_id": "A123"}
function_call_output {"order_id": "A123", "status": "charged, awaiting confirmation"}
message              Order A123 is currently: charged, awaiting confirmation.

Three habits in this loop are worth copying:

  • An error is also a result. A parsing failure or an exception in the function becomes an explanatory result handed back to the model instead of crashing the request. Anthropic’s documentation recommends informative error messages, such as “missing required parameter location” rather than “failed”.
  • Cap the turns. The loop needs a maximum number of turns, and exceeding it should raise an error or hand off to a human; otherwise the model and the tools can chase each other in circles.
  • Arguments are untrusted input. The model generated them from what the user said, and they can be steered. Strict mode guarantees format, not safety: permissions, amount limits and resource ownership must be checked in the back end.

What a tool returns is untrusted too: web pages, emails and third-party APIs can carry embedded instructions (indirect prompt injection). Anthropic’s documentation advises keeping such content inside tool_result blocks rather than in the system prompt or plain user text.

A practical checklist

  1. Use a schema constraint when you can, and keep validating: the schema covers format, business rules cover meaning.
  2. In the schema, put reasoning fields before conclusion fields; describe every field and prefer enums.
  3. Leave an exit for irrelevant input (null, unknown or an error field) so the model does not invent values to satisfy the schema.
  4. Check the status before parsing: was the response truncated, filtered or refused.
  5. On failure, retry with the specific error and a limit on attempts; degrade or hand off to a human when it is exceeded.
  6. Treat arguments as untrusted input, and put authorization and limits in the back end.
  7. Keep the schema stable and the number of tools small, and describe what each tool does, when to use it and what its limits are.
  8. Put format-validity rate, field accuracy and retry rate into your evaluation set, and compare results under different constraint strengths.

Apply two checks to synthetic structured data

The Structured Outputs notebook in Berkeley Scalable AI’s spring Assignment 3 generates schemas, tasks, and structured responses, then validates them programmatically. For training data, check field conformance and whether the field values preserve the input’s meaning. For multi-turn tool traces, use mock tools to check arguments and final state in addition to the text.

Four synthetic responses represent a request for a table for three. The handwritten constraints cover this example. The code ran on an Apple M2 Max with Python 3.14.3.

import json

responses = [
    '{"guests": 3}',
    '{"guests": 2}',
    '{"guests": true}',
    '{"guests": 3',
]
valid = correct = 0
for response in responses:
    try:
        obj = json.loads(response)
    except json.JSONDecodeError:
        continue
    if not isinstance(obj, dict) or set(obj) != {"guests"}:
        continue
    count = obj["guests"]
    if type(count) is not int or count < 1:
        continue
    valid += 1
    correct += count == 3

assert (valid, correct) == (2, 1)
print(f"valid fields: {valid}/{len(responses)}")
print(f"correct meaning: {correct}/{len(responses)}")
valid fields: 2/4
correct meaning: 1/4

The second response passes the structural check with the wrong guest count. Python booleans are a subclass of integers, so the code checks the exact type. In a full pipeline, use JSON Schema for structure and human labels, business rules, or a simulated environment for semantic checks. Record both pass rates and inspect failures to decide whether to revise decoding constraints, generation prompts, or grading rules.

Summary and exercises

  • The four levels guarantee different things: a prompt convention guarantees nothing, JSON mode only valid JSON, a schema constraint the supported schema, and validate-and-retry is the backstop.
  • Constrained decoding sets the logits of disallowed tokens to negative infinity at each step and then samples; in engineering, an automaton and a vocabulary index reduce each step to a lookup.
  • It guarantees format, not correct content, not that the output finishes, and it can distort the model’s distribution; on reasoning tasks a strict format can hurt, and putting the reasoning field before the answer is the cheapest mitigation.
  • Function calling is structured output plus a message protocol: the model only asks, and execution, validation and authorization are in your code.

1. What is the difference between JSON mode and Structured Outputs?

  • JSON mode guarantees the schema, Structured Outputs only guarantees valid JSON
  • JSON mode only guarantees valid JSON, while Structured Outputs also guarantees the given schema
  • Neither guarantees valid JSON
  • They differ only in price

OpenAI’s documentation states that both ensure valid JSON, only Structured Outputs ensures schema adherence, and it recommends the latter over the former whenever possible.

2. What does constrained decoding do at each step?

  • Sample freely, then discard and retry if it is illegal
  • Set the logits of disallowed tokens to negative infinity, then run softmax and sample
  • Make the model memorize the format during training
  • Repeat the format over and over in the prompt

The mask removes illegal tokens from sampling, so every step samples only from the allowed set; “sample then check” is rejection sampling, which is very inefficient when the format is strict and the output is long.

3. At the first step the model writes A or B with probability 0.5 each. After A the only legal token has model probability 0.1; after B the only legal token has 0.9. With step-by-step masking, what is the probability that the output starts with A?

  • 5%
  • 10%
  • 50%
  • 90%

At the first step both A and B can still reach a legal output, so neither is masked and each gets 0.5; at the second step only one legal token is left and it is renormalized to 1. Normalizing over the two legal sequences by model probability instead gives 0.05/(0.05+0.45)=10%0.05/(0.05+0.45)=10\%.

4. With a schema constraint on, which of these problems do you still have to handle yourself? (select all that apply)

  • Wrong values: the format is legal but the answer is wrong
  • The output is cut off by max_tokens and only a legal prefix comes back
  • The model refuses for safety reasons and the output holds a refusal instead of the schema’s content
  • JSON brackets that do not match

Bracket matching is part of the format, which constrained decoding already guarantees; whether the values are right, whether the output finishes and whether the model refuses are outside the constraint.

5. Tam et al. (2024) found GPT-3.5 Turbo did very poorly in JSON mode on Last Letter. What was the direct cause?

  • A high JSON parsing failure rate
  • 100% of the responses put the answer key before the reason key, turning the task into direct answering with no chain of thought
  • JSON mode limited the output length
  • The question was truncated on input

The parsing error rate the paper measured is near zero; the problem is field order: writing the answer before the rationale removes the chain of thought.

6. In Anthropic’s Messages API, how do you send a tool’s result back to the model?

  • Send a message whose role is tool
  • In the next user message, add a tool_result block with the matching tool_use_id
  • Append a function_call_output item
  • Write the result into the system prompt

function_call_output is the shape of OpenAI’s Responses API. Anthropic puts tools directly into the content blocks of user and assistant messages and has no dedicated tool role.

Exercises

  1. In the widget above, turn the constraint off and set the temperature to 0.5, 1 and 2, clicking “Run 1000 each” once for each. Roughly what share of unconstrained runs is complete and legal? Why does it fall as the temperature rises?

  2. The schema below is meant for OpenAI’s strict mode. Point out at least two things to change and write the corrected schema:

    {
      "type": "object",
      "properties": {
        "city": {"type": "string"},
        "days": {"type": "integer", "minimum": 1},
        "notes": {"type": "string"}
      },
      "required": ["city", "days"]
    }
  3. In a tool-call loop, the model returns arguments that is not valid JSON (for example, cut off half-way). What should the code do?

Reference answers
  1. About 53%, 17% and close to 0 (each run varies by a few percentage points; a 50,000-run simulation gave 53.1%, 16.9% and 0.1%). A higher temperature moves probability from the top-scored token to the others, including illegal ones: the illegal probability at the start rises from 21.6% at T=0.5 to 43.9% at T=1 and 64.2% at T=2. A complete output needs about ten correct steps in a row, and the per-step legal probabilities multiply, so the validity rate drops quickly with temperature. With the constraint on, all three temperatures give 100% legal output, apart from the rare runs cut off by the 40-step limit.

  2. At least two: the object lacks additionalProperties: false, and notes is not listed in required; strict mode requires every field to be in required, and an optional field is expressed as a union with null. Corrected:

    {
      "type": "object",
      "properties": {
        "city": {"type": "string"},
        "days": {"type": "integer", "minimum": 1},
        "notes": {"type": ["string", "null"]}
      },
      "required": ["city", "days", "notes"],
      "additionalProperties": false
    }
  3. First check whether the response was cut off by max_output_tokens (status is incomplete); if so, raise the output limit or shorten the output instead of retrying blindly. If the model really wrote it wrong, return the parse error as the result of that call (with the call_id) and let it correct itself. Never run a call that has not passed validation, and cap the number of turns, raising an error or handing off to a human when the cap is exceeded.

Further reading

FAQ

What is the difference between JSON mode and Structured Outputs?
JSON mode only guarantees that the output is valid JSON. It does not guarantee your schema, and the conversation must explicitly ask for JSON or the model may emit whitespace until it hits the token limit. Structured Outputs (strict mode) constrains decoding with a JSON Schema, so the output matches the supported subset of that schema. OpenAI's documentation recommends Structured Outputs over JSON mode whenever possible.
How does constrained decoding guarantee the output format?
At every token, the target format (a regex, a grammar or a JSON Schema) and the text written so far determine the set of allowed tokens. The logits of every other token are set to negative infinity before softmax and sampling, so each step is a legal prefix. In practice the format is compiled into an automaton and indexed against the vocabulary, so each step is a table lookup. It guarantees a legal format, not correct content and not that the output finishes within max_tokens.
Do structured outputs make the model less capable?
They can, depending on the task and the method. Tam et al. (2024) found that reasoning tasks degrade under strict format restrictions, and the stricter the restriction the larger the drop, while classification tasks do as well or better. Common mitigations are to put the reasoning field before the answer field in the schema, or to answer in natural language first and convert to the format afterwards, and to compare the options on your own evaluation set.
Does the model run the function itself during function calling?
No. The model only writes a function name and JSON arguments. Your code runs the function and sends the result back as a new message. Argument validation, permission checks, error handling and limits therefore all live on your side, and strict mode does not make them optional.
Do I still need validation and retries when strict mode is on?
Yes. Strict mode only covers format. The values can be wrong, the output can be cut off by max_tokens or refused for safety reasons, and business rules such as amount ranges or resource ownership are not in the schema. Check the response status and refusals first, then parse and validate, and on failure retry with the specific error and a retry limit.