The Schema Contract: Strict Structured Outputs That Keep Agent Tool Calls and Final Answers Predictable

Strict schema-enforced outputs eliminate parse failures in production agents. Treat the JSON Schema as the contract between model and code so tool arguments and final answers arrive typed and complete.

Mapki

Mapki

Nov 15, 2026•8 min read
Share:
Mapki
Custom Agents

The Schema Contract: Strict Structured Outputs That Keep Agent Tool Calls and Final Answers Predictable

Production agents fail in two places that look identical from the outside: the model produces something that looks right but is not, or it produces something the surrounding code cannot even parse. The second class of failure is almost entirely preventable.

When an agent decides to call a tool, the arguments it emits become the input to real systems. When it returns a final answer, that answer becomes the input to the next service, the database, or the user interface. Both moments need a contract. The contract is a JSON Schema enforced at generation time, not a hope that the model will remember to follow the format you described in the prompt.

Why prompting for JSON is not a contract

Asking a model to “respond in JSON” or “use this shape” works in demos and collapses under load. Parse errors, extra text, missing fields, wrong types, and markdown fences all appear once real traffic arrives. JSON mode (valid JSON, any shape) removes the fences and the syntax errors but still lets the model invent fields, omit required ones, or return the wrong types.

Strict structured outputs close the gap with constrained decoding. The provider builds a grammar from your schema and masks any token that would violate it. The model cannot emit a non-conforming character. Field names match, types match, required properties are present, and enums stay inside the allowed set. Reported schema-adherence rates move from the 70–90 % range of careful prompting into the high 99 % range on supported models.

OpenAI’s strict mode (json_schema with strict: true) and Anthropic’s strict tool use plus JSON outputs both implement this. The same discipline applies whether you are extracting a ticket, deciding the next tool, or returning a typed final state. Teams that adopted constrained decoding in 2025 and 2026 report the largest drop in tool-call failures coming from format issues rather than reasoning issues.

Two places the schema lives

Use the schema in two distinct places:

  1. Tool arguments. Every tool definition carries an input schema. Set strict mode so the arguments the model produces are guaranteed to match before your code ever sees them. This removes the most common source of “tool call failed, retry” loops and the wasted tokens that follow.
  2. Final or intermediate answers. When the agent must hand a structured object back to the caller or to the next step, use the provider’s response-format / output_config mechanism so the answer itself is typed.

Keep the two schemas focused. Deep nesting and many optional fields raise the chance of truncation or of the model filling fields it should have left empty. Prefer flat or shallow objects, enums over free strings, and nullable fields where “I don’t know” is a valid answer. A schema that is too strict forces invention; a schema that is too loose recreates the parse problem.

A practical implementation pattern

Define the shape once, with a library that can emit both the JSON Schema and a validated Python or TypeScript object.

from pydantic import BaseModel, Field
from typing import Literal
from openai import OpenAI

class ToolDecision(BaseModel):
action: Literal["lookup_order", "issue_refund", "escalate"]
order_id: str | None = None
reason: str
confidence: float = Field(ge=0.0, le=1.0)

client = OpenAI()
response = client.responses.parse(
model="gpt-4o-2024-08-06",  # or later model that supports strict
input=[
{"role": "system", "content": "Decide the next action for the support agent."},
{"role": "user", "content": "Customer says the package arrived damaged."}
],
text={"format": {"type": "json_schema", "name": "tool_decision", "strict": True, "schema": ToolDecision.model_json_schema()}}
)
decision: ToolDecision = response.output_parsed

For tool calling itself, set "strict": true on the tool definition. Anthropic’s equivalent is strict: true on the tool plus output_config.format when you also need a structured final message. In both cases, validate once more in application code. Constrained decoding removes structural failures; it does not remove the need for business-rule checks.

The same pattern works in TypeScript with Zod or in any language that can emit a JSON Schema. Keep the schema definition next to the code that consumes it so the two cannot drift.

