Treat LLM Output Like an API Contract, Not Friendly JSON
Once model output drives code, valid JSON is only the first requirement. A practical TypeScript and Python pattern for schema validation, domain invariants, bounded repair, and explicit failure.
On this page
The dangerous LLM response is not always malformed.
Sometimes it is beautifully valid JSON that your application should never have accepted.
That difference matters once model output stops being text for a person to read and becomes input to another system. A parser only tells you that braces and commas are in the right places. It does not tell you that an enum is allowed, a date is sensible, an ID belongs to the right tenant, or an action is safe to execute.
I treat structured model output the same way I treat an external API response: untrusted data crossing a boundary.
The example in this article is a deployment assistant. It reads a natural-language change request and proposes a structured deployment plan. The model is allowed to *propose* an environment, service, rollout mode, and risk level. Application code decides whether that proposal satisfies the contract.
JSON syntax is the smallest part of the contract
Imagine downstream code expects this shape:
{ "service": "billing-api", "environment": "staging", "rollout": "canary", "risk": "medium", "requiresApproval": false}Several outputs can parse successfully and still be unusable:
environmentis"stage"while the application only knowsstaging;requiresApprovalis the string"false"instead of a boolean;rolloutis omitted;- the service exists, but not in this tenant;
- production is selected while
requiresApprovalis false; - the model invents a service that was never in the input.
A provider's schema-constrained output feature is worth using because it removes a large class of shape errors. But I still validate at my own boundary. Provider guarantees can differ by model and feature, and a structurally valid response can still violate application rules.
The application owns the contract because the application owns the consequences.
One schema should drive both typing and validation
In TypeScript, Zod gives me a runtime validator and a useful inferred type from the same definition.
import { z } from "zod";const DeploymentPlanSchema = z.object({ service: z.string().min(1).max(100), environment: z.enum(["development", "staging", "production"]), rollout: z.enum(["all-at-once", "canary", "blue-green"]), risk: z.enum(["low", "medium", "high"]), requiresApproval: z.boolean(),});type DeploymentPlan = z.infer<typeof DeploymentPlanSchema>;Python with Pydantic serves the same role:
from enum import Enumfrom pydantic import BaseModel, Fieldclass Environment(str, Enum): DEVELOPMENT = "development" STAGING = "staging" PRODUCTION = "production"class Rollout(str, Enum): ALL_AT_ONCE = "all-at-once" CANARY = "canary" BLUE_GREEN = "blue-green"class Risk(str, Enum): LOW = "low" MEDIUM = "medium" HIGH = "high"class DeploymentPlan(BaseModel): service: str = Field(min_length=1, max_length=100) environment: Environment rollout: Rollout risk: Risk requires_approval: boolThe model can receive JSON Schema generated from these definitions where the provider supports it. The same schema is then applied again after the response comes back.
That second validation is not redundant. It is the point where untrusted model output becomes trusted application data.
Put parsing behind one gateway
I do not want every feature doing its own JSON.parse() and hoping the result is right.
A gateway gives the system one place to parse, validate, record failures, and decide whether repair is allowed.
class StructuredOutputError extends Error { constructor( message: string, public readonly details?: unknown, ) { super(message); }}function parseDeploymentPlan(raw: string): DeploymentPlan { let value: unknown; try { value = JSON.parse(raw); } catch (error) { throw new StructuredOutputError("Model returned invalid JSON", error); } const parsed = DeploymentPlanSchema.safeParse(value); if (!parsed.success) { throw new StructuredOutputError( "Model output failed deployment-plan schema", parsed.error.issues, ); } return parsed.data;}Python:
import jsonfrom pydantic import ValidationErrorclass StructuredOutputError(RuntimeError): def __init__(self, message: str, details: object | None = None): super().__init__(message) self.details = detailsdef parse_deployment_plan(raw: str) -> DeploymentPlan: try: value = json.loads(raw) except json.JSONDecodeError as exc: raise StructuredOutputError("Model returned invalid JSON", str(exc)) from exc try: return DeploymentPlan.model_validate(value) except ValidationError as exc: raise StructuredOutputError( "Model output failed deployment-plan schema", exc.errors(), ) from excDownstream code receives a DeploymentPlan, not an arbitrary dictionary and not raw model text.
That is a small architectural choice with a large payoff. The rest of the service can stop thinking about JSON quirks.
Schema-valid is not domain-valid
This is the part that gets missed.
The following object passes the schema:
{ "service": "payments-api", "environment": "production", "rollout": "all-at-once", "risk": "high", "requiresApproval": false}It is structurally correct and operationally unacceptable.
Domain invariants belong in deterministic code after schema validation.
type DeploymentContext = { allowedServices: Set<string>;};function validateDeploymentPolicy( plan: DeploymentPlan, context: DeploymentContext,): DeploymentPlan { if (!context.allowedServices.has(plan.service)) { throw new StructuredOutputError("Unknown or unauthorized service"); } if (plan.environment === "production" && !plan.requiresApproval) { throw new StructuredOutputError( "Production deployments must require approval", ); } if ( plan.environment === "production" && plan.rollout === "all-at-once" && plan.risk !== "low" ) { throw new StructuredOutputError( "Risky production changes cannot use all-at-once rollout", ); } return plan;}The Python version is equally boring, which is exactly what I want from a safety rule:
@dataclass(frozen=True)class DeploymentContext: allowed_services: set[str]def validate_deployment_policy( plan: DeploymentPlan, context: DeploymentContext,) -> DeploymentPlan: if plan.service not in context.allowed_services: raise StructuredOutputError("Unknown or unauthorized service") if plan.environment is Environment.PRODUCTION and not plan.requires_approval: raise StructuredOutputError("Production deployments must require approval") if ( plan.environment is Environment.PRODUCTION and plan.rollout is Rollout.ALL_AT_ONCE and plan.risk is not Risk.LOW ): raise StructuredOutputError( "Risky production changes cannot use all-at-once rollout" ) return planThe model is good at interpreting intent. It is not where I want to encode the rule that production always requires approval.
Repair only when the error is repairable
Some failures deserve a second model call. Others do not.
A missing enum field is repairable. A temporary formatting mistake is repairable. “This user is not authorized to deploy payments-api” is not something I want the model to talk its way around.
That gives me two error classes:
representation failures can be sent back for bounded repair;
policy failures stop the workflow.
A repair loop should include the actual validation issues and a hard attempt limit.
async function generatePlan( callModel: (prompt: string) => Promise<string>, initialPrompt: string,): Promise<DeploymentPlan> { let raw = await callModel(initialPrompt); for (let attempt = 0; attempt < 2; attempt += 1) { try { return parseDeploymentPlan(raw); } catch (error) { if (!(error instanceof StructuredOutputError) || attempt === 1) { throw error; } raw = await callModel( `Repair the previous output so it matches the required schema.\n` + `Validation details: ${JSON.stringify(error.details)}\n` + `Previous output: ${raw}`, ); } } throw new StructuredOutputError("Unreachable repair state");}Notice what this function does *not* do: it does not return a partially populated fallback object to keep the pipeline moving.
For workflow data, a loud failure is often much cheaper than corrupted state.
Keep model uncertainty visible in the schema
Schemas become dangerous when they force certainty the source does not contain.
If the user asks, “deploy the API later tonight,” the exact time may not be known. Making scheduledAt a required timestamp encourages the model to invent one.
Model uncertainty explicitly:
const ScheduleSchema = z.discriminatedUnion("kind", [ z.object({ kind: z.literal("immediate") }), z.object({ kind: z.literal("scheduled"), at: z.string().datetime() }), z.object({ kind: z.literal("needs-clarification"), reason: z.string() }),]);A needs-clarification state is often more valuable than another field marked required.
The same idea applies to extraction systems. If a document does not contain a value, null or an explicit unknown is more honest than pressure to fill every key.
Do not log raw structured output by default
A validation failure is tempting to log in full. That raw response may contain customer input, document text, generated personal data, or secrets copied from context.
I prefer to log:
- request/run ID;
- schema version;
- provider/model identifier;
- validation issue paths;
- response size;
- a redacted or hashed sample where genuinely useful.
The goal is to debug the contract without turning observability into a second data store.
Version the contract
Once several services consume structured AI output, schema changes become API changes.
Renaming requiresApproval to approvalRequired can break a worker just as surely as changing a REST response.
I usually make the schema version explicit in telemetry and, for durable workflows, in stored state. If a run is resumed tomorrow, I want to know which contract produced its existing data.
That also makes evaluation cleaner. A regression can be tied to a schema or prompt version instead of “something changed recently.”
Where I would stop adding machinery
A one-off assistant that generates text for a human to edit does not need all of this. If no downstream code acts on the result, a lightweight schema may be enough.
The stricter pattern becomes useful when model output changes application state, enters a database, triggers a workflow, selects a tool, controls permissions, or affects money.
At that point, structured output is not a formatting preference. It is an interface.
I want that interface to have the same properties I expect from any production API boundary: a defined shape, runtime validation, deterministic business rules, observable failures, versioning, and no silent coercion into something that merely looks close enough.
LLMs are probabilistic. The contract around them does not have to be.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article