StudyVisuallyStart studying
Part 02 · OpenAI API · Card 5 of 9

Structured output

Force the reply to match a JSON schema, so your code gets typed data instead of a paragraph it has to guess at.

Last updated

Analogy

Request validation with Zod, but pointed at the model. It may only answer in the shape you accept, like a form with dropdowns instead of free text.

Code example

structured.tsTypeScript
import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";
const PrSummary = z.object({
type: z.enum(["bug", "feature", "refactor"]),
risk: z.enum(["low", "medium", "high"]),
summary: z.string(),
});
const res = await client.chat.completions.parse({
model: "gpt-4o-mini",
messages: [{ role: "user", content: `Classify this PR: ${diff}` }],
response_format: zodResponseFormat(PrSummary, "pr_summary"),
});
const data = res.choices[0].message.parsed; // { type, risk, summary }

In an agent

Use it whenever code, not a human, reads the answer: routing decisions, classifications, final reports.

Practice

Flashcards

  • What is structured output?A model reply forced to match a JSON schema, so code can parse it safely.

Questions people ask

What is structured output in the OpenAI API?

It forces the model's reply to match a JSON schema you provide. With the SDK you can write the schema in Zod and use zodResponseFormat, then read typed, parsed data instead of a paragraph. Your code no longer has to guess where the answer is or handle text in an unexpected shape.

When should I use structured output instead of plain text?

Whenever code reads the answer rather than a person. Classifications, routing decisions, extracted fields and final reports for another system should all be structured. Plain text is fine for a reply shown in a chat window. Inside agents most outputs feed later steps, so structured output is usually the default.