Reliable AI integrations need more than a prompt that says “return JSON.” This guide explains how to combine function calling, structured outputs, schema validation, and defensive error handling so an AI chatbot can return predictable data and select tools safely. Use the checklists when adding a new tool, changing a response contract, switching models, or troubleshooting malformed output in production.
Overview
Large language models produce text, while applications usually need a contract. A support workflow may require a ticket category and priority; a shopping assistant may need a product identifier and quantity; an internal agent may need to choose between searching a knowledge base and asking for human approval. In each case, the application should not rely on visually plausible prose.
Three related techniques help bridge that gap:
- Function calling or tool calling: the model selects a tool and proposes arguments for your application to execute.
- Structured outputs: the model is guided to produce data that follows a declared schema rather than an arbitrary text format.
- Validation: your application independently checks the model’s output before using it.
These techniques solve different problems. Tool calling helps an assistant interact with software. Structured outputs help it express a response in a known shape. Validation remains necessary because a schema does not establish that the information is true, safe, authorized, or appropriate for the requested operation.
A minimal tool contract
A tool definition should describe one narrow action, its required arguments, and the limits of those arguments. For example:
{
"name": "create_support_ticket",
"description": "Create a support ticket after the user has confirmed the summary and priority.",
"parameters": {
"type": "object",
"properties": {
"summary": { "type": "string", "minLength": 1 },
"priority": { "type": "string", "enum": ["low", "normal", "high"] },
"account_id": { "type": "string", "minLength": 1 }
},
"required": ["summary", "priority", "account_id"],
"additionalProperties": false
}
}The exact field names and SDK syntax differ across providers. The durable design principle is to keep the contract explicit, narrow, and versioned. Your server should still check authorization, account ownership, confirmation requirements, and business rules before executing the operation.
Structured output is not the same as JSON mode
A JSON mode or equivalent response setting generally asks for syntactically valid JSON. That is useful, but valid JSON can still have missing fields, unexpected values, incorrect types, or an object shape your application does not recognize. A schema-constrained response goes further by declaring the expected structure. Neither approach guarantees factual accuracy or correct reasoning, so application-level checks remain part of the design.
Checklist by scenario
Scenario 1: You need a predictable extraction response
Use a structured response when the model is extracting fields from text, classifying a request, producing a summary object, or returning a set of UI elements.
- Define the smallest useful object rather than mirroring every detail in the source text.
- Choose types deliberately: use numbers for numeric values, enums for controlled categories, and arrays for repeated items.
- Decide how uncertainty is represented. An optional field, a nullable field, or an explicit status such as
unknownmay be clearer than an invented value. - Set required fields only when the application truly cannot proceed without them.
- Reject unknown properties where the provider and schema system support that behavior.
- Validate the returned object with a server-side schema library or equivalent checks.
A useful extraction response might look like this:
{
"sentiment": "neutral",
"topics": ["delivery delay"],
"customer_requested_action": "status update",
"confidence_note": "The message describes a delay but does not state whether a refund is requested."
}The application should not treat the sentiment label as a business decision without considering the surrounding workflow and review rules.
Scenario 2: You need the model to call a tool
Use function calling when the assistant must retrieve data, perform a calculation, update a record, or start a controlled workflow.
- Describe the tool: include its purpose, arguments, constraints, and any confirmation requirement.
- Send the user request and available tools to the model.
- Inspect the response: determine whether it contains a normal assistant message or a tool call.
- Validate the arguments: check types, required fields, allowed values, and limits.
- Authorize the action: use the authenticated user and server-side permissions, not model-generated identity fields.
- Execute the tool outside the model.
- Return a sanitized tool result to the model if a user-facing explanation is needed.
- Log the decision path: record the tool name, validation result, execution result, and correlation identifier without storing unnecessary sensitive data.
A model may request a tool, but it should never be the final authority on whether that tool is allowed to run. Treat the model’s call as an untrusted request that enters your normal application controls.
Scenario 3: You need both a tool call and a final JSON response
Separate the phases. First, allow the model to select and call a tool. After the tool returns, make a second model request for the final structured response, or map the tool result directly into your application’s response object when no language generation is needed.
For example, a delivery assistant might use a tracking tool and then return:
{
"status": "in_transit",
"estimated_delivery": "2026-11-25",
"next_action": "wait_for_delivery",
"needs_human_review": false
}Do not let the model silently transform an error response into a successful status. Represent tool failures explicitly and decide whether the user should retry, provide more information, or contact a person.
Scenario 4: You are comparing provider approaches
Provider APIs use different names and capabilities. Before committing to an implementation, compare the behavior you actually need rather than relying on a feature label.
| Approach | Best fit | What to verify | Application responsibility |
|---|---|---|---|
| Plain prompting for JSON | Experiments and low-risk prototypes | Whether the model emits extra text, missing fields, or invalid syntax | Parse, validate, retry, and handle failure |
| JSON mode or equivalent | Responses that must be syntactically JSON | Whether schema constraints, enums, and nested objects are supported | Validate the complete object and business rules |
| Schema-constrained structured output | Stable application contracts | Supported schema features, refusal behavior, incomplete responses, and model limits | Version schemas, validate, and monitor edge cases |
| Function or tool calling | Retrieval, actions, and workflow steps | Argument validation, multiple calls, parallel calls, and tool-result handling | Authorize and execute every call safely |
Check the current provider documentation and SDK behavior before implementation. Feature names, supported schema keywords, response shapes, and model-specific limitations can change.
What to double-check
Schema design
- Are required fields genuinely required?
- Are enums limited to values your code handles?
- Can the schema represent “not found,” “unknown,” or “needs clarification” without forcing a guess?
- Are arrays bounded to prevent unexpectedly large responses?
- Does the schema have a version identifier or migration plan?
Validation and execution
- Does validation happen on your server after the API response is received?
- Are dates, currency values, identifiers, and quantities checked for business validity?
- Are tool arguments scoped to the authenticated user or tenant?
- Are high-impact actions paused for confirmation or human approval?
- Are timeouts, retries, duplicate requests, and partial failures handled?
Testing
Build a small test set before changing a schema or model. Include ordinary requests, missing information, ambiguous wording, unexpected languages, long inputs, prompt-injection attempts, tool failures, and requests for actions the user is not allowed to perform. Assert both the output shape and the application’s decision. A response can pass schema validation and still be unsafe or operationally incorrect.
For production diagnostics, pair this work with a broader AI chatbot reliability runbook and the AI chatbot security checklist.
Common mistakes
Using a prompt as the only validator
Instructions such as “return only valid JSON” can improve consistency, but they are not an enforcement layer. Parse and validate independently, then return a controlled error or retry when the contract is not met.
Making one tool do everything
A broad tool such as run_any_action is difficult to authorize, test, and audit. Prefer small tools with clear permissions and narrow arguments. This also makes it easier to identify which step failed.
Confusing valid shape with correct content
A correctly shaped account number can still belong to the wrong customer. A valid date can still be impossible for the requested workflow. Add domain checks after schema validation.
Retrying without an idempotency strategy
If a timeout occurs after a write operation, a blind retry may create a duplicate. Use idempotency keys or a server-side operation record where appropriate, and make retry rules specific to the tool.
Ignoring refusal and incomplete responses
Models and providers may return a refusal, truncation, an interrupted generation, or a provider error instead of the expected object. Handle these outcomes explicitly; do not pass them to a JSON parser as though they were ordinary success responses.
For schema patterns and recovery techniques, see Structured JSON Outputs from LLMs. For prompt-level diagnosis, use the prompt debugging guide.
When to revisit
Review your function calling and structured-output implementation whenever the underlying inputs change. That includes changing models, providers, SDK versions, system prompts, tool descriptions, schema fields, authentication rules, or downstream APIs. Also revisit it before a seasonal planning cycle or any period when request volume, data types, or business policies are likely to shift.
Use this short release checklist:
- Run the representative test set against the new model or schema.
- Compare validation failures, tool-selection errors, latency, and token usage with the previous version.
- Test malformed, incomplete, unauthorized, and duplicate tool requests.
- Confirm that logs and alerts still identify the tool, schema version, and failure category.
- Deploy behind a measured rollout or feature flag when the workflow is important.
- Record the change and define a rollback path.
Keep tool definitions, schemas, validators, and tests close together in version control. If your assistant also uses a system prompt, review the system prompt examples and reusable template. For multi-step assistants, compare the approval and memory considerations in AI agent frameworks. The practical goal is not to make the model infallible. It is to make every uncertain, malformed, unauthorized, or failed response visible and controllable before it reaches your users or systems.