typescriptintermediate
OpenAI Structured Output with Zod
Force GPT-4o to return valid JSON matching a Zod schema using response_format structured output.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
pythonintermediate
OpenAI Structured Output with Pydantic
Force GPT to return validated JSON matching a Pydantic schema.
Best for: Review analysis
#ai#openai
typescriptintermediate
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
Best for: chatbot UI
#openai#streaming
typescriptintermediate
OpenAI Tool Calling (Function Calling)
Define tools for GPT to call, parse the response, execute the function, and return results.
Best for: AI agents
#openai#tool-calling
pythonintermediate
OpenAI Structured Outputs with JSON Schema
Use OpenAI's strict JSON schema mode to guarantee valid structured output from any model.
Best for: entity extraction
#openai#structured-output