Home / Insights / Generative AI and LLMs
Generative AI and LLMs
Structured Outputs and Function Calling: Making LLM Responses Reliable Enough for Software
Free text is fine for a chat window, but software needs fields it can trust. This guide explains how structured outputs and function calling work, where they still fail, and the validation layer every production integration needs.
Key takeaways
- Prompting for JSON is not enough for production; use schema-constrained outputs or strict function calling where your provider supports them.
- A valid schema is not a correct answer: schema enforcement guarantees shape, not truth, so business validation still runs after every call.
- Design schemas for the model as well as the code: clear field descriptions, enums instead of free text, and an explicit way to say ‘unknown’.
- Treat every model output and tool argument as untrusted input, as OWASP’s 2025 guidance on improper output handling recommends.
- Plan for refusals, truncation and timeouts as normal paths, with retries, fallbacks and a human review queue where the stakes justify it.
On this page
- Why do LLM features need structured outputs?
- What are the options, from prompting to strict schemas?
- How do you choose the right approach?
- How should you design schemas the model can follow?
- How do you validate outputs and keep integrations safe?
- How do you test and handle failures in production?
- What should be on your implementation checklist?
- Frequently asked questions
- Sources and methodology
Most valuable LLM features are not chatbots. They are pieces of software that classify a ticket, extract fields from an invoice, choose which internal API to call, or draft a record that another system stores. In all of these, the model’s response is read by code, not a person. If a field is missing, a date is in the wrong format or the model adds a friendly sentence before the JSON, the integration breaks.
Over the past two years the major providers have added features designed for exactly this problem: JSON modes, schema-constrained structured outputs and function calling (also called tool use). They have made reliable integrations much easier, but they have not removed the need for engineering discipline. This article is for CTOs, technical leads and product owners building LLM features into real systems. It explains the options, how to choose between them, how to design schemas and validation, how to test, and what to do when the model still gets it wrong.
Why do LLM features need structured outputs?
A language model generates text one token at a time. Left to itself, it produces whatever text seems most likely, which may or may not match the format your code expects. Early integrations relied on prompts such as “respond only with JSON in this format” and a parser wrapped in a retry loop. That works in demos and fails at scale, typically in three ways:
- Syntax failures. Invalid JSON, trailing commentary, unescaped quotes or truncated output.
- Shape failures. Valid JSON but missing required fields, extra fields, wrong types or values outside an allowed list.
- Semantic failures. Correct shape, wrong content: a plausible but incorrect invoice total, the wrong customer ID, or a category that does not fit.
Structured output features largely solve the first two. The third is a quality problem that no format feature can solve, and it is where most production effort should go.
Where structure matters most
- Extraction from documents, emails and forms into database records.
- Classification and routing, such as triaging support tickets or referrals.
- Tool and API calls made by assistants and agents.
- Generating content that must fit a template, such as product attributes or report sections.
What are the options, from prompting to strict schemas?
1. Prompt-only formatting
You describe the format in the prompt and parse the result. It works with any model, but offers no guarantee. Reserve it for prototypes or models without better options.
2. JSON mode
The provider guarantees syntactically valid JSON but not a particular structure. It removes parse errors but not missing or misnamed fields.
3. Schema-constrained structured outputs
You supply a JSON Schema and the provider constrains generation so the output matches it. OpenAI introduced this in August 2024: with strict: true, outputs adhere to the supplied schema. In OpenAI’s own evaluation of complex schema following, gpt-4o-2024-08-06 with Structured Outputs scored 100%, against under 40% for gpt-4-0613, and 93% for the newer model without constrained decoding. The same announcement lists important limits: only a subset of JSON Schema is supported, the first request with a new schema has extra latency while it is processed, refusals and outputs cut off by token limits may not match the schema, and strict mode was not compatible with parallel function calls at launch.
4. Function calling (tool use)
You describe functions with a name, a description and a JSON Schema for the arguments. The model decides whether to call one and returns the arguments as structured data; your code executes the function and returns the result. Anthropic’s documentation describes the same loop for Claude: the model returns a tool_use block with an ID, a name and input, your application runs the tool, and you send back a tool_result referencing that ID. Anthropic’s tool use documentation also notes that models may sometimes fill in or omit required parameters with ambiguous prompts, so inputs should be validated in your code.
Comparison
| Approach | Syntax guaranteed | Schema guaranteed | Best for | Main caveat |
|---|---|---|---|---|
| Prompt-only | No | No | Prototypes, any model | Needs robust parsing and retries |
| JSON mode | Yes | No | Simple, flexible objects | Fields can still be missing or wrong |
| Schema-constrained output | Yes | Yes, within supported subset | Extraction, classification, fixed records | Schema subset limits; refusals and truncation |
| Function calling, non-strict | Usually | No | Assistants choosing between actions | Arguments must be validated |
| Function calling, strict | Yes | Yes, where supported | Agents calling business APIs | Provider-specific support and limits |
How do you choose the right approach?
Three questions decide most cases.
- Is the model producing data or choosing an action? If it is producing a record (fields from a document, a classification), use a structured response format. If it is choosing which of several operations to perform, use function calling.
- How costly is a malformed result? If a failure just means a retry in a background job, JSON mode plus validation may be enough. If a malformed call could write bad data to a finance system, use the strictest option available and validate anyway.
- How portable must the design be? Providers implement these features differently and support different schema subsets. If you route between models or expect to switch, keep your schemas within the common subset and keep validation in your own code.
For example, an illustrative accounts-payable workflow might use a schema-constrained response to extract supplier, invoice number, dates, line items and totals, then use deterministic code (not the model) to match the invoice against purchase orders. The model fills the form; software makes the decision. Our guide to choosing a document extraction approach covers when an LLM is the right extractor in the first place.
How should you design schemas the model can follow?
JSON Schema is a declarative format for describing the structure of JSON data, and it serves both validation and documentation. The JSON Schema project also points out that schemas cannot express every constraint, so complex formats need a second, semantic validation step in ordinary code. That applies directly to LLM outputs.
Design rules we follow
- Describe every field. Field descriptions are instructions to the model. “Invoice date in ISO 8601 (YYYY-MM-DD), as printed on the document, not the due date” prevents a whole class of errors.
- Prefer enums to free text. A category field with five allowed values is easier to validate, analyse and act on than an open string.
- Make “unknown” explicit. Allow null or an explicit “not_found” value, and tell the model to use it rather than guess. Without this, required fields push the model to invent values.
- Keep nesting shallow. Deeply nested or recursive schemas are harder for models and may fall outside a provider’s supported subset.
- Separate evidence from conclusions. For extraction, ask for the quoted source text alongside the extracted value, so reviewers and validators can check it.
- Version schemas. Store a schema version with every output so downstream systems and evaluations know which contract applied.
Designing function definitions
- Give each function a single clear purpose and a description that says when to use it and when not to.
- Expose narrow, business-level operations (
create_refund_request) rather than generic ones (run_sql). - Keep the number of tools offered in one request small and relevant to the task.
- Mark parameters as required only when they truly are, and describe valid values with examples.
How do you validate outputs and keep integrations safe?
Schema enforcement tells you the output has the right shape. It does not tell you the output is true, permitted or safe. The OWASP Top 10 for LLM Applications 2025 lists improper output handling (LLM05:2025): passing model output to other components without validation, sanitisation or handling, which can lead to cross-site scripting, SQL injection, privilege escalation or remote code execution. OWASP’s recommended stance is zero trust: treat model output like any untrusted user input.
A layered validation pipeline
- Structural validation. Validate against the JSON Schema in your own code, even when the provider enforces it, so behaviour stays consistent across models.
- Business rules. Check totals add up, dates are plausible, IDs exist in your database, and enums map to real states.
- Authorisation. For function calls, check that the current user is allowed to perform the action with those arguments. The model choosing an action does not grant permission for it.
- Context-appropriate encoding. Encode output for where it is used: HTML-encode for web pages, use parameterised queries for databases, never pass output to
evalor a shell. - Confidence routing. Send low-confidence, high-value or rule-failing results to a human review queue instead of writing them automatically.
Our walkthrough of the OWASP Top 10 for LLMs covers the wider security picture, and AI agent permissions and approvals covers when a function call should require human sign-off.
How do you test and handle failures in production?
Build an evaluation set
Collect 100 or more representative inputs, including messy and edge cases, with expected outputs. Measure schema validity, field-level accuracy, the rate of “unknown” answers, and for function calling, whether the right tool was chosen with the right arguments. Re-run this set whenever you change the model, the prompt or the schema.
Treat failure modes as normal paths
| Failure | How it shows up | Handling |
|---|---|---|
| Refusal | Provider signals a refusal; output may not match schema | Detect explicitly; route to review or return a safe message |
| Truncation | Generation stops at the token limit | Check the stop reason; raise limits or split the task |
| Timeout or rate limit | No response or provider error | Retry with backoff; fall back to another model if configured |
| Valid but wrong | Passes schema, fails business rules | Retry once with the validation error in context, then review queue |
| Wrong tool chosen | Plausible call to the wrong function | Narrow tool lists per task; confirmation step for risky actions |
Monitor in production
- Log inputs, outputs, schema version, model version and validation results (with redaction where data is sensitive).
- Track validation failure rate, review queue volume and retry rate per feature.
- Alert on sudden changes, which often signal a model update or a change in input data.
What should be on your implementation checklist?
- Decide per feature whether the model produces data (structured response) or chooses actions (function calling).
- Use the strictest structured output mode your chosen models support, and keep schemas within their supported subset.
- Write descriptions for every field and function; use enums and an explicit “unknown” value.
- Validate structure, business rules and authorisation in your own code on every call.
- Encode outputs for their destination and never execute model output directly.
- Handle refusals, truncation, timeouts and rule failures explicitly, with retries, fallbacks and a review queue.
- Version schemas and prompts, and keep an evaluation set that runs on every change.
- Monitor validation failures and review volumes after launch.
PoliteTech’s LLM application development work treats these as standard: typed outputs, validation logic, retries, timeouts, fallback models, evaluation sets and monitoring are part of how we ship AI features, including in products such as our AI-assisted team messaging tool and the AI referral processing in our clinical operations platform work for an Australian healthcare client. For a broader pre-launch view, see our production readiness checklist for LLM features.
Frequently asked questions
If we use strict structured outputs, do we still need validation?
Yes. Strict modes guarantee the shape of the output, not that the values are correct, permitted or safe. Business rules, authorisation checks and output encoding still need to run in your own code.
Should we use function calling or a structured response format?
Use a structured response when the model is producing a record, such as extracted fields or a classification. Use function calling when the model is choosing which action to take. Many features use both.
Do structured outputs work the same across providers?
No. Providers support different JSON Schema subsets and have different strict-mode options and limits. If you use several models, keep schemas simple and portable and keep validation in your own code.
What happens when the model cannot find a value?
If the schema forces a value, the model may invent one. Allow null or an explicit not-found value, instruct the model to use it, and track how often it appears as a quality signal.
Does structured output make responses slower?
Usually only slightly. Some providers add latency the first time a new schema is used while it is processed. Long or complex schemas also increase token usage, so keep them focused on the fields you need.
Sources and methodology
Guidance reflects PoliteTech delivery experience. The external references below informed specific points in this article.
- OpenAI: Introducing Structured Outputs in the API (6 August 2024) — accessed 9 November 2026. strict: true schema adherence, evaluation results (100% vs under 40%), and limitations: schema subset, first-request latency, refusals, truncation, parallel calls.
- Anthropic: Tool use with Claude (documentation) — accessed 9 November 2026. The tool_use / tool_result loop, JSON Schema tool inputs, and the advice to validate inputs because parameters may be filled in or omitted.
- OWASP GenAI Security Project: LLM05:2025 Improper Output Handling — accessed 9 November 2026. Risks of passing unvalidated model output downstream and prevention: zero trust, validation, context-aware encoding, parameterised queries.
- JSON Schema: What is a schema? (Understanding JSON Schema) — accessed 9 November 2026. JSON Schema for validation and documentation, and the need for a second semantic validation step.
Related reading
Continue your research
Are your LLM integrations producing data your systems can trust?
We can review your schemas, validation and failure handling, or build a reliable LLM feature from prototype to production.
