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.
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
- Four levels of control
- Constrained decoding
- Only legal tokens get through at every step
- How rules become an allowed set
- Try it: watch the mask step by step
- A few lines of standard-library Python
- Step-by-step masking changes the distribution
- Writing the schema: strict-mode rules and design
- Generate the schema from types, and mind a few traps
- A constraint only covers format
- Do format constraints hurt reasoning?
- Function calling
- The message shapes of the two APIs
- A minimal tool-call loop that runs
- A practical checklist
- Apply two checks to synthetic structured data
- Summary and exercises
- Exercises
- Further reading
- 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.
| Approach | How | Guarantees | Does not guarantee |
|---|---|---|---|
| Prompt convention | State the format in the prompt, add one or two examples | Only a higher probability, no guarantee | Unbalanced brackets, extra chatter, missing fields, wrong types |
| JSON mode | Turn on the API’s JSON switch (json_object at OpenAI) | The output is valid JSON | That it matches your schema |
| Schema constraint | Provide 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 schema | That the values are right; no legal output if it is truncated or refused |
| Validate and retry | Parse, check against the schema and business rules, and on failure send the error back and let the model retry | Catches and repairs syntax and semantic errors | An 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
Only legal tokens get through at every step
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 of tokens allowed at this step, sets the logits outside the set to , and then runs softmax and sampling. The renormalized probability is
Every step can only sample from , so the output is always a legal prefix of the target format and cannot go wrong half-way. The real engineering difficulty is computing quickly.
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 , 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 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:
- 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.
- 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
}. - 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.
- 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_tokenstruncation, 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 method | Probability of Ax | Probability of By |
|---|---|---|
| Normalize over the two legal sequences by model probability | 10% | 90% |
| Step-by-step masking | 50% | 50% |
The model probabilities of the two legal sequences are and , 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.
| Rule | Details |
|---|---|
additionalProperties | Every object must set additionalProperties: false; keys that are not in the schema are not allowed |
required | Every field in properties must be listed in required. To make a field optional, type it as a union with null, for example ["string", "null"] |
| Root | Must be an object, not anyOf (a Zod discriminated union produces a top-level anyOf, so wrap it in an object) |
| Supported types | String, number, integer, boolean, object, array, enum and anyOf; $defs and recursive references are supported |
| Unsupported keywords | allOf, not, dependentRequired, dependentSchemas, if, then, else |
| Size limits | At most 5000 object properties and 10 levels of nesting; property names, enum values and similar strings total at most 120,000 characters |
| Key order | Output is generated in the order of the keys in the schema |
| When a rule is broken | The 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"producesadditionalProperties: 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 asstr | Nonewith no default (seeFixed): it is then both a union withnulland listed inrequired. - Field order is the order of
propertiesin the schema, which is the order in which the model generates. Puttingreasonbeforeprioritymakes 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:
- Name keys clearly and give every field a
description; prefer an enum to free text. - Do not make the model fill values you already know. If the order id is already in your code, do not make
order_ida parameter for the model to copy. - 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,unknownor a dedicated error field. - 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:
| Problem | What it looks like | What to do |
|---|---|---|
| Wrong content | The format is legal and the value is wrong: any legal name and age in the toy above passes | Write clear instructions, add examples, split the task; validate ranges and consistency with business rules; measure field-level accuracy on an evaluation set |
| Not finished | max_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_tokens | Check the status before parsing; leave enough output length; keep the schema lean so the output is shorter |
| Refusal | When the model refuses for safety reasons, the output holds a refusal and does not match the schema | Treat 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):
| Task | Natural language | Format in prompt | JSON mode | JSON Schema |
|---|---|---|---|---|
| GSM8K | 94.57 (3.95) | 87.17 (4.43) | 86.95 (1.36) | 91.71 (0.68) |
| Shuffled Objects | 82.85 (5.67) | 81.46 (3.71) | 76.43 (9.74) | 81.77 (6.86) |
| Last Letter | 83.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:
- 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.
- 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.
- 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
answerkey before thereasonkey, which means answering first and inventing a rationale afterwards, so the chain of thought disappears. That explains its poor Last Letter result. - 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:
stepscomes beforefinal_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 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:
| Step | OpenAI (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 call | A function_call item in the output, with a call_id, a name and arguments as a JSON string | A tool_use block in the reply, with an id, a name and an already-parsed input object; stop_reason is tool_use |
| Return the result | Append a function_call_output item with the same call_id and the result as a string output | In 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 call | tool_choice: auto (default), required, a specific function, allowed_tools, none | tool_choice: auto (default), any, tool (a specific tool), none |
| Parallel calls | Several calls can come back at once; parallel_tool_calls: false limits it to at most one | Also possible; set disable_parallel_tool_use: true inside tool_choice |
A few more notes:
- OpenAI’s
argumentsis a string you mustjson.loadsyourself; Anthropic’sinputis already an object. Even with strict mode on, keep the parsing inside atry. - 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_toolslimits 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 thatanyandtoolprefill the assistant message, so the model does not write natural language before thetool_useblock; not every model and setting supports forced tool use, and where unsupported the request errors, so useautowith 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
- Use a schema constraint when you can, and keep validating: the schema covers format, business rules cover meaning.
- In the schema, put reasoning fields before conclusion fields; describe every field and prefer enums.
- Leave an exit for irrelevant input (
null,unknownor an error field) so the model does not invent values to satisfy the schema. - Check the status before parsing: was the response truncated, filtered or refused.
- On failure, retry with the specific error and a limit on attempts; degrade or hand off to a human when it is exceeded.
- Treat arguments as untrusted input, and put authorization and limits in the back end.
- 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.
- 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 .
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_tokensand only a legal prefix comes back - The model refuses for safety reasons and the output holds a
refusalinstead 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
answerkey before thereasonkey, 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
roleistool - In the next
usermessage, add atool_resultblock with the matchingtool_use_id - Append a
function_call_outputitem - Write the result into the system prompt
function_call_outputis the shape of OpenAI’s Responses API. Anthropic puts tools directly into the content blocks ofuserandassistantmessages and has no dedicatedtoolrole.
Exercises
-
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?
-
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"] } -
In a tool-call loop, the model returns
argumentsthat is not valid JSON (for example, cut off half-way). What should the code do?
Reference answers
-
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.
-
At least two: the object lacks
additionalProperties: false, andnotesis not listed inrequired; strict mode requires every field to be inrequired, and an optional field is expressed as a union withnull. Corrected:{ "type": "object", "properties": { "city": {"type": "string"}, "days": {"type": "integer", "minimum": 1}, "notes": {"type": ["string", "null"]} }, "required": ["city", "days", "notes"], "additionalProperties": false } -
First check whether the response was cut off by
max_output_tokens(statusisincomplete); 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 thecall_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
- Willard and Louf, Efficient Guided Generation for Large Language Models (2023); Outlines, compiling a regex into a finite-state machine and indexing the vocabulary
- Dong et al., XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models (2024); efficient mask computation for context-free grammars, the source of the vocabulary-split and 128k-vocabulary numbers on this page
- Park et al., Grammar-Aligned Decoding (2024); how step-by-step masking distorts the model’s distribution, and the ASAp algorithm that aligns it
- Tam et al., Let Me Speak Freely? A Study on the Impact of Format Restrictions on Performance of Large Language Models (2024); how format restrictions affect reasoning and classification tasks differently, the source of the table on this page
- OpenAI documentation: Structured Outputs and Function calling (consulted in November 2026)
- Anthropic documentation: Define tools, Handle tool calls and Strict tool use (consulted in November 2026)
- On this site: Prompt Engineering: A Systematic Guide to Specs, Layers, Examples and Evaluation, Decoding and Sampling and LLM Evaluation Methodology
- Constrained decoding in robotics: RT-2 samples only from 256 action tokens on robot-action tasks.
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.