Every summer, the ferry company’s phone line is busy with the same few questions: when the next boat leaves, whether there’s room for a car, and whether a booking can be rescheduled. A booking assistant could answer them in a chat. But a model only generates text from what’s in the request, and nothing in the request says how many vehicle spaces are left on Saturday’s sailing.
In this lesson, you’ll describe a function of your own as a tool the model can ask for, send the description with a passenger’s question, and read what comes back. By the end of the course, your assistant will look up sailings, change bookings only when it’s safe to, and show with evals, or tests of the assistant’s behavior, that a change made it better. Start with the problem a tool solves.
Give the Model a Way to Ask
Sent on its own, the passenger’s question leaves the model with no availability figures. In one real run, with today’s date in the instructions, it replied: “I can’t see live vehicle availability for Saturday morning, December 5.” Another run could return a confident, invented answer instead. Either way, the passenger is no better off.
Your app could paste the whole current timetable into every request, but then every request carries every sailing, even for a question about one. Instead, you can send the model a tool: a description of a function for finding sailings, so a question brings in only the sailings it needs. A tool has three parts:
- A name that your code will recognize in the model’s request.
- A description that says what the function does and when to use it. The model never sees your function’s code, only the tool’s name, this description, and the schema.
- A JSON Schema for the arguments, the same kind of schema you’ve used for structured output: an object type, its properties, every key in
required, andadditionalProperties: false.
This course’s starting project, from the download below the course overview, holds the ferry company’s data in data/ and the model/ module with ask(), askForJson(), and streamAnswer(). Add a file named tools.js in the project’s root directory, with a description of the function that finds sailings:
tools.js
const PORTS = ["Linden Harbor", "Gull Island", "Heron Island"];
export const FIND_SAILINGS = {
name: "findSailings",
description:
"Find the ferry sailings between two ports on one date, " +
"with the seats and vehicle spaces left on each. Use it " +
"whenever a passenger asks about departure times or " +
"space on a sailing.",
schema: {
type: "object",
properties: {
from: { type: "string", enum: PORTS },
to: { type: "string", enum: PORTS },
date: {
type: "string",
description: "The sailing date, as YYYY-MM-DD",
},
},
required: ["from", "to", "date"],
additionalProperties: false,
},
};
The description says what the function returns, then when to use it. The enum on from and to limits the ports to the three the company sails between, so a passenger’s “the island” can’t turn into a harbor that doesn’t exist. The date property has a description of its own, which tells the model the format your code expects.
The schema is enforced, but descriptions aren’t. Even with strict mode, which you’ll meet below, a date can still come in another format or name the wrong day, so your code checks arguments later in this course. FIND_SAILINGS isn’t in either provider’s format yet. Each provider wraps it in its own shape, as you’ll see in the request next.
Send the Tool With a Question
Before you add tools to your model/ module, see one raw request and response, so you know exactly what the model returns. Create tool-request.js. Its first part imports your tool, your module’s settings, and its model IDs. It then sets up the instructions and the passenger’s question:
tool-request.js
import { FIND_SAILINGS } from "./tools.js";
import { settings } from "./model/settings.js";
import { MODELS } from "./model/config.js";
const now = new Date();
const today = now.toISOString().slice(0, 10);
const weekday = now.toLocaleDateString("en-US", {
weekday: "long",
timeZone: "UTC",
});
const INSTRUCTIONS = `You answer passengers' questions for
Linden Ferries in a short, friendly reply.
Today is ${weekday}, ${today}.`;
const QUESTION = "Is there room for my car on Saturday " +
"morning's sailing from Linden Harbor to Gull Island?";
The instructions include today’s weekday and date because “Saturday” means nothing to the model without them. Both use UTC, so they agree. A real app would use the company’s time zone.
The rest of the script sends the request with fetch() and prints the reply’s text, using the same approach as your module’s readReply(). The request body is where the providers differ, so open the version for your provider. In both, the request carries the tool in a tools array:
First, add one more import at the top, for the role settings in your provider file:
tool-request.js
import { ROLE_SETTINGS } from "./model/openai.js";
Then add the request body below the first part. OpenAI’s Responses API takes each tool with type: "function", and the schema goes in parameters. With strict: true, the arguments in the model’s request always match the schema:
tool-request.js
const body = {
model: MODELS.openai.capable,
instructions: INSTRUCTIONS,
input: QUESTION,
max_output_tokens: settings.maxOutputTokens,
...ROLE_SETTINGS.capable,
tools: [
{
type: "function",
name: FIND_SAILINGS.name,
description: FIND_SAILINGS.description,
parameters: FIND_SAILINGS.schema,
strict: true,
},
],
};
The last part sends the body and prints the status. If the request fails, it throws the provider’s error. Otherwise, it prints the reply’s text, which is in the output_text parts of the message items in output:
tool-request.js
const response = await fetch("https://api.openai.com/v1/responses", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${settings.apiKey}`,
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(settings.timeoutMs),
});
const data = await response.json();
console.log("status:", response.status);
if (!response.ok) {
throw new Error(JSON.stringify(data.error));
}
const answer = data.output
.filter((item) => item.type === "message")
.flatMap((item) => item.content)
.filter((part) => part.type === "output_text")
.map((part) => part.text)
.join("");
console.log("answer:", JSON.stringify(answer));
First, add one more import at the top, for the role settings in your provider file:
tool-request.js
import { ROLE_SETTINGS } from "./model/anthropic.js";
Then add the request body below the first part. Anthropic’s Messages API takes each tool with its schema in input_schema. With strict: true, the arguments in the model’s request always match the schema:
tool-request.js
const body = {
model: MODELS.anthropic.capable,
system: INSTRUCTIONS,
messages: [{ role: "user", content: QUESTION }],
max_tokens: settings.maxOutputTokens,
...ROLE_SETTINGS.capable,
tools: [
{
name: FIND_SAILINGS.name,
description: FIND_SAILINGS.description,
input_schema: FIND_SAILINGS.schema,
strict: true,
},
],
};
The last part sends the body and prints the status. If the request fails, it throws the provider’s error. Otherwise, it prints the reply’s text, which is in the content blocks of type text:
tool-request.js
const response = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${settings.apiKey}`,
"anthropic-version": "2026-10-21",
},
body: JSON.stringify(body),
signal: AbortSignal.timeout(settings.timeoutMs),
});
const data = await response.json();
console.log("status:", response.status);
if (!response.ok) {
throw new Error(JSON.stringify(data.error));
}
const answer = data.content
.filter((block) => block.type === "text")
.map((block) => block.text)
.join("");
console.log("answer:", JSON.stringify(answer));
The model now has a tool that fits the question exactly. Before you run node --env-file=.env tool-request.js, decide what you expect the answer: line to show:
Here’s one real run, against OpenAI:
status: 200
answer: ""
The request succeeded, and the answer is empty. With either provider, the reply has no answer about the car.
If you expected seats and vehicle spaces, you probably pictured the model calling findSailings and answering with the result. It can’t. Look back at tools.js: FIND_SAILINGS is plain data, a description with no code behind it.
The model runs on the provider’s servers, and even once you write findSailings, it’ll live in your code on your machine. All the model can do is generate a request to call it, and that request came back instead of text, so your script didn’t print it.
Once you’ve run it and checked your prediction, read on.
Look Inside the Response
The answer: line shows only text, so look for anything else the model sent. Add a few lines to the end of tool-request.js. The tool call’s shape differs by provider, so open the version for your provider:
The request is an item of type function_call in output. A reply can contain zero, one, or several requests. These lines print the type of every item. If there’s a function_call item, they also print the first one and the type of its arguments:
tool-request.js
console.log(data.output.map((item) => item.type));
const call = data.output.find(
(item) => item.type === "function_call"
);
if (call) {
console.log(call);
const args = JSON.parse(call.arguments);
console.log(typeof call.arguments, args.date);
} else {
console.log("No tool call");
}
Run the script again. Here’s one real run on Wednesday, December 2. Your IDs and date will differ:
status: 200
answer: ""
[ 'function_call' ]
{
arguments: '{"from":"Linden Harbor","to":"Gull Island","date":"2026-12-05"}',
call_id: 'call_1a57d8655002471c914103792b6e976e',
id: 'fc_0685f78218f54008006b0f9c1d7cec87d29114eae50996bb0e',
name: 'findSailings',
status: 'completed',
type: 'function_call'
}
string 2026-12-05
The one item is a function_call. Its name is your tool’s name, and arguments is a JSON string, so your code turns it into an object with JSON.parse(). The model turned “Saturday” into the date of the coming Saturday.
The item has two IDs, and your code needs call_id. When your code sends back the function’s result, it uses the same call_id, so the model can match the result to the request. You can find every field in OpenAI’s function calling guide.
The tool’s description costs tokens because it’s sent as input with every request. This run’s data.usage showed 185 input and 37 output tokens, about 0.074 cents at the gpt-6.2-sol model’s $2 per million input tokens and $10 per million output tokens.
Without tools, the same question used 58 input tokens, so this tool adds about 0.025 cents a request, or 25 cents per thousand, and each tool you add costs more. This lesson suggests three runs: the car question, the same script with these inspection lines, and a question about a dog that comes later. Together they cost about a quarter of a cent.
The request is a content block of type tool_use, and the response’s stop_reason is "tool_use". A reply can contain zero, one, or several requests. These lines print the stop reason and the type of every block. If there’s a tool_use block, they also print the first one and the type of its input:
tool-request.js
console.log(data.stop_reason);
console.log(data.content.map((block) => block.type));
const call = data.content.find(
(block) => block.type === "tool_use"
);
if (call) {
console.log(call);
console.log(typeof call.input, call.input.date);
} else {
console.log("No tool call");
}
This lesson’s runs used OpenAI because no Anthropic key was available, so there’s no Anthropic output here. Anthropic’s tool use documentation says what to expect. The first line these additions print is tool_use. The block list ends with tool_use, and it can start with a short text block, such as a note that the model is checking, so the answer: line may hold that note but never the sailings.
The tool_use block has type, id, name, and input, along with a caller field you can ignore here. Its name is your tool’s name, and input is already an object, such as { from: "Linden Harbor", to: "Gull Island", date: "2026-12-05" }, so the last line prints object and the date of the coming Saturday.
When your code sends back the function’s result, it uses the block’s id, so the model can match the result to the request.
The tool’s description costs tokens because it’s sent as input with every request. The same page says the API also builds a system prompt from your tool definitions, so a request with tools uses more input tokens. Print data.usage to see yours: at the claude-sonnet-5-5 model’s $2 per million input tokens and $10 per million output tokens, a request this size costs under a tenth of a cent.
With either provider, the reply contains a request with the tool’s name, an ID, and arguments that fit your schema. Nothing has run, and no sailing has been looked up. If your code ignores the request, the passenger gets no answer about their car, as your first run showed.
That split is the core of this course: the model asks, and your code decides whether to run what it asks for. Later, that’s where you’ll check arguments and refuse requests a passenger shouldn’t be able to make.
The button above opens the mentor, which asks you to explain that reply before you write the code that acts on it.
A tool doesn’t force a request, either. Change QUESTION to "Can I bring my dog on the ferry?" and run the script again.
In one real OpenAI run, the reply was text, “I don’t have Linden Ferries’ pet policy to hand. Please check with the ferry team before you travel,” and the last line was No tool call. No tool’s description fits pets. A description makes a call likely or unlikely, never certain.
Only a tool_choice setting can require a call. Both providers also have hosted tools, such as web search, that run on their servers, not in your code. That’s all you need about either for now: this course leaves tool_choice at its default, where the model may call a tool or answer in text, and uses only your own functions.
Open the mentor if you’d like feedback on writing a description and schema before the check below.
Check Your Understanding
Answer these questions before you open the answers:
- The ferry company wants the assistant to answer questions about a passenger’s booking, such as “Is my booking LF-2417 for two people or three?” Write a tool description with a name, a description that says when to use it, and a schema for its one argument.
- A teammate copies the tool entry from the OpenAI request into an Anthropic request. What has to change?
- A teammate runs
tool-request.jswith the car question, seesanswer: "", and decidesfindSailingsmust have failed. What would you tell them?
-
One answer uses
name: "lookUpBooking", with a description such as “Look up one booking by its reference, with its sailing, passengers and vehicle. Use it whenever a passenger asks about a booking they’ve made,” and a schema with one required property,reference, of type"string". Give the property adescriptionwith the format, such as “The booking reference, for example LF-2417,” and setadditionalProperties: false. -
With OpenAI, a tool has
type: "function"and its schema inparameters. With Anthropic, your own tool needs notype, though it accepts an optionaltype: "custom". Its schema goes ininput_schema. Thename,description, andstrictkeys are the same for both. -
Look at the rest of the response, not the empty text. The request to call
findSailingsthat you printed in the last section is there, with its arguments, and nothing ran because the model can’t run your functions. Your code has to run the function and send the result back before there’s an answer to print.
The model’s request is a job for your code: run findSailings against data/sailings.json, send the result back with the request’s ID, and ask the model again. In the next lesson, Run the Tool-Calling Loop, you’ll watch that exchange go back and forth until the passenger gets an answer.