All articles

English

October 25, 20265 min read

Structured LLM Outputs: Schemas, Validation, and Safe Application Boundaries

Move AI output into application logic safely: small schemas, explicit uncertainty, runtime validation, semantic checks, and server-owned authorization before any action.

Portrait of Tran Kim Dat

Tran Kim Dat

Software Engineer

The AI SDK developer tools interface from Vercel's AI SDK 6 article, used to inspect model calls and their outputs.
The AI SDK developer tools interface from Vercel's AI SDK 6 article, used to inspect model calls and their outputs. Image: Vercel. Original source - Full-size image

When software consumes an AI response, a convincing paragraph is rarely the right interface. The application needs a bounded result it can inspect: a category, extracted fields, evidence references, or a proposed next action. Structured output makes that interface easier to validate, but it does not turn a prediction into an authorized decision.

Imagine a support tool that proposes which team should receive a ticket. A response can satisfy a JSON schema and still select the wrong team. It can also name a real account that the current operator cannot access. These are separate problems, and a robust integration gives each one an explicit check.

Design the smallest useful contract

Start from the decision the surrounding software needs to make. If the application only needs a route and a reason, avoid asking for a large object full of speculative metadata. Every field adds another thing to interpret, store, and keep consistent. Constrain stable categories with enums and give explanatory text a clear size bound.

Model missing information directly. A nullable field should mean something specific, such as not present in the supplied evidence. If the system needs clarification, represent that outcome explicitly instead of forcing the model to choose a department. A schema that has no room for uncertainty can produce well-formed guesses.

Provider-native structured output can constrain generation to supported schemas. Check the provider's current feature support and schema subset before adopting a complex contract. Keep the application schema versioned and test it with the exact provider configuration you deploy.

Validate at the application boundary

TypeScript types disappear at runtime. Casting an unknown response to a type does not check it. Parse the completed response with a runtime schema before using it. Keep transport errors, refusals, truncated generation, invalid structure, and successful results as distinct outcomes; they need different product responses.

This example uses Zod to validate an application-owned routing proposal after the provider adapter has produced a completed JSON value. The adapter itself must handle HTTP failures and provider-specific stop conditions. The object remains a proposal until the application applies its policy.

import { z } from "zod";

const RoutingProposal = z.object({
  schemaVersion: z.literal(1),
  outcome: z.enum(["route", "needs_clarification"]),
  department: z.enum(["billing", "technical", "sales"]).nullable(),
  reason: z.string().min(1).max(400),
}).strict().superRefine((value, context) => {
  const hasDepartment = value.department !== null;
  if ((value.outcome === "route") !== hasDepartment) {
    context.addIssue({
      code: "custom",
      message: "Only routing outcomes may select a department.",
    });
  }
});

export function parseProposal(value: unknown) {
  return RoutingProposal.safeParse(value);
}

Separate structure from meaning and authority

There are three boundaries. Structural validation asks whether the value follows the contract. Semantic validation asks whether it is consistent with the task and available evidence. Authorization asks whether the authenticated actor is permitted to perform the resulting operation. Passing the first boundary proves nothing about the other two.

For extraction, semantic checks may include whether a referenced document exists, whether an amount appears in the source, and whether a date is supported. For routing, they may include whether the selected department handles that product. Resolve identifiers against trusted application data instead of trusting model-generated labels.

Keep tenant identity, actor identity, permission scopes, and protected state on the server. If a model proposes an account identifier, the server must still look it up within the actor's allowed scope. Never accept an isAdmin flag or a permission list from a generated object as evidence of access.

Make failure a normal part of the contract

Anthropic's structured-output documentation calls out cases such as refusal and output truncation. Design the provider adapter to inspect completion conditions before assuming that the payload is a usable object. A response that stopped halfway through is not a successful result merely because some fields were received.

Bound repair attempts. Retrying the same invalid request indefinitely hides a contract mismatch and increases cost. A small retry budget may be appropriate for a transient failure, while an unsupported schema needs a configuration fix. After the budget is exhausted, surface a useful failure state or send the item for review.

Do not feed unlimited raw validation errors and private data back into a repair prompt. Return only the minimal structural feedback required. Record failure categories and schema versions so you can distinguish a model-quality problem from a broken integration without logging full customer content.

Keep side effects behind ordinary application policy

Treat a generated action as an instruction candidate. The application should validate its resource scope, compare it with current state, and require confirmation when the product's policy calls for it. For important writes, use an idempotency key and record the accepted operation so a retry cannot duplicate the effect.

For example, a ticket-routing proposal could become a preview showing the selected department and explanation. The server commits the reassignment only after verifying that the ticket is still eligible and the operator can modify it. The model never receives the authority to redefine that rule.

Test the contract beyond the happy path

  • Missing, unknown, extra, and contradictory fields.

  • Refusal, timeout, interruption, and provider response changes.

  • Valid identifiers outside the current tenant or permission scope.

  • Structurally correct answers unsupported by the source.

  • Duplicate requests and stale state at the time of a write.

I would adopt structured output early for any AI result that enters application logic. The benefit comes from making the interface inspectable. The remaining engineering work is still familiar: validate input, verify meaning, enforce permissions, control writes, and expose a recoverable failure path.

Continue reading

Design bounded agent tools and stopping conditions

Primary sources

Anthropic: structured outputs, schema support, and invalid-output cases

Zod: parsing unknown values and handling validation failures

Continue reading

More field notes.

View all articles
Langfuse experiments table showing selected runs, model metadata, latency and error counts.
EnglishOct 25, 2026

LLM Evaluation as a Release Gate: From Good Demos to Regression Tests

Build an evaluation process that catches AI regressions before release: representative datasets, deterministic checks, calibrated reviewers, and explicit quality budgets.

AI · developer-tools · evaluation · reliability · testing

Read article
Archival v0 chat interface from Vercel's September 2024 AI SDK 3.4 article; an example of an AI SDK-powered interface.
EnglishOct 25, 2026

Streaming AI Interfaces: Cancellation, Recovery, and Honest Progress

A streaming response needs more than a typing effect. Design explicit states, useful stop and retry behavior, durable message identity, and accessible progress feedback.

AI · React · UX · architecture · reliability

Read article
The retrieval-augmented generation pipeline published in Neon's January 2025 pgrag article.
EnglishOct 25, 2026

RAG with PostgreSQL: Retrieval, Permissions, and Answers You Can Verify

A practical design for PostgreSQL-backed RAG: versioned ingestion, permission-aware retrieval, useful citations, and separate tests for search quality and answer quality.

AI · PostgreSQL · RAG · architecture · security

Read article

Have a product worth building carefully?

Start a conversation