Module 2, Lesson 3: Chat with Tools (OpenAI)
The same weather and date tools with the Responses API: function calls, strict schemas and reasoning items.
Published: 11/22/2026
Lesson 3: Chat with tools
The file is src/openai/basic-chat-with-tools.ts. The loop is the one from Module 1: call, run the requested tools, send the results, repeat until there are no more tool requests.
1. Imports and tool definitions
import dotenv from "dotenv"; import { createInterface } from "node:readline/promises"; import OpenAI from "openai"; import type { FunctionTool, Response, ResponseFunctionToolCall, ResponseInput, } from "openai/resources/responses/responses"; import { basicTravelSystemPrompt } from "../common/prompt-ref.js"; import { addTimePeriod, askHolidayPrompt, getWeather, type TimePeriod, } from "../common/utils.js"; import { model } from "./config.js"; dotenv.config(); const client = new OpenAI(); const tools: FunctionTool[] = [ { type: "function", 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.", strict: true, parameters: { 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"], additionalProperties: false, }, }, { type: "function", name: "get_todays_date", description: "Get today's date. Takes no arguments.", strict: true, parameters: { type: "object", properties: {}, required: [], additionalProperties: false, }, }, { type: "function", name: "add_time_period", description: "Add a period of time to a given date and return the new date. Use a negative amount to go back in time. To count from today, first call get_todays_date.", strict: true, parameters: { 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"], additionalProperties: false, }, }, ];
strict: true makes the model's arguments follow the schema exactly. Strict mode requires every property to be listed in required and additionalProperties: false on each object.
2. Running the tools
const runTool = async (name: string, args: unknown): Promise<string> => { switch (name) { case "get_weather": { const { location, country } = args 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 } = args 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 ( calls: ResponseFunctionToolCall[], ): Promise<ResponseInput> => Promise.all( calls.map(async (call) => { console.log(`[tool] ${call.name}(${call.arguments})`); let output: string; try { output = await runTool(call.name, JSON.parse(call.arguments)); } catch (err) { output = `Error: ${String(err)}`; } return { type: "function_call_output" as const, call_id: call.call_id, output, }; }), );
Unlike Anthropic, the arguments arrive as a JSON string (call.arguments), so you parse them. The result is a function_call_output item tied to the request by call_id.
3. The loop and the history
// The conversation lives here and is resent in full on every request (no // previous_response_id or Conversations API), so `store: false` keeps the // server stateless. const history: ResponseInput = []; const chat = (): Promise<Response> => client.responses.create({ model, instructions: basicTravelSystemPrompt, input: history, tools, store: false, // Needed to send reasoning items back when responses are not stored include: ["reasoning.encrypted_content"], }); const runTurn = async (): Promise<Response> => { while (true) { const response = await chat(); // Keep the items the API needs to see again on the next request for (const item of response.output) { if ( item.type === "message" || item.type === "function_call" || item.type === "reasoning" ) { history.push(item); } } const calls = response.output.filter( (item): item is ResponseFunctionToolCall => item.type === "function_call", ); if (calls.length === 0) return response; history.push(...(await runTools(calls))); } };
This is where OpenAI differs from lesson 2. The output of a response is a list of items: messages, function calls and, for reasoning models, reasoning items. They must go back into the history so the model keeps its chain of thought across a tool call. With store: false the server has no copy of that reasoning, so you ask for it with include: ["reasoning.encrypted_content"]. It comes back encrypted, and you send it back as-is.
The loop ends when the output contains no function_call items.
4. The main loop
const rl = createInterface({ input: process.stdin, output: process.stdout }); try { history.push({ role: "user", content: await askHolidayPrompt(rl) }); while (true) { const response = await runTurn(); console.log(`\n${response.output_text}\n`); if (response.status !== "completed") { const reason = response.incomplete_details?.reason ?? "unknown"; console.warn(`[stopped early: ${response.status}] ${reason}\n`); } // Press return on an empty line to exit const followUp = (await rl.question("Follow-up (return to exit): ")).trim(); if (!followUp) break; history.push({ role: "user", content: followUp }); } } finally { rl.close(); }
OpenAI's equivalent of a stop reason is response.status. Anything other than completed (for example incomplete) is reported along with incomplete_details.reason.
Run it with pnpm tsx src/openai/basic-chat-with-tools.ts.
👉 Continue to Lesson 4: Server-side conversation