TypeScript Zod to OpenAI Schema
Zod is a TypeScript-first schema validation library. Learn how to use Zod schemas with OpenAI's Structured Outputs for type-safe AI responses.
Why Zod for OpenAI?
- TypeScript-native with excellent type inference
- Runtime validation of AI responses
- Convert to JSON Schema with
zod-to-json-schema - Works with OpenAI's Node.js SDK
Strict Mode with Zod
Use .strict() to ensure the schema is compatible with OpenAI's strict mode:
import { z } from 'zod';
import { zodToJsonSchema } from 'zod-to-json-schema';
const UserSchema = z.object({
name: z.string(),
email: z.string().email(),
age: z.number().int(),
}).strict(); // Important for OpenAI strict mode
const jsonSchema = zodToJsonSchema(UserSchema);Using with OpenAI SDK
import OpenAI from 'openai';
import { z } from 'zod';
import { zodToJsonSchema } from 'zod-to-json-schema';
const ResponseSchema = z.object({
summary: z.string(),
sentiment: z.enum(['positive', 'negative', 'neutral']),
confidence: z.number(),
}).strict();
const client = new OpenAI();
const response = await client.chat.completions.create({
model: 'gpt-4o-2024-08-06',
messages: [{ role: 'user', content: '...' }],
response_format: {
type: 'json_schema',
json_schema: {
name: 'Analysis',
strict: true,
schema: zodToJsonSchema(ResponseSchema)
}
}
});
// Parse and validate response
const parsed = ResponseSchema.parse(
JSON.parse(response.choices[0].message.content)
);Benefits of This Approach
🔒 Type Safety
TypeScript infers the response type from your Zod schema.
✅ Runtime Validation
Zod validates the AI response at runtime, catching malformed outputs.
🔄 Single Source of Truth
One schema for both OpenAI and your application validation.
Generate Zod Schemas
Our tool generates Zod schemas from JSON samples automatically.
Try the Generator →