What it is
Large language models sample tokens probabilistically rather than executing strict schemas by default. Constrained decoding or tool schemas force outputs into valid JSON shapes, while prompt trust boundaries treat user input and retrieved documents as untrusted data rather than system authority.
Why you need it
Asking nicely in a prompt still leaves a tail of malformed JSON or overridden instructions. Production integrations need schema enforcement in code and security controls outside the model.
How it works
- Define an explicit output schema with tight fields and types.
- Use provider constrained generation or tool calling instead of regexing markdown.
- Validate parsed output in application code and handle bounded retries.
- Never rely on system prompt phrasing alone to guard secrets or privileged actions.
Schema validation at the model boundary
function parseInvoiceExtraction(rawText) {
const parsed = JSON.parse(rawText)
if (typeof parsed.invoiceId !== "string" || typeof parsed.totalCents !== "number" || !Number.isInteger(parsed.totalCents)) {
throw new Error("Invalid extraction shape")
}
return { invoiceId: parsed.invoiceId, totalCents: parsed.totalCents }
}Even with constrained generation, validate types and ranges in code before persisting to a database or calling downstream tools. Treat injected user strings as untrusted data.
Good practices and why
- Keep schemas flat and minimal to lower generation errors.
- Keep credentials and authorization checks out of prompts and enforce them in application code.
Common mistakes
- Adding "return valid JSON" to the prompt and assuming parse errors cannot happen.
- Embedding sensitive internal API secrets inside a system prompt.
Try it yourself
Write a strict validator for an extracted support ticket ({ category, priority, summary }) and test it against missing fields, extra unexpected keys, and prompt-injection text inside the summary.
What a successful result looks like
Malformed shapes fail loudly with a clear error rather than writing corrupt records, and user text cannot invent privileged fields.
0 / 6000 characters · Saved on this device. Do not include passwords or private data.
Check your understanding
Answer the understanding check correctly to record exercise completion.
Related interview practice
- A user made your AI assistant ignore its instructions. ↗
- The model returns valid JSON 90% of the time. ↗
These scenarios add constraints and follow-up questions to the concepts you just learned.
Further reading
Selected primary references · reviewed 2026-10-09. Examples are educational; use your framework’s documented integration guidance when building a deployed system.