You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
docs: fix CHAPTER-1 to show correct systemPrompt and route patterns
- Updated system prompt section to show updating regularPrompt constant
instead of replacing the entire systemPrompt function
- Added note that system prompt already has requestHints for location
- Updated route handler to show correct systemPrompt({ selectedChatModel, requestHints })
- Added explanation that full route uses createUIMessageStream
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
In this chapter, we'll give the AI the ability to **do things** beyond just responding with text. We'll add a weather tool that demonstrates how AI can call functions to retrieve real-time information.
|`execute`function| Event handler callback | Runs when the AI decides to use the tool |
21
-
| Tool description | JSDoc / component documentation | Helps the AI "read" when to use it |
22
-
23
-
### Key Talking Points
24
-
25
-
1. **"Tools are just functions with extra metadata"**
26
-
- The AI reads the `description` to decide when to call
27
-
- Zod schemas ensure type-safe inputs (like TypeScript for AI)
28
-
- `execute` is async - can fetch APIs, query DBs, anything
29
-
30
-
2. **"The AI decides, not you"**
31
-
- You define WHAT the tool does, the AI decides WHEN
32
-
- Good descriptions = accurate tool selection
33
-
- Bad descriptions = confused AI, wrong tool calls
34
-
35
-
3. **"Tools don't break the chat"**
36
-
- Tool results flow back into the conversation
37
-
- The AI synthesizes results into natural language
38
-
- Users see a seamless experience
39
-
40
-
### Live Demo Tips
41
-
42
-
- Show the Network tab to see tool calls as separate events
43
-
- Intentionally ask something the tool can't handle ("What's the weather on Mars?")
44
-
- Compare with/without tools: same question, different capabilities
45
-
46
-
### Common Questions
47
-
48
-
- **"Why Zod?"** - Runtime validation + TypeScript types in one schema
49
-
- **"Can tools call other tools?"** - Not directly, but the AI can chain multiple tool calls
50
-
- **"What if the API fails?"** - Handle errors gracefully in `execute`, return user-friendly messages
51
-
52
-
---
53
-
54
5
## Learning Objectives
55
6
56
7
By the end of this chapter, you'll understand:
@@ -74,9 +25,6 @@ When you ask "What's the weather in London?", instead of guessing, the AI can **
74
25
75
26
Every tool has three parts:
76
27
77
-
<details>
78
-
<summary>📄 <strong>Code: Tool Anatomy</strong> (click to expand)</summary>
79
-
80
28
```typescript
81
29
import { tool } from"ai";
82
30
import { z } from"zod";
@@ -98,86 +46,140 @@ const myTool = tool({
98
46
});
99
47
```
100
48
101
-
</details>
102
-
103
-
> 💡 **React Parallel**: This is like defining a custom hook with TypeScript props - the schema is your prop types, the execute is your hook logic, and the description is your JSDoc comment.
104
-
105
49
## The Weather Tool
106
50
107
-
Here's the complete weather tool implementation:
51
+
Here's the complete weather tool implementation with city name geocoding:
108
52
109
53
### File: `lib/ai/tools/get-weather.ts`
110
54
111
-
<details>
112
-
<summary>📄 <strong>Code: Complete Weather Tool</strong> (click to expand)</summary>
113
-
114
55
```typescript
115
56
import { tool } from"ai";
116
57
import { z } from"zod";
117
58
59
+
// Helper function to convert city names to coordinates
The full route handler uses `createUIMessageStream` with `JsonToSseTransformStream` for streaming - the key thing is adding `getWeather` to the `tools` object and `"getWeather"` to `experimental_activeTools`.
176
+
177
+
### Key Configuration
179
178
180
-
> 💡 **Key Insight**: `maxSteps: 5` allows the AI to make multiple tool calls in sequence - like calling `getWeather` for two cities to compare them.
179
+
-**`stopWhen: stepCountIs(5)`**: Limits tool call chains to 5 steps
180
+
-**`experimental_activeTools`**: Conditionally enables/disables tools (disabled for reasoning model)
181
+
-**`tools`**: Object containing all available tools
182
+
-**`requestHints`**: Contains user's location (useful for "What's the weather?" without a city)
181
183
182
184
## How Tool Calling Works
183
185
@@ -188,9 +190,12 @@ export async function POST(request: Request) {
{cityName ? `Weather in ${cityName}` : "Current Weather"}
231
+
</p>
220
232
<pclassName="text-3xl">
221
-
{temperature}
222
-
{unit}
233
+
{current.temperature_2m}
234
+
{current_units.temperature_2m}
223
235
</p>
224
236
</div>
225
237
</div>
@@ -239,23 +251,39 @@ export function Weather({ temperature, unit }: WeatherProps) {
239
251
})}
240
252
```
241
253
242
-
## Updating the System Prompt
254
+
## Updating the System Prompt (Optional)
243
255
244
-
Help the AI know when to use tools:
256
+
The AI will use tools based on their `description` field, so you don't *need* to update the system prompt. However, you can optionally add tool documentation to help the AI understand when to use tools.
257
+
258
+
The system prompt is built from multiple parts. The simplest way to add tool info is to update the `regularPrompt` constant:
245
259
246
260
```typescript
247
261
// lib/ai/prompts.ts
248
-
export const systemPrompt = () => `
249
-
You are a helpful AI assistant.
262
+
263
+
// Update this constant to include tool documentation
264
+
exportconst regularPrompt =`You are a friendly study buddy assistant! Keep your responses concise and helpful.
250
265
251
266
## Tools Available
252
267
- **getWeather**: Use this when users ask about weather conditions.
253
-
Ask for a city name if not provided.
254
-
255
-
Today's date is ${new Date().toLocaleDateString()}.
268
+
You can provide a city name like "Paris" or "Tokyo".
256
269
`;
270
+
271
+
// The systemPrompt function combines regularPrompt with location hints
272
+
// No need to change this function - it already works!
**Note**: The `requestHints` add the user's location context (city, country, lat/lon), which is useful for the weather tool - the AI can use the user's location as a default if they just say "What's the weather?"
286
+
259
287
## Try It Out: Weather Tool
260
288
261
289
Now that you've wired up the weather tool, test it with these prompts. Click the **"What is the weather in San Francisco?"** button in the chat, or try these variations:
@@ -282,7 +310,8 @@ Should I bring an umbrella to Seattle?
282
310
283
311
**Troubleshooting:**
284
312
- If you see "I don't have access to real-time weather", check that the tool is properly added to the `tools` object in your chat route
285
-
- If coordinates seem wrong, the AI is inferring lat/long from city names - this is expected behavior
313
+
- If the city isn't found, try using a more common spelling or a larger nearby city
0 commit comments