Skip to content

TutorialsTutorial

Structured Outputs in TypeScript with the AI SDK and Zod

Stop parsing free-form model text. Define a Zod schema, request an object with Output.object and get validated, typed data back — plus the schema rules that keep strict providers happy.

AI Dev Hub Editorial

Automated quality gate

Published
Updated
Reading time
2 min read
  • 4 sources cited
  • 7 facts quote-verified

What you will build

A small extractor that turns messy release notes into a typed object — product, version, highlights and breaking changes — that is validated at runtime and typed at compile time. No regular expressions, no JSON.parse on free-form model text.

Prerequisites

  • A TypeScript project with the ai and zod packages.
  • A model provider configured for the AI SDK. The examples pass a model id string; swap in whichever provider or model you use.
bash
npm install ai zod

Step-by-step

1. Describe the shape with Zod

Zod lets you declare a schema once and get both a static TypeScript type and runtime validation 3. Field descriptions double as guidance for the model.

ts
import { z } from "zod";

export const releaseNote = z.object({
  product: z.string().describe("Product or library name"),
  version: z.string().describe("Version exactly as written, for example 2.4.0"),
  highlights: z.array(z.string()).max(5),
  breakingChanges: z.array(z.string()),
  requiresMigration: z.boolean(),
});

export type ReleaseNote = z.infer<typeof releaseNote>;

2. Generate the object

The AI SDK generates structured data through the output option of generateText: pass Output.object({ schema }) and the schema is used both to guide generation and to validate the result 1. Besides Zod, it also accepts Valibot and JSON Schema definitions 1.

ts
import { generateText, Output } from "ai";
import { releaseNote } from "./schema";

export async function extractReleaseNote(changelog: string) {
  const { output } = await generateText({
    model: "anthropic/claude-sonnet-5.5", // any model your provider supports
    instructions: "Extract release information. Use only facts stated in the text.",
    prompt: changelog,
    output: Output.object({ schema: releaseNote }),
  });
  return output; // typed as ReleaseNote
}

3. Stream partial objects for responsive UIs

For longer outputs, streamText accepts the same output option and exposes partialOutputStream, an async iterable of partial objects 1. Partial objects are not validated against the schema, because incomplete data may not match it yet 1 — validate the final object before you trust it.

ts
import { Output, streamText } from "ai";
import { releaseNote } from "./schema";

export async function streamReleaseNote(changelog: string, render: (partial: unknown) => void) {
  const { partialOutputStream } = streamText({
    model: "anthropic/claude-sonnet-5.5",
    prompt: changelog,
    output: Output.object({ schema: releaseNote }),
  });

  for await (const partial of partialOutputStream) {
    render(partial); // fields fill in as they arrive
  }
}

4. Handle failures explicitly

When the model cannot produce a valid object, the SDK throws NoObjectGeneratedError. The error carries the generated text, the finish reason and the underlying cause, which makes it useful for logging and targeted retries 2.

ts
import { NoObjectGeneratedError } from "ai";
import { extractReleaseNote } from "./extract";

export async function safeExtract(changelog: string) {
  try {
    return await extractReleaseNote(changelog);
  } catch (error) {
    if (NoObjectGeneratedError.isInstance(error)) {
      console.error("Model output did not match the schema", {
        finishReason: error.finishReason,
        text: error.text,
      });
      return null;
    }
    throw error;
  }
}

Schema rules that keep strict providers happy

Some providers enforce a strict subset of JSON Schema. OpenAI's Structured Outputs, for example, requires every field to be required and objects to disallow additional properties; to make a value optional you use a union with null 4. In Zod terms:

  • Prefer .nullable() over .optional() for values the model may not find.
  • Avoid open-ended objects such as z.record() in schemas you send to a model.
  • Keep nesting shallow, names descriptive, and use .describe() to state intent.

Troubleshooting

SymptomLikely causeFix
NoObjectGeneratedErrorOutput did not match the schemaRelax constraints, add .describe() hints, log error.text
The provider rejects the schemaOptional fields or open records under a strict modeUse .nullable(), remove records
Arrays come back emptyThe input simply lacks that dataThat may be correct — never force a model to invent values

Next steps

Frequently asked questions

Do I have to use Zod with the AI SDK?

No. The AI SDK also accepts Valibot and JSON Schema definitions. Zod is popular because one definition gives you both TypeScript types and runtime validation.

Are streamed partial objects validated?

No. Partial objects cannot be validated because incomplete data may not match the schema yet. Validate the final object before you rely on it.

Why use nullable instead of optional in schemas?

Strict structured-output modes, such as OpenAI's, require every field to be present. A nullable field stays required but can hold null when the model finds no value.

Sources

Every factual claim above cites one of these documents, retrieved and snapshotted by our research pipeline.

  1. S1
    Generating Structured Data
    AI SDKOfficialRetrieved Sep 30, 2026
  2. S2
    NoObjectGeneratedError
    AI SDKOfficialRetrieved Sep 30, 2026
  3. S3
    Zod: TypeScript-first schema validation
    ZodOfficialRetrieved Sep 30, 2026
  4. S4
    Structured model outputs
    OpenAIOfficialRetrieved Sep 30, 2026

AgentsNews

MCP TypeScript SDK v2.2.0 Enhances OAuth, List Calls

The Model Context Protocol TypeScript SDK v2.2.0 has been released, updating key client and server packages. This update introduces a mandatory expectedIssuer parameter for machine-to-machine OAuth providers and enhances list call behavior.

3 min readListen · 8 min