1import Anthropic from "@anthropic-ai/sdk";
2import { tools } from "./tools";
3
4const client = new Anthropic(); // reads ANTHROPIC_API_KEY
5
6// A stand-in for a real weather API (the checkpoint uses a real one).
7function getWeather(city: string) {
8 return { city, temp_c: 5, sky: "overcast" };
9}
10
11const question = process.argv[2] ?? "Do I need a coat in Chicago?";
12const messages: Anthropic.MessageParam[] = [{ role: "user", content: question }];
13
14// Request one: question + tools.
15const first = await client.messages.create({
16 model: "claude-haiku-5-5",
17 max_tokens: 4096,
18 tools,
19 messages,
20});
21
22const call = first.content.find((block) => block.type === "tool_use");
23if (first.stop_reason !== "tool_use" || !call) {
24 // Claude answered without a tool. That's allowed.
25 for (const block of first.content) if (block.type === "text") console.log(block.text);
26 process.exit(0);
27}
28
29// Your code runs the tool. Claude only asked.
30const { city } = call.input as { city: string };
31const result = getWeather(city);
32
33// Request two: Claude's reply as it came, then the result.
34messages.push(
35 { role: "assistant", content: first.content },
36 {
37 role: "user",
38 content: [{ type: "tool_result", tool_use_id: call.id, content: JSON.stringify(result) }],
39 },
40);
41const second = await client.messages.create({
42 model: "claude-haiku-5-5",
43 max_tokens: 4096,
44 tools,
45 messages,
46});
47
48for (const block of second.content) if (block.type === "text") console.log(block.text);