Structured Output
This example shows how to require schema-shaped final output without giving up the normal assistant response flow.
Use this when
- downstream code needs a typed object
- post-processing free-form text is too brittle
- you want strong validation at the final response boundary
What it shows
outputSchemaon the agent- the injected finalize
responsetool - parsed output on
result.output
Run it
bash
cd examples
npm run example:structured-outputCore code
ts
const ResultSchema = z.object({
title: z.string(),
bullets: z.array(z.string()).min(1),
});
const agent = createAgent({
model,
outputSchema: ResultSchema,
});
const res = await agent.invoke({
messages: [{ role: "user", content: "Generate 3 bullet points with a title about AI" }],
});End-to-end flow
- A Zod schema defines the final shape.
- The agent runs with
outputSchemaenabled. - The model produces a final response.
- The runtime parses it against the schema.
- Typed output becomes available on
res.output.
Why it matters
Structured output is the cleanest path when downstream code needs a predictable object instead of post-processing free-form text.
What to inspect
- the Zod schema definition
res.outputwhen parsing succeeds- fallback to
res.contentwhen parsing does not succeed
Production takeaway
If another service consumes the result, this pattern is usually better than asking the model for JSON and hoping it behaves.
Expected output
- when parsing succeeds, the console prints
Title:andBullets:fromres.output - when parsing fails, the script falls back to raw assistant content
Common failure modes
- the model returns shape-invalid JSON, so
res.outputis empty and onlyres.contentis available - your schema changes but the prompt still asks for the old shape