Loading lesson…
Force an LLM to return JSON that matches a schema. Zod + tool-use or JSON mode makes this reliable.
Asking an LLM for JSON and parsing the string is a trap. Use the AI SDK's generateObject with a Zod schema — you get validated, typed data every time.
import { generateObject } from "ai"; import { anthropic } from "@ai-sdk/anthropic"; import { z } from "zod"; const ExtractSchema = z.object({ people: z.array( z.object({ name: z.string(), role: z.string().optional(), email: z.string().email().optional(), }) ), summary: z.string().max(240), }); export async function extract(text: string) { const { object } = await generateObject({ model: anthropic("claude-opus-4-7"), schema: ExtractSchema, prompt: `Extract people mentioned and a short summary from:\n\n${text}`, }); // object is fully typed from the schema console.log(`${object.people.length} people found`); return object; }generateObject validates the response against the schema and retries on failure. You get a typed object, not a string.import OpenAI from "openai"; import { zodResponseFormat } from "openai/helpers/zod"; const client = new OpenAI(); const r = await client.responses.parse({ model: "gpt-5", input: [{ role: "user", content: "Extract a person from: Ada Lovelace, mathematician" }], text: { format: zodResponseFormat(z.object({ name: z.string(), role: z.string() }), "person") }, }); console.log(r.output_parsed); // { name: "Ada Lovelace", role: "mathematician" }OpenAI's helpers.zod converts Zod to the JSON schema the API wants. parse() returns typed data.Understanding "Structured Output With Zod" in practice: AI-assisted coding shifts work from syntax recall to design thinking — models handle boilerplate so you focus on architecture. Force an LLM to return JSON that matches a schema. Zod + tool-use or JSON mode makes this reliable — and knowing how to apply this gives you a concrete advantage.
The big idea: never parse JSON by hand from an LLM. Zod + generateObject turns the model into a typed function.
8 questions · take it digitally for instant feedback at tendril.neural-forge.io/learn/quiz/end-progx-structured-output-zod-creators
What is the main idea of "Structured Output With Zod"?
Which concept is most central to "Structured Output With Zod"?
Which use of AI fits this topic best?
What should a careful learner remember about "Describe fields with .describe()"?
You want to use AI after this lesson. What is the safest next step?
How should AI output about Zod be treated?
Name one way to verify an AI answer about Zod.
Which action would help you apply "Structured Output With Zod" responsibly?