Lab 14: AI Integration

Time: 60 minutes | Level: Architect | Docker: node:20-alpine

Overview

Type-safe AI integration: Vercel AI SDK (generateText/generateObject/streamText with Zod schemas), typed streaming responses, type-safe tool definitions, OpenAI SDK types, Anthropic SDK types, and structured output validation.


Step 1: Vercel AI SDK — generateObject with Zod

import { generateObject, generateText, streamText } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import { openai }    from '@ai-sdk/openai';
import { z }         from 'zod';

// generateObject: structured output guaranteed by Zod schema
const { object } = await generateObject({
  model: anthropic('claude-3-5-sonnet-20241022'),
  schema: z.object({
    products: z.array(z.object({
      name:        z.string(),
      price:       z.number().positive(),
      category:    z.enum(['electronics', 'clothing', 'food', 'books']),
      description: z.string().max(200),
      inStock:     z.boolean(),
    })),
    totalCount: z.number(),
    categories: z.array(z.string()),
  }),
  prompt: 'List 3 popular electronics products with realistic details.',
});

// `object` is fully typed — no type assertions needed
console.log(object.products[0].name);   // string ✓
console.log(object.products[0].price);  // number ✓
// console.log(object.products[0].xyz); // Error: Property 'xyz' doesn't exist ✓

Step 2: Type-Safe Tool Definitions


Step 3: streamText — Typed Streaming


Step 4: OpenAI SDK Types


Step 5: Anthropic SDK Types


Step 6: AI SDK + Zod Schema — Full Pipeline


Step 7: AI Error Handling with Types


Step 8: Capstone — generateObject Demo

📸 Verified Output:

(With correct data, output shows fully typed, Zod-validated AI responses)


Summary

Function
Schema
Type Safety

generateObject

Zod schema

Output matches schema exactly

streamText

Callback types

Chunk types are discriminated

tool()

Zod parameters

Execute args are typed

OpenAI SDK

ChatCompletionMessageParam

Message array typed

Anthropic SDK

MessageParam

Content blocks typed

Error handling

SDK error classes

Specific error types

Last updated