fix: lessons

This commit is contained in:
2026-06-07 15:15:11 +02:00
parent 83779e0d7a
commit 4f13aadc1a
121 changed files with 2038 additions and 23690 deletions

View File

@@ -1,298 +1,80 @@
# Les 13: Vercel AI SDK, Tool Calling & Agents
# Les 13: Externe APIs + Cursor agents + Vercel deploy
> ✅ **Deze les is volledig uitgewerkt**
## Lesmateriaal
- [Slide Overzicht](../Les13-Cursor-Vercel-Deploy/Les13-Slide-Overzicht.md)
- [Docenttekst](../Les13-Cursor-Vercel-Deploy/Les13-Docenttekst.md)
- [Lesstof](../Les13-Cursor-Vercel-Deploy/Les13-Lesstof.md)
- [Lesopdracht](../Les13-Cursor-Vercel-Deploy/Les13-Lesopdracht.md)
- [Huiswerk](../Les13-Cursor-Vercel-Deploy/Les13-Huiswerk.md)
---
## Hoofdstuk
**Deel 4: Advanced AI & Deployment** (Les 13-18)
## Deel
**Deel 3 — AI Development** (Les 11-16)
## 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.
We verlaten `localhost:3000`. We bouwen een kleine Pokédex die de PokéAPI gebruikt (geen LLM nodig), zetten Cursor's Composer + Background Agent in voor feature branches, en deployen naar Vercel met preview deployments + GitHub Actions CI.
---
## Te Behandelen (~45 min)
## Te Behandelen
- 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.
### Theorie
- Externe APIs in Next.js (server-side fetch, caching)
- Cursor Composer vs. Background Agent — wanneer welke?
- Vercel preview deployments per branch
- GitHub Actions CI (lint + build per PR)
- Environment variables: lokaal vs. Vercel
---
### 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 (
<div>
{messages.map((msg) => (
<div key={msg.id}>
<strong>{msg.role}:</strong> {msg.content}
</div>
))}
<form onSubmit={handleSubmit}>
<input
value={input}
onChange={handleInputChange}
placeholder="Type message..."
/>
<button type="submit">Send</button>
</form>
</div>
)
}
```
---
### 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<typeof SearchProductsSchema>
```
---
### 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)
### Live demo's
1. Nieuwe Pokédex-app — PokéAPI integreren
2. Feature branch via Cursor Composer
3. Background Agent: PR + diff review
4. Vercel deploy + preview URL per PR
5. GH Actions workflow voor lint + typecheck
---
## Tools
- Vercel AI SDK
- Zod
- OpenAI API (of andere LLM provider)
- Cursor
- Next.js 16
- Cursor (Composer + Background Agent)
- Vercel (productie + previews)
- GitHub Actions
- PokéAPI (geen key nodig)
---
## Lesopdracht (2 uur, klassikaal)
## Lesopdracht (in-class, 60 min)
### Bouw Chat Interface met Streaming
Studenten kijken mee. In-class oefening:
- Clone de Pokédex-starter
- Maak een feature branch via Cursor Composer ("voeg type-filter toe")
- Push naar GitHub en bekijk je Vercel preview URL
- Merge de PR — zie GH Actions runnen
**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
**Inleveren:** Screenshot van werkende preview URL.
---
## Huiswerk (2 uur)
## Huiswerk (take-home)
### Integreer AI in Eindproject
Neem je AI SDK-project uit Les 11/12:
- Deploy naar Vercel
- Voeg minimaal 1 externe API toe (geen LLM)
- Configureer GH Actions CI (lint + build)
- README beschrijft hoe lokaal + hoe productie
**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
**Inleveren:** GitHub + Vercel URL via Teams.
---
## 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
- Externe APIs aanroepen vanuit een Next.js server route
- Het verschil uitleggen tussen Cursor Composer en Background Agent
- Een feature branch + preview deployment opzetten
- GitHub Actions CI configureren voor een Next.js project
- Environment variables veilig beheren tussen lokaal en Vercel