AI Model Wiki

    Skip to main content
    40 min
    Lesson 2 of 5

    Zod Schemas for Structured Output

    From the course TypeScript for AI Applications

    Runtime Validation with Zod

    Why Zod?

    AI outputs are unpredictable. Zod validates at runtime what TypeScript checks at compile time.

    Defining Output Schemas

    import { z } from "zod";
    
    const ProductSchema = z.object({
      name: z.string().min(1),
      price: z.number().positive(),
      category: z.enum(["electronics", "clothing", "food"]),
      features: z.array(z.string()).min(1).max(10),
      inStock: z.boolean(),
    });
    
    type Product = z.infer<typeof ProductSchema>;
    

    Validating AI Output

    async function extractProduct(description: string): Promise<Product> {
      const response = await openai.chat.completions.create({
        model: "gpt-4o",
        messages: [{ role: "user", content: `Extract product info: ${description}` }],
        response_format: { type: "json_object" },
      });
    
      const raw = JSON.parse(response.choices[0].message.content!);
      return ProductSchema.parse(raw); // Throws if invalid
    }
    

    Safe Parsing with Fallbacks

    const result = ProductSchema.safeParse(raw);
    if (result.success) {
      return result.data; // Typed as Product
    } else {
      console.error("Validation failed:", result.error.issues);
      return defaultProduct; // Fallback
    }
    

    Converting Zod to JSON Schema

    import { zodToJsonSchema } from "zod-to-json-schema";
    
    const jsonSchema = zodToJsonSchema(ProductSchema);
    // Use as function calling parameter schema or structured output schema
    

    Common Pitfall: Calling .parse() Without a Try-Catch

    zodSchema.parse() throws a ZodError when validation fails. In production, unhandled ZodErrors become 500 Internal Server Errors. Always use .safeParse() in API routes, or wrap .parse() in a try-catch:

    // Fragile: throws 500 if AI returns unexpected format
    const product = ProductSchema.parse(raw);
    
    // Robust: handle gracefully
    const result = ProductSchema.safeParse(raw);
    if (!result.success) {
      logger.error("AI returned invalid product format", {
        errors: result.error.issues,
        raw,
      });
      return { error: "Failed to parse product data", raw };
    }
    const product = result.data;  // Fully typed as Product
    

    Best Practice: Add .describe() to Schema Fields

    Zod's .describe() method adds a description to a field, which is included in the JSON Schema output. When you use zodToJsonSchema to generate function call schemas, these descriptions are read by the AI model to understand what each field means:

    const ProductSchema = z.object({
      name: z.string().min(1).describe("The product's official name as shown on packaging"),
      price: z.number().positive().describe("Price in USD, must be greater than 0"),
      category: z.enum(["electronics", "clothing", "food"]).describe("Product category for catalog organization"),
    });
    

    Better descriptions lead to better field extraction accuracy from the AI model.

    Named Product Reference: tRPC for Type-Safe AI APIs

    tRPC generates TypeScript types for your API endpoints automatically, eliminating the need to manually sync client and server types. For AI apps where the server-side AI logic frequently changes response shapes, tRPC ensures the client code always reflects the current API shape at compile time. The @trpc/next integration is particularly smooth for Next.js AI applications.

    Key Takeaways

    • •Zod provides runtime validation for AI-generated outputs
    • •Use z.infer to derive TypeScript types from Zod schemas
    • •safeParse enables graceful handling of invalid outputs
    • •Convert Zod schemas to JSON Schema for function calling definitions
    0 of 5 lessons marked complete

    Progress is kept in this browser only.