|
| 1 | +# Chapter 0: The Starting Point |
| 2 | + |
| 3 | +Welcome to the AI Chatbot Workshop! In this chapter, we'll explore the foundation of our application - a basic chat interface powered by Next.js and the AI SDK. |
| 4 | + |
| 5 | +## Learning Objectives |
| 6 | + |
| 7 | +By the end of this chapter, you'll understand: |
| 8 | +- The basic project structure |
| 9 | +- How the chat API route works |
| 10 | +- How streaming responses work with the AI SDK |
| 11 | +- The message format and data flow |
| 12 | + |
| 13 | +## Project Structure Overview |
| 14 | + |
| 15 | +``` |
| 16 | +ai-chatbot/ |
| 17 | +├── app/ |
| 18 | +│ ├── (auth)/ # Authentication routes |
| 19 | +│ │ ├── auth.ts # NextAuth configuration |
| 20 | +│ │ ├── login/ # Login page |
| 21 | +│ │ └── register/ # Registration page |
| 22 | +│ └── (chat)/ # Main chat application |
| 23 | +│ ├── api/ |
| 24 | +│ │ └── chat/ # Chat streaming endpoint |
| 25 | +│ │ └── route.ts |
| 26 | +│ ├── page.tsx # Main chat page |
| 27 | +│ └── layout.tsx # Chat layout |
| 28 | +├── components/ # React components |
| 29 | +├── lib/ |
| 30 | +│ ├── ai/ # AI configuration |
| 31 | +│ │ ├── providers.ts # Model setup |
| 32 | +│ │ └── prompts.ts # System prompts |
| 33 | +│ └── db/ # Database layer |
| 34 | +├── hooks/ # React hooks |
| 35 | +└── docker/ # Docker configuration |
| 36 | +``` |
| 37 | + |
| 38 | +## The Chat API Route |
| 39 | + |
| 40 | +The heart of the application is `/app/(chat)/api/chat/route.ts`. This is where messages are sent to the AI and responses are streamed back. |
| 41 | + |
| 42 | +### Basic Chat Flow |
| 43 | + |
| 44 | +```typescript |
| 45 | +// app/(chat)/api/chat/route.ts (simplified) |
| 46 | +import { streamText } from "ai"; |
| 47 | +import { myProvider } from "@/lib/ai/providers"; |
| 48 | +import { systemPrompt } from "@/lib/ai/prompts"; |
| 49 | + |
| 50 | +export async function POST(request: Request) { |
| 51 | + const { messages } = await request.json(); |
| 52 | + |
| 53 | + // Stream the AI response |
| 54 | + const result = streamText({ |
| 55 | + model: myProvider.languageModel("chat-model"), |
| 56 | + system: systemPrompt(), |
| 57 | + messages, |
| 58 | + }); |
| 59 | + |
| 60 | + return result.toDataStreamResponse(); |
| 61 | +} |
| 62 | +``` |
| 63 | + |
| 64 | +### Key Concepts |
| 65 | + |
| 66 | +1. **`streamText`**: The AI SDK function that sends messages to the model and streams the response token by token. |
| 67 | +2. **`myProvider`**: Our configured AI provider (Claude Haiku via AI Gateway). |
| 68 | +3. **`systemPrompt`**: Instructions that tell the AI how to behave. |
| 69 | +4. **`toDataStreamResponse`**: Converts the stream into a format the frontend can consume. |
| 70 | + |
| 71 | +## How Streaming Works |
| 72 | + |
| 73 | +When you send a message: |
| 74 | + |
| 75 | +``` |
| 76 | +┌─────────────────────────────────────────────────────────┐ |
| 77 | +│ 1. User types message in chat input │ |
| 78 | +│ ↓ │ |
| 79 | +│ 2. Frontend sends POST to /api/chat │ |
| 80 | +│ ↓ │ |
| 81 | +│ 3. streamText sends messages to AI model │ |
| 82 | +│ ↓ │ |
| 83 | +│ 4. AI generates response token by token │ |
| 84 | +│ ↓ │ |
| 85 | +│ 5. Each token streams back to frontend │ |
| 86 | +│ ↓ │ |
| 87 | +│ 6. UI updates in real-time as tokens arrive │ |
| 88 | +└─────────────────────────────────────────────────────────┘ |
| 89 | +``` |
| 90 | + |
| 91 | +## The Frontend Chat Hook |
| 92 | + |
| 93 | +The frontend uses `useChat` from the AI SDK React package: |
| 94 | + |
| 95 | +```typescript |
| 96 | +// Simplified usage in a chat component |
| 97 | +import { useChat } from "@ai-sdk/react"; |
| 98 | + |
| 99 | +export function Chat() { |
| 100 | + const { messages, input, handleSubmit, handleInputChange } = useChat(); |
| 101 | + |
| 102 | + return ( |
| 103 | + <div> |
| 104 | + {messages.map((message) => ( |
| 105 | + <div key={message.id}> |
| 106 | + <strong>{message.role}:</strong> {message.content} |
| 107 | + </div> |
| 108 | + ))} |
| 109 | + <form onSubmit={handleSubmit}> |
| 110 | + <input value={input} onChange={handleInputChange} /> |
| 111 | + <button type="submit">Send</button> |
| 112 | + </form> |
| 113 | + </div> |
| 114 | + ); |
| 115 | +} |
| 116 | +``` |
| 117 | + |
| 118 | +The `useChat` hook handles: |
| 119 | +- Managing message history |
| 120 | +- Sending messages to the API |
| 121 | +- Streaming response updates |
| 122 | +- Input state management |
| 123 | + |
| 124 | +## Message Format |
| 125 | + |
| 126 | +Messages follow this structure: |
| 127 | + |
| 128 | +```typescript |
| 129 | +type Message = { |
| 130 | + id: string; |
| 131 | + role: "user" | "assistant" | "system"; |
| 132 | + content: string; |
| 133 | + // Can also contain parts for multimodal content |
| 134 | + parts?: MessagePart[]; |
| 135 | +}; |
| 136 | +``` |
| 137 | + |
| 138 | +## The System Prompt |
| 139 | + |
| 140 | +The system prompt shapes the AI's personality and behavior: |
| 141 | + |
| 142 | +```typescript |
| 143 | +// lib/ai/prompts.ts |
| 144 | +export const systemPrompt = () => ` |
| 145 | +You are a helpful AI assistant. Be concise and helpful. |
| 146 | +Today's date is ${new Date().toLocaleDateString()}. |
| 147 | +`; |
| 148 | +``` |
| 149 | + |
| 150 | +## Exercise: Trace a Message |
| 151 | + |
| 152 | +1. Start the development server: `npm run dev` |
| 153 | +2. Open the browser console (F12) |
| 154 | +3. Send a message like "Hello!" |
| 155 | +4. Watch the Network tab to see the streaming response |
| 156 | +5. Notice how the text appears token by token |
| 157 | + |
| 158 | +## What's Next |
| 159 | + |
| 160 | +In Chapter 1, we'll add our first **tool** - giving the AI the ability to do more than just respond with text. We'll start with a simple weather tool that demonstrates how AI can call functions to retrieve information. |
| 161 | + |
| 162 | +## Key Files to Explore |
| 163 | + |
| 164 | +Before moving on, familiarize yourself with these files: |
| 165 | + |
| 166 | +| File | Purpose | |
| 167 | +|------|---------| |
| 168 | +| `app/(chat)/api/chat/route.ts` | Main streaming endpoint | |
| 169 | +| `lib/ai/providers.ts` | AI model configuration | |
| 170 | +| `lib/ai/prompts.ts` | System prompts | |
| 171 | +| `components/chat.tsx` | Chat UI component | |
| 172 | +| `components/message.tsx` | Message rendering | |
| 173 | + |
| 174 | +## Running the Application |
| 175 | + |
| 176 | +```bash |
| 177 | +# Start MongoDB |
| 178 | +npm run docker:up |
| 179 | + |
| 180 | +# Start the dev server |
| 181 | +npm run dev |
| 182 | + |
| 183 | +# Visit http://localhost:3000 |
| 184 | +``` |
| 185 | + |
| 186 | +You should see a chat interface. Send a message and watch the AI respond! |
0 commit comments