Module 1, Lesson 3: Chat with Tools (Anthropic)
Give the chatbot weather and date tools, run the tool-use loop and handle thinking blocks and stop reasons.
Published: 11/22/2026
Lesson 3: Chat with tools
A model can't know today's weather or today's date. Tools let it ask your code. The model never runs anything itself: it replies with a request to call a tool, your code runs it, and you send the result back.
The file is src/anthropic/basic-chat-with-tools.ts. It is built from these parts.
1. Message helpers
import Anthropic from "@anthropic-ai/sdk"; import dotenv from "dotenv"; import { createInterface } from "node:readline/promises"; import { addTimePeriod, askHolidayPrompt, getWeather, type TimePeriod, } from "../common/utils.js"; import { basicTravelSystemPrompt } from "../common/prompt-ref.js"; import { model } from "./config.js"; dotenv.config(); const client = new Anthropic(); type Content = string | Anthropic.ContentBlockParam[]; const toContent = (input: Content | Anthropic.Message): Content => typeof input === "string" || Array.isArray(input) ? input : input.content; const add_user_message = ( messages: Anthropic.MessageParam[], message: Content | Anthropic.Message, ) => { messages.push({ role: "user", content: toContent(message) }); }; // Passing the whole Message keeps every content block (including thinking and // tool_use blocks), which the API needs to see again on the next request. const add_assistant_message = ( messages: Anthropic.MessageParam[], message: Content | Anthropic.Message, ) => { messages.push({ role: "assistant", content: toContent(message) }); };
The comment is the important point. When Claude asks for a tool, its reply contains a tool_use block, and with thinking turned on it can also contain a thinking block. All of them must go back in the history unchanged, or the next request is rejected.
2. Tool definitions
Each tool has a name, a description and an input_schema (JSON Schema). The description is how the model decides when to call the tool, so write it carefully.
const tools: Anthropic.Tool[] = [ { name: "get_weather", description: "Get the CURRENT weather observation for a place. This is not a forecast for future travel dates. " + "Only call it when the user asks about the weather. Always give the country, because place names " + "alone can match the wrong location.", input_schema: { type: "object", properties: { location: { type: "string", description: "The place name only, e.g. 'Keflavik' (no country).", }, country: { type: "string", description: "The country the place is in, e.g. 'Iceland'.", }, }, required: ["location", "country"], }, }, { name: "get_todays_date", description: "Get today's date in YYYY-MM-DD format. Takes no arguments.", input_schema: { type: "object", properties: {}, }, }, { name: "add_time_period", description: "Add a period of time to a given date and return the new date in YYYY-MM-DD format. Use a negative amount to go back in time. To count from today, first call get_todays_date.", input_schema: { type: "object", properties: { date: { type: "string", description: "The starting date in YYYY-MM-DD format", }, amount: { type: "integer", description: "Number of units to add; negative to subtract", }, unit: { type: "string", enum: ["days", "weeks", "months", "years"], description: "The unit of time for the amount", }, }, required: ["date", "amount", "unit"], }, }, ];
3. Running the tools
runTool maps a tool name to real code. runTools finds every tool_use block in the reply, runs them in parallel and wraps each output in a tool_result block that carries the matching tool_use_id.
const runTool = async (name: string, input: unknown): Promise<string> => { switch (name) { case "get_weather": { const { location, country } = input as { location: string; country: string; }; return JSON.stringify(await getWeather(location, country)); } case "get_todays_date": return new Date().toISOString().slice(0, 10); case "add_time_period": { const { date, amount, unit } = input as { date: string; amount: number; unit: TimePeriod; }; return addTimePeriod(new Date(date), amount, unit) .toISOString() .slice(0, 10); } default: throw new Error(`Unknown tool: ${name}`); } }; const runTools = async ( message: Anthropic.Message, ): Promise<Anthropic.ToolResultBlockParam[]> => { const toolUseBlocks = message.content.filter( (block): block is Anthropic.ToolUseBlock => block.type === "tool_use", ); return Promise.all( toolUseBlocks.map(async (block) => { console.log(`[tool] ${block.name}(${JSON.stringify(block.input)})`); try { const output = await runTool(block.name, block.input); return { type: "tool_result", tool_use_id: block.id, content: typeof output === "string" ? output : JSON.stringify(output), is_error: false, }; } catch (err) { return { type: "tool_result", tool_use_id: block.id, content: String(err), is_error: true, }; } }), ); };
If a tool throws, the error goes back with is_error: true, so the model can explain the problem instead of the program crashing.
4. The tool-use loop
const chat = async (messages: Anthropic.MessageParam[]) => { return client.messages.create({ model: model, max_tokens: 4000, messages, tools, thinking: { type: "adaptive" }, system: basicTravelSystemPrompt, }); }; const runTurn = async (messages: Anthropic.MessageParam[]) => { while (true) { const response = await chat(messages); add_assistant_message(messages, response); if (response.stop_reason !== "tool_use") { return response; } add_user_message(messages, await runTools(response)); } };
runTurn keeps calling the API for as long as stop_reason is tool_use. A single user question may need several rounds, for example get_todays_date, then add_time_period, then get_weather. thinking: { type: "adaptive" } lets Claude decide how much to think before answering.
5. Reading the answer and stop reasons
With thinking enabled the first block is usually a thinking block, so look for the text block rather than reading content[0].
const getText = (message: Anthropic.Message) => { const block = message.content.find((b) => b.type === "text"); return block?.type === "text" ? block.text : ""; }; // Explanations for stop reasons other than a normal finish ("end_turn") const EARLY_STOP_REASONS: Record<string, string> = { max_tokens: "the reply hit the max_tokens limit and was cut off", refusal: "the model declined to answer", pause_turn: "the turn was paused and is not complete", model_context_window_exceeded: "the conversation is too long for the model", };
6. The main loop
const messages: Anthropic.MessageParam[] = []; const rl = createInterface({ input: process.stdin, output: process.stdout }); try { add_user_message(messages, await askHolidayPrompt(rl)); while (true) { const response = await runTurn(messages); console.log(`\n${getText(response)}\n`); const { stop_reason } = response; if (stop_reason !== "end_turn") { const why = EARLY_STOP_REASONS[stop_reason ?? ""] ?? "unexpected stop"; console.warn(`[stopped early: ${stop_reason ?? "unknown"}] ${why}\n`); } // Press return on an empty line to exit const followUp = (await rl.question("Follow-up (return to exit): ")).trim(); if (!followUp) break; add_user_message(messages, followUp); } } finally { rl.close(); }
The conversation state is still just the messages array, resent in full each time. The Messages API has no server-side conversation store. In Module 2 you'll see OpenAI offer both styles.
Try it
Run pnpm tsx src/anthropic/basic-chat-with-tools.ts, pick "Winter sun" and watch the [tool] lines. Then ask "what will the date be in 3 weeks?" and see which tools it chains.
👉 Next: Lesson 4: Showing Reasoning
👉 Or skip ahead to Module 2: Chat with OpenAI