Lab 14: AI Integration
Overview
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
Summary
Function
Schema
Type Safety
Last updated
