FORTILABS AI LAB · ENGINEERING
An AI pipeline can return perfectly valid JSON and still fail in production. A field may contain the wrong business value, a tool may be called with an unauthorized identifier, or a downstream service may reject an otherwise well-formed request.
The distinction matters: Structured Outputs controls the shape of model-generated data. Function calling gives a model a structured way to request application actions. They solve related but different problems, and modern AI systems often need both.
TL;DR
- Use Structured Outputs when the model must return data in a defined schema.
- Use function calling when the model needs to request an operation from your application, such as searching records or creating a support ticket.
- Use strict schema enforcement for supported model and API configurations, but still handle refusals, incomplete responses, and unsupported schema features.
- Validate business rules, permissions, and state transitions in application code. Schema compliance is not proof of correctness or authorization.
- Measure reliability across the complete pipeline, not just JSON parsing.
1. The real problem with AI output
Traditional application code generally operates on predictable contracts. A function receives defined parameters, executes logic, and returns a value according to an expected interface. Large language models are different: their primary output is generated from learned patterns and context.
If an application asks a model to return JSON using only a prompt, it is relying on instructions to control a format that the model is generating token by token. That can fail in several ways:
- Invalid JSON syntax, such as trailing commas or unescaped characters.
- Missing required fields.
- Unexpected types, such as a number represented as a string.
- Values outside an application’s accepted enumeration.
- Structurally valid data that is semantically incorrect.
- Tool arguments that are valid JSON but unsafe or unauthorized.
Consider an invoice extraction pipeline. It receives a document and asks a model to return a customer identifier, invoice number, currency, and total. A response can parse successfully while assigning the wrong customer or extracting a subtotal instead of the final amount.
This is why a production design needs more than a JSON parser. It needs a contract for data shape, application-level validation, authorization, controlled execution, and recovery.
Important distinction: Eliminating malformed JSON is a narrower goal than eliminating AI pipeline failures. Structured generation can reduce formatting failures, but it cannot guarantee that the model understood the source correctly or that the application should accept the result.
2. Structured Outputs and function calling explained
What are Structured Outputs?
Structured Outputs constrain a model’s response to a developer-defined data schema. Instead of merely asking for JSON, the application provides a schema describing the expected structure, field types, required properties, and supported constraints.
With a supported API configuration, strict Structured Outputs uses constrained generation to ensure the response conforms to the supported schema. This is stronger than ordinary JSON mode, which targets valid JSON syntax but does not guarantee adherence to a particular schema.
For example, a document extraction system might expect:
{
"invoice_number": "INV-2048",
"currency": "USD",
"total": 1250.50,
"is_paid": false
}
A schema can require the invoice number to be a string, the total to be numeric, and the payment status to be Boolean. It can also restrict currency to an allowed set of values, subject to the provider’s supported schema features.
Structured Outputs is useful for extraction, classification, report generation, data transformation, and any workflow where model responses become application data.
What is function calling?
Function calling, also known as tool calling, allows a model to request that the surrounding application execute a defined operation.
The application describes available tools and their parameters. The model can select a tool and produce arguments. The application receives the request, validates it, performs the operation if permitted, and returns the result to the model or workflow.
For example, a customer support assistant might have access to:
{
"name": "lookup_order",
"description": "Retrieve an order using its public order reference.",
"parameters": {
"order_reference": "ORD-7821"
}
}
The model does not directly execute the database query. It requests the operation. The application remains responsible for deciding whether the request is valid, authorized, and safe to run.
They can work together
These concepts are not mutually exclusive. Strict function calling applies schema constraints to tool names and arguments in supported configurations. Structured Outputs can separately constrain the model’s final response after the tool operation has completed.
OpenAI documents the distinction directly: function calling is intended for connecting models to tools and application functionality, while a structured response format is appropriate when the application needs the model’s answer to follow a defined schema. OpenAI Structured Outputs documentation.
3. The practical differences
| Dimension | Structured Outputs | Function Calling |
|---|---|---|
| Primary purpose | Generate data matching a defined schema. | Request execution of an application-defined tool. |
| Typical output | Structured response data. | Tool name and structured arguments. |
| Application action | Usually parses and processes the response. | Validates and may execute the requested operation. |
| Common use cases | Extraction, classification, normalization, reports. | Database lookup, API calls, workflow actions, search. |
| Schema enforcement | Constrains the response to a supported schema. | Strict mode can constrain tool arguments to a supported schema. |
| Does it execute code? | No. | No. The application executes the requested tool. |
| Does it guarantee business correctness? | No. | No. |
Which one should an engineer choose?
Choose based on what the next stage of the application needs:
- Need structured data? Use Structured Outputs.
- Need the model to request an operation? Use function calling.
- Need an operation followed by a structured report? Combine strict function calling with a structured final response.
- Need a high-risk operation? Add application authorization, policy checks, and possibly human approval regardless of the model’s schema compliance.
4. A production architecture
A reliable AI pipeline should place a deterministic application layer between model-generated data and consequential operations.
USER / SOURCE DATA
|
v
INPUT NORMALIZATION
|
v
MODEL ORCHESTRATOR
|
+----------+----------+
| |
v v
STRUCTURED OUTPUT FUNCTION CALL
RESPONSE FORMAT TOOL REQUEST
| |
v v
SCHEMA CHECK ARGUMENT CHECK
| |
v v
BUSINESS VALIDATION AUTHORIZATION
| |
| v
| TOOL EXECUTION
| |
| v
| RESULT CHECK
| |
+----------+----------+
|
v
APPLICATION LOGIC
|
v
DATABASE / API / UI
|
v
AUDIT + MONITORING
This architecture separates responsibilities:
- The model interprets context and proposes structured data or a tool request.
- The orchestrator manages model calls, tool definitions, response states, and workflow transitions.
- The validator checks types, required values, formats, and business constraints.
- The authorization layer determines whether the current user or service may perform the requested action.
- The tool executor performs an explicitly permitted operation.
- The application records outcomes, handles failures, and controls what happens next.
The model should never be treated as the authority for permissions, account ownership, payment status, or other security-sensitive facts. Those must come from trusted application state.
5. Implementing Structured Outputs
Start with a contract, not a prompt
A schema should represent the application’s actual data contract. It should not simply mirror whatever format is easiest for a model to generate.
Consider an invoice extraction task. The application wants to identify the invoice number, currency, total, and whether the document explicitly states that it has been paid.
A simplified JSON Schema could look like this:
{
"type": "object",
"properties": {
"invoice_number": {
"type": "string",
"description": "Invoice identifier exactly as printed."
},
"currency": {
"type": "string",
"enum": ["USD", "EUR", "GBP"]
},
"total": {
"type": "number",
"description": "Final invoice total, not subtotal."
},
"is_paid": {
"type": "boolean"
},
"uncertain_fields": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"invoice_number",
"currency",
"total",
"is_paid",
"uncertain_fields"
],
"additionalProperties": false
}
This example illustrates a strict object contract. The exact supported JSON Schema subset depends on the model provider and API mode. A schema accepted by a general JSON Schema validator is not automatically accepted by every model API.
Make uncertainty representable
A common design mistake is to force the model to invent a value when the source document is incomplete. A reliable extraction contract should give the model a way to express uncertainty.
For example, instead of requiring a guessed invoice total, the application can allow a nullable field and require an uncertainty reason. The application should then route unresolved records to review rather than silently treating guesses as facts.
The important design principle is that the schema should represent the valid states of the workflow, including missing or uncertain information.
Example request shape
The following is a conceptual Responses API request shape. The schema is shortened to keep the example readable; production code should use the complete schema and handle every response state.
{
"model": "YOUR_SUPPORTED_MODEL",
"input": [
{
"role": "user",
"content": "Extract the invoice fields from the supplied document."
}
],
"text": {
"format": {
"type": "json_schema",
"name": "invoice_extraction",
"strict": true,
"schema": {
"type": "object",
"properties": {
"invoice_number": {
"type": "string"
},
"currency": {
"type": "string",
"enum": ["USD", "EUR", "GBP"]
},
"total": {
"type": "number"
},
"is_paid": {
"type": "boolean"
}
},
"required": [
"invoice_number",
"currency",
"total",
"is_paid"
],
"additionalProperties": false
}
}
}
}
The model name and request options must be selected for the API and model version being deployed. The example is not a universal request format for every provider.
OpenAI notes that the first request using a schema can incur additional schema-processing latency, while subsequent requests with the same schema do not incur that same first-use cost. It also documents edge cases such as refusals and incomplete outputs that applications must handle. Read the implementation and edge-case guidance.
6. Implementing strict function calling
Define narrow, predictable tools
A tool should represent one understandable operation. Avoid giving a model a generic tool such as execute_sql, run_command, or call_any_api when a narrow application operation will do.
A better design is a tool such as lookup_order with a limited set of arguments:
{
"type": "function",
"name": "lookup_order",
"description": "Retrieve an order using its public order reference. Do not use this tool to modify an order.",
"strict": true,
"parameters": {
"type": "object",
"properties": {
"order_reference": {
"type": "string",
"description": "Public order reference supplied by the customer."
}
},
"required": [
"order_reference"
],
"additionalProperties": false
}
}
In OpenAI strict function mode, each object must set additionalProperties to false, and all declared properties must be required. A field that is logically optional can be represented with a nullable type where supported.
These are API-specific requirements, not universal rules for every JSON Schema implementation. Consult the provider’s current function-calling documentation before deploying a schema. OpenAI function calling guide.
The tool execution loop
Function calling is a multi-step application workflow. A typical sequence looks like this:
- Send the user’s request and available tool definitions to the model.
- Receive the model’s response.
- Determine whether the response contains a tool call, a final answer, a refusal, or an incomplete result.
- Validate the tool name and arguments.
- Check user identity, permissions, tenant scope, and business rules.
- Execute the permitted tool in application code.
- Return the tool result to the model or the workflow.
- Process the final response and record the outcome.
The model’s request is not authorization. Even if the arguments conform perfectly to the declared schema, the application must independently verify whether the operation is allowed.
Use application-controlled identity
Do not let the model decide which account it is allowed to access by trusting a user ID included in generated arguments.
A safer approach is to obtain the authenticated identity from the application’s session or verified token, then apply that identity to the query:
// Conceptual server-side pseudocode
function lookupOrder($arguments, $authenticatedUser) {
$reference = validateOrderReference(
$arguments['order_reference'] ?? null
);
if ($reference === null) {
throw new InvalidArgumentException(
'Invalid order reference'
);
}
return OrderRepository::findForUser(
$reference,
$authenticatedUser->id
);
}
The model supplies the reference. The application supplies the trusted user identity and enforces ownership. This prevents a model-generated identifier from becoming an authorization shortcut.
7. The validation layers that prevent failures
A reliable pipeline uses several distinct validation layers. They should not be collapsed into a single check.
| Layer | What it checks | Example failure |
|---|---|---|
| Transport and response state | API status, response completion, refusal, truncation. | Response stopped before completion. |
| Syntax and schema | JSON validity, required fields, types, allowed structure. | total is a string instead of a number. |
| Semantic validation | Whether values make sense in the domain. | Invoice total is negative when the workflow disallows it. |
| Authorization | Whether the authenticated principal can access the resource. | User requests another tenant’s order. |
| State validation | Whether the requested transition is currently allowed. | Attempt to refund an already refunded payment. |
| Execution and result validation | Whether the operation succeeded and returned an acceptable result. | External service times out or returns an unexpected status. |
Why schema validation is not enough
Imagine a model extracts an invoice total of 1250.50. The value is numeric, the field is present, and the response matches the schema.
But the actual invoice total is 1520.50. The response is structurally valid and factually wrong.
A second example: the model requests a refund using a valid payment identifier. The request conforms to the tool schema, but the authenticated user does not own the payment. The application must reject it.
This is why reliable systems validate the meaning and authority of data after checking its shape.
8. Designing for 99.9% pipeline reliability
A 99.9% reliability target sounds simple, but it must be defined precisely. Does it mean 99.9% of model responses match a schema? Or does it mean 99.9% of end-to-end requests produce a correct, authorized, successfully persisted result?
Those are different service-level objectives. For production systems, the second is the more meaningful measure.
Define the success condition
A pipeline request should count as successful only when the required stages have completed:
- The model response completed successfully.
- The expected response or tool arguments passed schema validation.
- Business rules accepted the values.
- Authorization checks passed.
- Any required operation completed.
- The result was persisted or delivered correctly.
If the model returns valid JSON but the database write fails, the end-to-end request has not succeeded.
Understand the reliability budget
For a simplified pipeline with independent stages, end-to-end success probability is the product of the success probabilities of those stages.
For example, if five stages each succeed 99.98% of the time:
0.9998 × 0.9998 × 0.9998 × 0.9998 × 0.9998
≈ 0.9990006
End-to-end success ≈ 99.90006%
This is an illustrative calculation, not a benchmark. Real failures are not always independent: a provider outage, invalid deployment, or shared database problem can affect several stages at once.
The lesson is that individual components need reliability budgets. A pipeline cannot assume that every component’s high availability automatically adds up to the desired end-to-end result.
Use bounded retries, not endless retries
Retrying every failure is not a reliability strategy. It can increase costs, amplify outages, and duplicate side effects.
A sensible retry policy distinguishes transient infrastructure failures from deterministic application failures:
- Potentially retryable: temporary network failures, rate limits, and selected service errors, subject to provider guidance.
- Not automatically retryable: authorization failures, invalid arguments, unsupported schemas, and business-rule violations.
- Requires special handling: timeouts during a write operation where the application cannot tell whether the operation completed.
Use bounded exponential backoff with jitter for eligible transient failures. Respect provider retry instructions and request identifiers. For writes, use an idempotency strategy so a retry does not accidentally repeat a payment, refund, or other side effect.
Keep schemas stable and versioned
A schema is an API contract. Changing a required field, changing a type, or altering an enumeration can break downstream consumers.
Version important schemas and test compatibility before rollout. Keep the model prompt, schema version, tool version, and application deployment version observable together. This makes it easier to identify whether a reliability regression came from a prompt edit, schema change, model change, or backend release.
9. Failure handling and recovery
A production workflow should explicitly model failure states. Do not treat every non-success response as malformed JSON.
| Failure | Recommended handling |
|---|---|
| Refusal | Handle as a refusal state. Do not parse it as normal business data or repeatedly retry without changing the request. |
| Incomplete or truncated response | Detect the response state and decide whether a bounded continuation or fresh request is appropriate. |
| Schema rejection | Fix the schema or request configuration. Do not retry the same invalid request unchanged. |
| Business validation failure | Return a clear validation result, request clarification, or route to human review. |
| Authorization failure | Reject the action and record the security event. Do not ask the model to bypass the permission check. |
| Tool timeout | Check whether the operation may already have completed before retrying a side effect. |
| External service failure | Apply bounded retries where safe, then use a controlled fallback or return an explicit failure. |
Make side effects idempotent
Consider a model that requests a payment operation. The payment service processes the request, but the connection drops before the application receives the response. A blind retry can charge the customer twice.
Use a server-generated idempotency key tied to the logical operation. Store the operation state and the external service’s reference so that a retry can safely retrieve the existing result rather than creating a second transaction.
The model should not generate or control the idempotency key. It is an application-level reliability mechanism.
10. Security and operational boundaries
Structured output does not make untrusted content safe. Function calling does not make a tool request authorized. A model can produce schema-valid arguments that still attempt to access sensitive data or trigger an inappropriate action.
Keep tool permissions narrow
- Give each tool only the permissions required for its purpose.
- Separate read operations from write operations.
- Require explicit application-side approval for high-impact actions.
- Apply tenant and user scoping in backend queries.
- Validate identifiers against trusted application state.
- Never expose raw database credentials, unrestricted shell access, or broad administrative capabilities to the model.
Treat model-generated values as untrusted input
Validate strings, URLs, identifiers, file paths, amounts, and enumeration values. Apply output encoding when displaying generated content. Use parameterized database queries. Enforce request size limits and timeouts.
For external URLs or network tools, add destination allowlists and server-side network controls. A schema that requires a URL string does not prevent server-side request forgery or access to internal network resources.
Keep sensitive data out of logs
Logs should help engineers reconstruct failures without becoming a second database of customer secrets. Redact access tokens, passwords, payment credentials, personal data, and confidential source documents where appropriate.
Record tool names, schema versions, request identifiers, validation outcomes, latency, and error categories. Use controlled access and retention policies for traces and debugging payloads.
11. Testing and measuring reliability
A system cannot claim 99.9% reliability because it uses strict mode. It needs evidence from representative workloads and a clearly defined success metric.
Build an evaluation dataset
Use a fixed, versioned collection of realistic inputs. Include normal cases, ambiguous cases, incomplete documents, adversarial text, unexpected formats, and edge conditions.
Each test case should have an expected outcome, including cases where the correct behavior is to refuse, request clarification, or send the record for review.
Measure each layer separately
| Metric | What it tells you |
|---|---|
| Schema conformance rate | How often completed model outputs satisfy the expected structure. |
| Semantic accuracy | How often extracted or generated values are factually correct. |
| Tool selection accuracy | How often the model selects the correct tool for the task. |
| Argument validity rate | How often tool arguments pass application validation. |
| Authorization rejection rate | How often unauthorized requests are correctly blocked. |
| Tool execution success rate | How often authorized operations complete successfully. |
| End-to-end success rate | How often the complete workflow reaches its defined successful state. |
| p50 / p95 / p99 latency | Typical and tail latency across the complete workflow and its individual stages. |
Test more than the happy path
- Missing or contradictory source data.
- Long inputs that approach context or output limits.
- Unexpected Unicode, escaped characters, and unusual numeric formats.
- Unknown identifiers and cross-tenant access attempts.
- Tool timeouts and duplicate delivery.
- Provider rate limits and temporary outages.
- Model or schema version changes.
- Prompt injection embedded in documents or retrieved content.
Calculate the end-to-end success rate
A simple operational metric is:
End-to-end success rate =
Successful completed workflows
-------------------------------- × 100
Eligible workflow attempts
Define the denominator carefully. Exclude only cases that are explicitly outside the service objective, not inconvenient failures. Track refusals, user cancellations, and human-review outcomes separately so the reliability number cannot be improved artificially by changing how failures are classified.
A 99.9% target permits roughly one failed eligible request per thousand. At one million eligible requests, that still means up to one thousand failures. For payments, identity, healthcare, or other high-impact workflows, the acceptable failure rate may need to be lower, with stronger human controls and independent verification.
12. Production checklist
- Define whether the model must return data or request an operation.
- Use a supported strict schema instead of relying on prompt-only JSON instructions.
- Represent missing and uncertain values explicitly.
- Version schemas and tool contracts.
- Handle refusals, incomplete responses, and API errors as separate states.
- Validate semantic and business rules outside the model.
- Derive user identity and permissions from trusted application state.
- Use narrow tools with least-privilege access.
- Make side-effecting operations idempotent.
- Apply bounded retries, timeouts, and controlled fallbacks.
- Log request IDs, schema versions, tool outcomes, and latency without exposing secrets.
- Run evaluation tests before changing prompts, schemas, models, or tools.
- Measure end-to-end success, not just valid JSON.
Build reliability around the contract
Structured Outputs and function calling address different parts of the same engineering problem. One constrains the shape of generated data; the other provides a controlled interface for requesting application operations. Both become more useful when surrounded by deterministic validation, authorization, idempotency, and observability.
The strongest design does not ask the model to guarantee the entire workflow. It gives the model a narrow, well-defined role and keeps critical decisions inside ordinary application code.
That is how an AI pipeline moves beyond “the JSON parsed” toward a measurable reliability target.
Frequently asked questions
Are Structured Outputs and function calling the same thing?
No. Structured Outputs constrains the format of model-generated responses. Function calling lets a model request that the application execute a defined tool. Strict function calling can also constrain tool arguments to a schema.
Does Structured Outputs eliminate JSON parsing errors?
In supported strict configurations, it constrains completed outputs to the supplied schema. Applications must still handle refusals, incomplete responses, transport failures, and provider-specific limitations. It also does not guarantee that the values are factually correct.
Should every AI application use function calling?
No. If the model only needs to extract, classify, or format information, a structured response may be sufficient. Function calling is appropriate when the model needs to request an application operation.
Can strict function calling make tool execution safe?
It can constrain tool names and arguments in supported configurations, but it does not authorize the operation. The application must enforce identity, permissions, tenant boundaries, business rules, and execution policies.
Can Structured Outputs guarantee 99.9% reliability?
No. It can improve structural consistency, but end-to-end reliability also depends on semantic accuracy, provider availability, authorization, backend services, persistence, and recovery. A 99.9% target must be measured across the complete workflow.
Is JSON mode enough for production AI pipelines?
JSON mode can ensure valid JSON in supported configurations, but it does not guarantee that the response follows a specific schema. When schema adherence is required, use a supported Structured Outputs configuration or validate and recover from non-conforming output.
Can different AI providers use the same JSON Schema?
They can share a common schema design, but supported JSON Schema features, request formats, strict-mode behavior, and response handling differ between providers. Test the exact schema against every model and API configuration in use.