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.
typescriptintermediate
OpenAI Chat Completion with Streaming
Stream GPT responses token-by-token using the OpenAI SDK with async iteration.
#openai#streaming
typescriptintermediate
OpenAI Tool Calling (Function Calling)
Define tools for GPT to call, parse the response, execute the function, and return results.
#openai#tool-calling
typescriptbeginner
Generate Text Embeddings with OpenAI
Create vector embeddings for semantic search and similarity matching using text-embedding-3-small.
#openai#embeddings
typescriptadvanced
RAG Pipeline (Retrieve + Augment + Generate)
Minimal RAG implementation: embed a query, retrieve top-k chunks, inject into prompt.
#rag#embeddings