# Les 13: Vercel AI SDK, Tool Calling & Agents
---
## Hoofdstuk
**Deel 4: Advanced AI & Deployment** (Les 13-18)
## Beschrijving
Vercel AI SDK fundamentals voor het bouwen van AI-powered features. Stream responses, tool calling, Zod schemas, system prompts, agents met autonome actie. Integreer LLM capabilities in je app.
---
## Te Behandelen (~45 min)
- Vercel AI SDK: wat is het en waarom gebruiken?
- Installation en basic setup
- useChat hook voor chat UI state management
- Streaming responses van API
- Tool calling: laat AI externe APIs aanroepen
- Zod schemas voor tool parameters validation
- System prompts schrijven voor AI behavior
- Agent patterns: maxSteps, autonomous execution
- Error handling en edge cases
- Model selection: OpenAI, Claude, Gemini, etc.
---
### Vercel AI SDK Basics
**Wat is het?**
- React library van Vercel voor AI integration
- Streaming responses van LLMs
- Server-side tool calling
- Multi-turn conversations
- Gratis, open-source
**Installation:**
```bash
npm install ai zod openai
```
---
### useChat Hook
**Client-side chat state management:**
```typescript
'use client'
import { useChat } from 'ai/react'
export function ChatComponent() {
const { messages, input, handleInputChange, handleSubmit } = useChat({
api: '/api/chat',
})
return (
{messages.map((msg) => (
{msg.role}: {msg.content}
))}
)
}
```
---
### Streaming Responses
**API Route met streaming:**
```typescript
import { generateText, streamText } from 'ai'
import { openai } from '@ai-sdk/openai'
export async function POST(req: Request) {
const { messages } = await req.json()
const result = await streamText({
model: openai('gpt-4'),
system: 'You are a helpful assistant',
messages,
})
return result.toAIStreamResponse()
}
```
**Waarom streaming?**
- Responses verschijnen real-time (beter UX)
- Bespaar tokens vs waiting for full response
---
### Tool Calling
**Laat AI externe APIs aanroepen:**
```typescript
import { generateText } from 'ai'
import { openai } from '@ai-sdk/openai'
import { z } from 'zod'
const tools = {
getWeather: {
description: 'Get weather for a city',
parameters: z.object({
city: z.string(),
}),
execute: async ({ city }: { city: string }) => {
// Call external API
const response = await fetch(`https://api.weather.com?city=${city}`)
return response.json()
},
},
}
const result = await generateText({
model: openai('gpt-4'),
tools,
prompt: 'What is the weather in Amsterdam?',
})
```
---
### Zod Schemas
**Type-safe tool parameters:**
```typescript
import { z } from 'zod'
const SearchProductsSchema = z.object({
query: z.string().describe('Search query'),
limit: z.number().optional().describe('Max results'),
sortBy: z.enum(['price', 'rating']).optional(),
})
type SearchProductsInput = z.infer
```
---
### System Prompts
**Stuur AI behavior:**
```typescript
const systemPrompt = `You are a helpful recipe assistant.
Your role is to:
1. Suggest recipes based on ingredients
2. Provide cooking instructions
3. Estimate cooking time
Always be friendly and encouraging.`
const result = await generateText({
model: openai('gpt-4'),
system: systemPrompt,
prompt: userMessage,
})
```
---
### Agent Patterns
**Multi-step autonomous execution:**
```typescript
const result = await generateText({
model: openai('gpt-4'),
tools: { getWeather, getFlights },
maxSteps: 3, // Maximum iterations
prompt: 'Plan a trip to Paris next week',
})
```
**Hoe het werkt:**
1. AI bepaalt welke tool nodig is
2. Tool wordt uitgevoerd
3. Result teruggestuurd naar AI
4. AI beslist next stap (repeat tot maxSteps of done)
---
## Tools
- Vercel AI SDK
- Zod
- OpenAI API (of andere LLM provider)
- Cursor
---
## Lesopdracht (2 uur, klassikaal)
### Bouw Chat Interface met Streaming
**Groepsdiscussie (15 min):**
Bespreek klassikaal de project setup ervaringen uit Les 12 - hoe goed werken jullie .cursorrules en configuration?
**Deel 1: Installation & Setup (30 min)**
```bash
npm install ai zod openai
```
Create `app/api/chat/route.ts`:
- Setup Vercel AI SDK
- Configure OpenAI model
- Add system prompt
**Deel 2: Chat Component (45 min)**
Build `app/page.tsx`:
1. Use useChat hook
2. Render messages list
3. Input form for user messages
4. Display streaming responses
**Deel 3: Tool Calling (30 min)**
Add 2 simple tools:
- getTime: return current time
- getRandomNumber: return random number
Update API route to handle tools with Zod schemas.
**Deel 4: Testing (15 min)**
Test chat locally with different prompts that trigger tools.
### Deliverable
- Werkende chat interface with streaming
- 2 integrated tools
- GitHub commit with AI chat feature
---
## Huiswerk (2 uur)
### Integreer AI in Eindproject
**Deel 1: Project-Specific Tools (1 uur)**
Add 2-3 tools relevant to your project:
- Recipe Generator: tool to search recipes API
- Budget App: tool to calculate expenses
- Travel Planner: tool to search destinations
Define with Zod schemas and execute functions.
**Deel 2: System Prompt Tuning (30 min)**
Write a custom system prompt for your AI:
- Define personality
- Set constraints
- Add context about your app
**Deel 3: Integration (30 min)**
Connect AI chat to your main app:
- Add chat page/component
- Integrate with Supabase auth (if needed)
- Test end-to-end
### Deliverable
- AI feature integrated in project
- Custom tools defined
- docs/AI-DECISIONS.md updated with choices
- GitHub commits with AI integration
---
## Leerdoelen
Na deze les kan de student:
- Vercel AI SDK installeren en configureren
- useChat hook gebruiken voor chat UI
- Streaming responses implementeren
- Tool calling setup met Zod schemas
- Externe APIs aanroepen via tools
- System prompts schrijven voor AI behavior
- Agent patterns verstaan (maxSteps)
- AI features in een Next.js app integreren
- Tool parameters valideren met Zod