typescriptintermediate

OpenAI Structured Output with Zod

Force GPT-4o to return valid JSON matching a Zod schema using response_format structured output.

typescript
import OpenAI from "openai";
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";

const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

const PersonSchema = z.object({
  name:     z.string(),
  age:      z.number(),
  skills:   z.array(z.string()),
  location: z.string(),
});

type Person = z.infer<typeof PersonSchema>;

export async function extractPerson(text: string): Promise<Person> {
  const res = await client.beta.chat.completions.parse({
    model: "gpt-4o",
    messages: [
      { role: "system", content: "Extract structured person info from the text." },
      { role: "user",   content: text },
    ],
    response_format: zodResponseFormat(PersonSchema, "person"),
  });

  return res.choices[0].message.parsed!;
}

const person = await extractPerson("Alice is a 28-year-old designer from Berlin who knows Figma and CSS.");
console.log(person);

Use Cases

  • data extraction
  • form autofill
  • document parsing

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.