A customer asks "Is The Rainbow Troops still in stock?", and the assistant answers "Yes, The Rainbow Troops has 12 in stock, priced at $18." Those numbers come straight from the Bookshop API, yet the model never touches your API. It works through function calling (Anthropic calls it tool use). You give the model a list of functions it may use. The model can then reply "please call checkStock with the title The Rainbow Troops" instead of answering right away. Your server runs that function and sends the result back to the model. Then the model answers with real data.
It's like a shop assistant who serves customers by phone but isn't allowed into the warehouse. They tell you, "please check the shelf for The Rainbow Troops". You walk to the warehouse and report "12 there", and they answer the customer. The assistant never touches the warehouse. In this picture, the assistant on the phone is the model, you are your server, and the warehouse is the Bookshop API and database.
A tool: name, description and JSON Schema
A tool (here, a function the model may ask for) is defined by three things: a name, a description of when to use it, and a JSON Schema for its arguments. JSON Schema is a standard format for describing the shape of some JSON: which fields it has, what their types are, and which are required. Here is the checkStock tool in OpenAI's Responses API (API reference and the "Function calling" guide, checked October 2026):
const tools = [
{
type: "function",
name: "checkStock",
description: "Check a book's stock and price at the Bookshop. Use it whenever a customer asks whether a book is available or what it costs.",
parameters: {
type: "object",
properties: {
title: { type: "string", description: "The book's title, for example The Rainbow Troops" },
},
required: ["title"],
additionalProperties: false,
},
strict: true,
},
];
- In the Responses API,
type: "function", thenname,description,parametersandstrictgo right on the tool object.parametersholds its JSON Schema. (Chat Completions, the older endpoint, wraps them once more insidefunction: {...}.) - The model reads
descriptionto decide when to use the tool. Write it as clearly as a briefing for a new employee, as in the Prompt Engineering lesson. strict: truemakes the model's arguments always match the schema. It has two conditions:additionalProperties: falseon every object, and every field listed inrequired. An optional field (one that may be empty) is writtentype: ["string", "null"]. If you leavestrictout, the Responses API tries to make the schema strict. If the schema doesn't meet the conditions, it returns to normal mode: the model tries to follow the schema, but nothing is guaranteed. In Chat Completions, a tool withoutstrictstays non-strict.- Tool definitions count as input tokens, so don't send 50 tools when you need 2.
The loop, step by step
Function calling runs as a loop (a round that repeats): the model asks for a tool, the server runs it, then the model reads the result. Here is that loop for "Is The Rainbow Troops still in stock?". The Lab runs the same loop with Indonesian names, titles and prices in rupiah. The model's replies in the Lab are hand-written stand-ins (fixed answers, not from a model), but their JSON shape follows the API reference.
| # | From, to | What it carries |
|---|---|---|
| 1 | Server, to OpenAI | input: the customer's question, tools: checkStock |
| 2 | OpenAI, to the server | item {"type":"function_call","call_id":"call_1","name":"checkStock","arguments":"{\"title\":\"The Rainbow Troops\"}"} |
| 3 | Server, to the Bookshop API | GET /books?q=The%20Rainbow%20Troops, answered 200 [{"id":1,"title":"The Rainbow Troops","price":18,"stock":12}] |
| 4 | Server, to OpenAI | the same input, plus the function_call item from step 2 and {"type":"function_call_output","call_id":"call_1","output":"[{\"title\":\"The Rainbow Troops\",\"price\":18,\"stock\":12}]"} |
| 5 | OpenAI, to the server | message: "Yes, The Rainbow Troops has 12 in stock, at $18." |
Step 3, GET /books?q=The%20Rainbow%20Troops, is run by the Bookshop server, not by the model. The model only writes JSON naming a function and its arguments. It can't touch your database or API. So function calling is the model's ability to decide when a function should be called and with which arguments. Your application code does the executing (running the function).
Here is the loop's code on the server, following the example in the "Function calling" guide. RULES is the content of instructions, tools is the tool list above, and runTool is in the next section:
import { toResponseInputItems } from "openai/lib/responses/ResponseInputItems";
async function askAssistant(question) {
const input = [{ role: "user", content: question }];
const ask = () => client.responses.create({ model: "gpt-6-luna", reasoning: { effort: "none" }, instructions: RULES, tools, input });
let res = await ask();
for (let round = 1; round <= 3; round++) {
const calls = res.output.filter((item) => item.type === "function_call");
if (calls.length === 0) return res.output_text; // the model has answered
input.push(...toResponseInputItems(res.output)); // keep the model's request in the history
for (const c of calls) {
const result = await runTool(c.name, c.arguments);
input.push({ type: "function_call_output", call_id: c.call_id, output: JSON.stringify(result) });
}
res = await ask();
}
if (!res.output.some((item) => item.type === "function_call")) return res.output_text; // the reply to request 4 is still read
return "Sorry, I can't answer that yet.";
}
res.outputcan hold zero, one or severalfunction_callitems. The guide says to always assume there may be more than one.- The model's request is kept in
inputthroughtoResponseInputItems, a helper function from the OpenAI SDK. Then every result is returned as afunction_call_outputwith the samecall_id, so the model knows which result belongs to which call. round <= 3caps the loop: at most 3 tool rounds, so at most 4 requests to the model. The reply to request 4 is still read before the function gives up. Without a cap, a model that keeps asking for tools can make requests without end, and every request is billed.
Validate the arguments on the server
strict: true guarantees the shape of the arguments, not their content. title can still be an empty string, 5,000 characters, or strange text from a prompt injection. So runTool checks the arguments before using them:
async function runTool(name, argsJson) {
if (name !== "checkStock") return { error: `unknown tool ${name}` };
let args;
try {
args = JSON.parse(argsJson); // arguments arrive as JSON text
} catch {
return { error: "the arguments are not valid JSON" };
}
const title = typeof args.title === "string" ? args.title.trim() : "";
if (title === "" || title.length > 100) return { error: "title is required, at most 100 characters" };
const res = await fetch(`https://api.bookshop.test/books?q=${encodeURIComponent(title)}`);
const books = await res.json();
return books.map((b) => ({ title: b.title, price: b.price, stock: b.stock }));
}
- Errors go back as the tool's result instead of being thrown. The model reads them, then can fix its arguments or explain the problem to the customer.
encodeURIComponentmakes the title safe to use in the URL. The Bookshop API itself still uses SQL placeholders (marks in the query that are filled with values separately), as in the API track.- In the Lab, turn
strictoff and ask for the price of This Earth of Mankind (Bumi Manusia there). The stand-in model first sends the title under the wrong field name, and validation rejects it. The model reads the error, then calls again with the right field name. With this lesson's English names, that is{"book":"This Earth of Mankind"}, then{"title":"This Earth of Mankind"}. So there are two rounds.
Tools that write: ask for confirmation first
checkStock only reads data, so it may run automatically. A tool that changes something needs more care, like orderBook, a tool for creating an order (POST /orders). The model can misread the customer (thinking they want to order when they only asked), or be tricked by malicious text. The rules:
- When the model asks for
orderBook({"book_id":1,"quantity":2}), the server does not callPOST /orders. It returns{"status":"awaiting_confirmation","total":36}to the model, then shows the customer a Confirm button. POST /ordersis only sent when the customer presses that button, through the normal endpoint with its own login session and permission checks.- Admin-only tools (changing prices, deleting books) are never given to the model.
The same shape at Anthropic
At Anthropic the idea is the same, but the field names differ (the "Tool use with Claude" docs, platform.claude.com, checked October 2026). A message there is made of blocks (parts of a message), and the model's request is a tool_use block. In this code, anthropic is the client from the Anthropic SDK, and messages is the conversation history:
const res = await anthropic.messages.create({
model: "claude-haiku-5-5",
max_tokens: 1024,
tools: [{ name: "checkStock", description: "Check a book's stock and price.", input_schema: { type: "object", properties: { title: { type: "string" } }, required: ["title"] } }],
messages,
});
// res.stop_reason === "tool_use"
const tu = res.content.find((b) => b.type === "tool_use"); // { type: "tool_use", id: "toolu_...", name: "checkStock", input: { title: "The Rainbow Troops" } }
messages.push(
{ role: "assistant", content: res.content },
{ role: "user", content: [{ type: "tool_result", tool_use_id: tu.id, content: JSON.stringify(await checkStock(tu.input.title)) }] },
);
Here is how it differs from the Responses API:
| OpenAI Responses | Anthropic Messages | |
|---|---|---|
| Argument schema | parameters |
input_schema |
| The model's request | a function_call item, arguments as JSON text in arguments |
a tool_use block, arguments already an object in input |
| The server's result | a function_call_output item with call_id |
a tool_result block with tool_use_id, in a user message |
| Marking an error | inside output, your own format |
is_error: true |
At Anthropic there are two rules about order. The user message carrying tool_result must come right after the assistant message with the tool_use. Inside that message, the tool_result blocks must come before any other text.
⚠️ What makes tools run carelessly, or not at all
- Thinking the model executes. The model only asks. If your server runs nothing, nothing happens. If your server runs whatever is asked, that's even more dangerous.
JSON.parsewithout validation.strictguarantees the shape, not the content. Check types, lengths and allowed values on the server.- Write tools that run automatically. Orders, payments and deletions need a click from the user, not a sentence from the model.
- A loop with no cap. Cap the rounds, and return errors as the tool's result instead of failing silently.
- A
call_idortool_use_idthat doesn't match. Each result must point to the right request, especially when the model asks for several tools at the same time.
TL;DR: Function calling (at Anthropic: tool use) lets the model decide when to call a function and with which arguments, but your application code does the executing. A tool (a function the model may ask for) is defined with type: "function", name, description, parameters (JSON Schema: the shape of its arguments) and strict: true (the arguments always match the schema, if every object has additionalProperties: false and every field is in required). The loop: the model replies with a function_call (a request to call a function). The server checks the arguments and calls the Bookshop API (GET /books?q=...). The result is returned as a function_call_output with the same call_id, then the model answers. Cap the number of rounds. At Anthropic: input_schema, a tool_use block, then a tool_result with tool_use_id in a user message. Tools that write (POST /orders) never run without the user's confirmation.
⚡ The model asks, the server runs
Guess first: in function calling, the AI model can ask for the function checkStock (it checks a book's stock) to be called. Who actually runs it, the model or your server?
Your server. The model only writes JSON naming a function and its arguments. It can't touch your database or API.
Meaning: In function calling, you give the model a list of functions it may use. The model decides when a function should be called and with which arguments. Your application code does the executing (running the function).
⚡ One tool: name, description, schema
Write:
const tools = [
{
type: "function",
name: "checkStock",
description: "Check a book's stock and price at the Bookshop. Use it whenever a customer asks whether a book is available or what it costs.",
parameters: {
type: "object",
properties: {
title: { type: "string", description: "The book's title, for example The Rainbow Troops" },
},
required: ["title"],
additionalProperties: false,
},
strict: true,
},
];
Meaning: A tool (a function the model may ask for) is defined by a name (name), a description (description) and a JSON Schema for its arguments (parameters): which fields, what types, and which are required. The model reads description to decide when to use the tool. strict: true makes its arguments always match the schema.
⚡ The loop: function_call, then function_call_output
Meaning: The model replies with a function_call item that names the tool and its arguments. The server validates (checks) the arguments, calls the Bookshop API (GET /books?q=...), then sends the result as a function_call_output with the same call_id (the id of that request). The model then answers from that result. Cap how many times this loop repeats, because every round is a new request, and every request is billed.
⚡ Tools that write need confirmation
Meaning: strict guarantees the shape of the arguments, not their content, so check types and lengths on the server. orderBook is a tool that creates an order. For this tool, the server only returns {"status":"awaiting_confirmation","total":36} to the model. POST /orders, which really creates the order, is only sent when the customer presses the Confirm button.