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
aiandzodpackages. - A model provider configured for the AI SDK. The examples pass a model id string; swap in whichever provider or model you use.
npm install ai zodStep-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.
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.
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.
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.
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
| Symptom | Likely cause | Fix |
|---|---|---|
NoObjectGeneratedError | Output did not match the schema | Relax constraints, add .describe() hints, log error.text |
| The provider rejects the schema | Optional fields or open records under a strict mode | Use .nullable(), remove records |
| Arrays come back empty | The input simply lacks that data | That may be correct — never force a model to invent values |
Next steps
- Structured output is only as trustworthy as its inputs. Our editorial policy explains how every extracted fact on this site is checked against its source.
- Streaming the result to a browser? Compare Server-Sent Events and WebSockets.