Prompting a language model to reply in JSON and running JSON.parse in a try/catch loop breaks as soon as traffic scales. Models wrap payloads in Markdown code fences, invent extra keys, omit required fields, or close braces early under token limits. Grammar-constrained decoding eliminates syntax drift inside the token sampler itself, though it still cannot verify whether the values inside a valid payload are true or authorized.
Choosing between unconstrained JSON, non-strict tool calling, and strict schema decoding is an architectural decision that affects latency, accuracy, and application security. For how schema enforcement fits into multi-step tool execution, see our AI SDK 6 and TypeScript tools guide.
How grammar-constrained decoding works
During normal generation, an autoregressive model computes a logit score for every token in its vocabulary at each step and samples from the resulting probability distribution. Grammar-constrained decoding inserts a deterministic state machine between the logit vector and the sampler.
Before sampling the next token, the engine compiles your JSON Schema into a finite-state machine (FSM) or pushdown context-free grammar (CFG). Systems such as OpenAI Structured Outputs, Anthropic strict tool schemas, Gemini responseSchema, vLLM with xgrammar or outlines, and llama.cpp GBNF grammars advance the parser state after each emitted token and build a bitmask over the vocabulary. Every token that would violate the active grammar transition has its logit forced to negative infinity before softmax.
Because invalid tokens receive zero probability mass, the model can only emit characters that advance a valid JSON document matching your schema. As explained in the OpenAI Structured Outputs guide, strict mode ensures structural adherence unless the model issues a safety refusal or hits max_tokens before closing the root object.
Constrained decoding versus tool calling and semantic safety
Strict grammar masking solves syntax, not truth or authorization. If an untrusted document injects instructions telling a support classifier to output "decision": "approve", the constrained sampler happily masks logits to guarantee a valid enum string while emitting the attacker's chosen value.
| Extraction mode | Syntactic compliance | First-request latency | Schema expressiveness | Semantic and security safety |
|---|---|---|---|---|
| Prompt-only JSON | Best-effort; breaks on edge cases | Zero compilation overhead | Unrestricted prose guidance | Requires full parser and repair |
| Non-strict tool calling | High on common models, not guaranteed | Low; schema lives in prompt | Broad JSON Schema support | Needs strict runtime validation |
| Grammar-constrained output | Guaranteed until stop (unless truncated) |
Cold compile cost on new shape | Strict provider subset only | Syntax valid; semantics still untrusted |
| Constrained + Zod boundary | Guaranteed syntax plus domain invariants | Amortized via static schemas | Static wire schema + rich TS checks | Enforces cross-field rules and permissions |
Treat every constrained LLM output as untrusted user input at your TypeScript boundary. Combine strict wire schemas with domain authorization rules like those detailed in our prompt injection and MCP security checklist and production AI agent architecture.
JSON Schema subset limits across providers
Full JSON Schema Draft 2020-12 includes constructs that cause state explosion or non-determinism when compiled into token-level grammars. Every major engine therefore restricts schemas to a predictable subset:
additionalProperties: falseon every object: OpenAI strict mode and most CFG compilers reject open object schemas because allowing arbitrary unknown keys prevents tight grammar bounds.- All properties listed in
required: To avoid exponential optional-field branching in the state graph, strict schemas require every declared key to appear inrequired. Represent optional fields explicitly as nullable unions such astype: ["string", "null"]. - Bounded recursion and
$defssupport: Recursive trees via$refwork in OpenAI Structured Outputs andllama.cppGBNF via CFG pushdown stacks, whereas pure FSM engines and some hosted Gemini schema tiers reject recursive references or cap nesting depth. - Restricted regex and string/numeric bounds: Lookaheads, backreferences, and nested quantifiers in
patternfail compilation or blow up DFA table size. Numeric constraints such asmultipleOf,minimum, ormaxLengthare often stripped or unsupported in strict mode depending on the provider.
Keep your wire schema portable by sticking to primitives, fixed object trees, enum literals, nullable unions, and additionalProperties: false, while enforcing regex patterns, numeric bounds, and array length limits inside TypeScript after parsing.
First-request grammar compilation latency
Compiling a JSON Schema into token bitmasks across a 100,000+ token vocabulary is non-trivial compute. On the first request containing an unseen schema shape, the inference server parses the schema, constructs the FSM or CFG transition tables, and maps vocabulary subword tokens to valid state transitions. That cold compilation adds tens of milliseconds to several seconds of time-to-first-token latency, or returns HTTP 400 if a large enum or deep union exceeds compiler limits.
Providers cache compiled grammars by schema structure hash. Injecting dynamic per-request values directly into the schema—such as putting 500 tenant-specific category IDs into an enum or generating dynamic object keys from database rows—invalidates the grammar cache on every call and triggers repeated cold compilation spikes. Keep the wire schema structurally static across requests: use plain string (or a small fixed enum) in JSON Schema, pass dynamic candidate IDs inside the prompt context, and verify membership in TypeScript after decoding.
Field ordering for autoregressive accuracy
Property order inside a JSON Schema changes classification accuracy even when every property has the exact same type. Autoregressive transformers generate tokens strictly from left to right, conditioning each token on everything emitted before it.
Consider a schema for triaging support refund requests:
{
"type": "object",
"additionalProperties": false,
"required": ["decision", "rationale"],
"properties": {
"decision": { "type": "string", "enum": ["approve", "escalate", "reject"] },
"rationale": { "type": "string" }
}
}
When "decision" appears first, the model must commit to "approve" or "reject" immediately after emitting {"decision":"—before it has written a single token summarizing the evidence. Once "approve" is in the KV cache, "rationale" becomes post-hoc rationalization constrained to justify that locked choice.
Reordering the properties so evidence and analysis precede the label resolves the bottleneck:
- Place
"extractedFacts"or"evidenceQuotes"first so the model copies grounded identifiers and amounts from input data. - Place a concise
"reasoningSummary"second to resolve policy conditions explicitly in tokens. - Place
"decision"and"confidence"last so the constrained decoder samples the final enum conditioned on all preceding structured observations.
Keep "reasoningSummary" concise in your instructions so an overly verbose rationale cannot exhaust max_tokens before the trailing "decision" field is reached.
TypeScript and Zod validation boundaries
The TypeScript boundary owns three tasks that constrained decoding never handles: checking finishReason for truncation or refusals, verifying cross-field invariants, and isolating semantic validation errors from wire syntax errors.
The following standalone TypeScript module uses Zod to derive a strict wire schema, inspect termination status, enforce business invariants that JSON Schema cannot express, and produce typed feedback when semantic verification fails.
import { z } from "zod";
const RefundExtractionSchema = z
.object({
orderId: z.string(),
evidenceQuote: z.string(),
reasoningSummary: z.string(),
requestedCents: z.number().int(),
decision: z.enum(["approve", "escalate", "reject"]),
})
.strict();
type RefundExtraction = z.infer<typeof RefundExtractionSchema>;
interface OrderContext {
orderId: string;
paidCents: number;
maxAutoApproveCents: number;
refundEligible: boolean;
}
interface ModelCompletion {
finishReason: "stop" | "length" | "content_filter" | "error";
refusal?: string;
rawJson: string;
}
type ValidationOutcome =
| { ok: true; data: RefundExtraction }
| { ok: false; retryable: boolean; reason: string };
export function toStrictOpenAISchema(): Record<string, unknown> {
return {
type: "object",
additionalProperties: false,
required: [
"orderId",
"evidenceQuote",
"reasoningSummary",
"requestedCents",
"decision",
],
properties: {
orderId: { type: "string" },
evidenceQuote: { type: "string" },
reasoningSummary: { type: "string" },
requestedCents: { type: "integer" },
decision: { type: "string", enum: ["approve", "escalate", "reject"] },
},
};
}
export function validateRefundOutput(
completion: ModelCompletion,
context: OrderContext,
): ValidationOutcome {
if (completion.refusal) {
return { ok: false, retryable: false, reason: `model_refusal:${completion.refusal}` };
}
if (completion.finishReason !== "stop") {
return {
ok: false,
retryable: completion.finishReason === "length",
reason: `incomplete_generation:${completion.finishReason}`,
};
}
let parsedRaw: unknown;
try {
parsedRaw = JSON.parse(completion.rawJson);
} catch {
return { ok: false, retryable: true, reason: "malformed_json" };
}
const DomainGuard = RefundExtractionSchema.superRefine((val, ctx) => {
if (val.orderId !== context.orderId) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["orderId"],
message: "Returned orderId does not match active order context",
});
}
if (val.requestedCents <= 0 || val.requestedCents > context.paidCents) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["requestedCents"],
message: "Requested refund exceeds paid order amount",
});
}
if (val.decision === "approve" && !context.refundEligible) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["decision"],
message: "Cannot approve refund for ineligible order",
});
}
if (val.decision === "approve" && val.requestedCents > context.maxAutoApproveCents) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["decision"],
message: "Amount exceeds automatic approval threshold",
});
}
});
const checked = DomainGuard.safeParse(parsedRaw);
if (!checked.success) {
const summary = checked.error.issues.map((i) => `${i.path.join(".")}:${i.message}`).join("; ");
return { ok: false, retryable: true, reason: summary };
}
return { ok: true, data: checked.data };
}
Notice how the TypeScript boundary enforces invariants that no JSON Schema grammar can express: matching orderId against the authenticated request context, capping requestedCents at paidCents, and blocking "approve" when refundEligible is false. If validateRefundOutput returns retryable: true because finishReason === "length", increase max_tokens or shorten reasoningSummary; if a domain check fails, reject the action or feed the concise violation string into one bounded correction attempt rather than executing the payload.
Production rollout checklist
Before enabling strict structured outputs on a production route, confirm five engineering checks:
- Every object node in the exported JSON Schema explicitly sets
additionalProperties: falseand lists all keys inrequired. - Dynamic IDs and runtime database options live in prompt context rather than dynamically generated
enumschemas so provider grammar caches remain warm. - Extraction and reasoning fields appear before classification enums in both the JSON Schema property list and prompt instructions.
- Callers inspect
finishReasonandrefusalbefore callingJSON.parse, handlinglengthtruncation cleanly without treating cut-off JSON as a bug in the model grammar. - Every parsed payload passes through a Zod domain boundary checking tenant ownership, numeric limits, and business state transitions before triggering side effects.