What the schema still cannot guarantee

Shape is solved. Content is not.

  • Semantic correctness. The model can return a perfectly typed but wrong order ID or an invented confidence score. Pair the schema with outcome checks and sampled evaluation. A typed wrong answer is still wrong.
  • Truncation. If the response hits the token limit mid-object, the JSON may be incomplete. Always inspect the finish / stop reason before parsing. Both OpenAI and Anthropic note that truncated responses may not match the schema.
  • Refusals. Safety refusals or “I don’t know” answers can still appear. Design the schema with an explicit escape (nullable fields, an “unknown” enum value, or a separate refusal object) so the model has a legal way to decline instead of inventing a value to satisfy the grammar.
  • Provider differences. OpenAI strict mode requires additionalProperties: false and every property listed in required. Anthropic strips some constraint keywords into the description and has limits on recursion and certain numeric constraints. Test the exact schema on the exact model you will run in production.

Treat the schema as the structural contract and keep a second, smaller set of deterministic checks for the business invariants that matter (amount ranges, existence of referenced records, permission scopes).

Production checklist

  • Name the contract. Every tool and every final-answer type has a single, versioned schema stored with the code.
  • Enable strict mode by default. Fall back to non-strict only when the schema is intentionally flexible or the model does not support it.
  • Keep schemas shallow. Prefer enums, required fields, and explicit nulls over deep nesting. Aim for objects that fit comfortably inside a few hundred tokens.
  • Validate in code anyway. Parse into a typed object (Pydantic, Zod, etc.) and reject on business-rule failure even after the provider has enforced the shape.
  • Log validation and truncation. Count schema failures, finish-reason anomalies, and retries. They should be near zero after strict mode is on. A rising count is an early signal that a model update or prompt change has broken the contract.
  • Give the model an exit. Include an unknown / decline path so it does not invent values to satisfy the schema.
  • Version and test. When you change a schema, run the existing regression set before the new version reaches production. Include both happy-path and refusal cases.
  • Combine with observability. Attach the schema version and the parse result to every trace so you can later correlate shape failures with quality scores or cost spikes.

When not to use it

Do not force a strict schema on free-form creative writing, on exploratory research steps where the shape is not yet known, or on steps whose only job is to return prose the user will read. Use it at every boundary where code will consume the result. The cost of an extra schema compilation on the first request is small compared with the cost of a single malformed tool call that reaches a payment API or a customer-facing ticket.

Multi-provider and local models

The same idea travels. OpenAI and Anthropic expose it natively. Gemini offers response schemas. For open-weight models running on vLLM or similar, libraries such as Outlines or XGrammar provide constrained decoding. Instructor and similar wrappers add retry-on-validation on top of any provider. Choose the strictest option the model supports, then keep the application-level typed parse as the last line of defense.

The difference between an agent that works in the demo and one that stays up in production is often just this: the places where the model’s output becomes input to another system are governed by a schema the model cannot violate. Everything else—better prompts, larger context, stronger models—improves the quality of the values inside the schema. The schema itself removes the class of failures that used to crash the surrounding code before the values could even be judged.

References & Community Insights

  • OpenAI Structured Outputs guide and the original constrained-decoding approach demonstrated at DevDay.
  • Anthropic strict tool use and JSON outputs documentation.
  • Practitioner analyses of schema-constrained generation reducing tool-call and parse failures (AgentMarketCap 2026, Boundev, and related production guides).
  • LangChain structured-output strategies and Pydantic patterns commonly used in production agent loops.
  • Community discussions on production agent reliability that repeatedly identify parse and type failures as the first, most fixable class of errors before deeper evaluation work begins.

Want to implement this in your business?

Mapki designs bespoke AI agents, custom workflow automations, and tool-agnostic integrations tailored specifically to your existing ERP, CRM, and databases.

Tags:AI AgentsStructured OutputsTool CallingProduction ReliabilityJSON SchemaAgent Evaluation