# 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.

AI developers · Part 02: OpenAI API · Card 5 of 9 · Last updated 2026-10-13

## 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.ts`

```typescript
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.

## Related concepts

- [Who reads the answer?](https://studyvisually.com/learn/tech/ai-developers/openai-api/human-or-code-reader)
- [The OpenAI SDK](https://studyvisually.com/learn/tech/ai-developers/openai-api/openai-client)
- [Chat completion](https://studyvisually.com/learn/tech/ai-developers/openai-api/chat-completion)
- [Messages array](https://studyvisually.com/learn/tech/ai-developers/openai-api/messages-array)

Web page: https://studyvisually.com/learn/tech/ai-developers/openai-api/structured-output
Study this card in the app: https://studyvisually.com/app/learn?category=ai-developers&card=structured-output
