Function calling explained with a shopping cart
From the work/ 13 min read
Function calling with a shopping cart: three tools in Node, the tool_use and tool_result loop, errors with is_error and what your code must validate.
- AI
- Node.js
In this article (8)
Function calling is how an AI model uses functions in your code. You describe each tool with a name, a description and a JSON schema; the model runs nothing. It replies with a request to call a tool with arguments, your code runs it and sends back the result so the model can answer the customer.
This guide builds it around a store: a shopping assistant with three tools, search_products, add_to_cart and calculate_shipping, in Node with TypeScript and the official @anthropic-ai/sdk. The request and response shapes come from Anthropic's tool use documentation, checked on November 19, 2026. We tested the loop with a mocked client that returns responses in that shape, without calling the paid API. The products, prices, stock levels and shipping rule in the example are illustrative.
What a tool is in function calling
Anthropic calls it tool use and notes that it is also called function calling. A tool is a definition you send in the tools parameter of every request, with three parts: a name that matches ^[a-zA-Z0-9_-]{1,128}$, a plain-text description, and an input_schema in JSON Schema that lists the parameters it expects. You do not send code. The model never sees your function, only its description.
When the model decides to use a tool, the response comes back with stop_reason: "tool_use" and one or more tool_use blocks, each with an id, the tool's name and an input object with the arguments. Running the function is your job. There is a second kind, server tools (web search, code execution), which run on Anthropic's infrastructure; a cart does not need them, because your data lives in your own database.
The difference from a RAG chatbot is the kind of help: a RAG chatbot gives the model text to read, while function calling gives it actions your code controls. And if all you want is data in a fixed shape, with nothing to execute, what you need is structured outputs for valid JSON, which use the same schema machinery.
The docs are clear about what matters most: a detailed description is "by far the most important factor" in tool performance. They ask for at least three or four sentences per tool: what it does, when to use it and when not to, what each parameter means, and what it does not return.
Defining search_products, add_to_cart and calculate_shipping
The three tools cover a purchase up to the point of paying: find the product, put it in the cart and find out what shipping costs. All three are built by the same small function, so the schema boilerplate is written once. Here is that function with the add_to_cart definition; the full file is in the guide:
// Strict schema: every field required, no extra fields.
const tool = (name: string, description: string, properties: Record<string, object>): Anthropic.Tool => ({
name,
description,
strict: true,
input_schema: { type: "object", properties, required: Object.keys(properties), additionalProperties: false },
});
export const tools: Anthropic.Tool[] = [
// search_products and calculate_shipping are built the same way (full file in the guide)
tool(
"add_to_cart",
"Adds a product to the current session's cart. Needs the exact sku returned by search_products and a whole quantity from 1 to 10. If there is not enough stock, it returns an error with the units available. The store sets the price; it is not an input.",
{
sku: { type: "string", description: "Exact SKU, for example MUG-12OZ" },
quantity: { type: "integer", description: "Units to add, from 1 to 10" },
},
),
];
toolreturns the object the API expects:name,description,strictandinput_schema. The SDK'sAnthropic.Tooltype checks the shape.strict: trueturns on strict tool use, which makes everyinputfollow the schema: correct types, required fields present and a valid tool name.required: Object.keys(properties)makes every field mandatory, andadditionalProperties: falseblocks extra fields, such as a price nobody asked for. Strict mode requires thatfalse.- The name,
add_to_cart, uses underscores, because the pattern only allows letters, digits, hyphens and underscores. - The description says what the tool does, where the
skucomes from (search_products), the quantity range, what happens when stock runs out, and that the price is not an input. - The properties define two fields,
skuas a string andquantityas an integer, so you never get"2"or"two".
Something is missing on purpose: minimum and maximum. Strict mode does not support numeric or length constraints, and the API answers with a 400 error if you include them. That is why the 1 to 10 limit lives in the description, so the model knows it, and in your code, so it holds.
Scroll the figure sideways to see all of it
The loop: the model asks, your code runs, the model answers
The docs describe five steps. Run each tool a tool_use block names; in a new request, keep the earlier messages and add the response's content, unchanged, as an assistant message; add a user message with one tool_result for each tool_use, even if the tool failed; send the same tools again; and if the next response also has stop_reason: "tool_use", repeat. One exchange, shortened, looks like this:
// Model response (shortened)
{
"stop_reason": "tool_use",
"content": [
{ "type": "text", "text": "Let me find the mugs." },
{ "type": "tool_use", "id": "toolu_01A", "name": "search_products", "input": { "query": "mug" } }
]
}
// Your next message: the result, with the same id
{
"role": "user",
"content": [
{ "type": "tool_result", "tool_use_id": "toolu_01A", "content": "[{\"sku\":\"MUG-12OZ\",\"price\":1400,\"available\":12}]" }
]
}
The tool_use_id is what ties each result to its request. This is the whole loop in TypeScript, the same code that passed the tests:
const MAX_TURNS = 6;
export async function converse(client: Anthropic, question: string, cart: Cart) {
const messages: Anthropic.MessageParam[] = [{ role: "user", content: question }];
for (let turn = 0; turn < MAX_TURNS; turn++) {
const res = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 16000,
system: SYSTEM,
tools,
messages,
});
if (res.stop_reason !== "tool_use") {
// end_turn is the normal answer; refusal or max_tokens go back to the caller.
const text = res.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("\n");
return { text, stop: res.stop_reason, messages };
}
messages.push({ role: "assistant", content: res.content }); // unchanged, thinking blocks included
const results: Anthropic.ToolResultBlockParam[] = [];
for (const block of res.content) {
if (block.type !== "tool_use") continue;
try {
const output = runTool(block.name, block.input, cart);
results.push({ type: "tool_result", tool_use_id: block.id, content: output });
} catch (err) {
if (!(err instanceof ToolError)) console.error(block.name, err); // log the real cause, don't send it
const message = err instanceof ToolError ? err.message : "Internal store error. Try again later.";
results.push({ type: "tool_result", tool_use_id: block.id, content: message, is_error: true });
}
}
messages.push({ role: "user", content: results }); // every result, in one message
}
throw new Error(`No final answer after ${MAX_TURNS} turns.`);
}
conversetakes the client, the question and the session's cart. The cart is never a model argument: your server provides it.- The
forcaps the loop at six turns. Without a cap, a model retrying a broken tool can stay in the loop and burn tokens. client.messages.createsends the model (claude-opus-5-5), thesystemprompt, thetoolsand the full history. The Messages API does not keep the conversation for you, so you resend all of it.- If
stop_reasonis nottool_use, the reply is finished:end_turnis the normal answer, whilerefusalormax_tokensgo back to the caller to decide. - The assistant
contentgoes into the history as is, with its text, reasoning and tool blocks. - The
for...ofwalks the blocks, because the model can ask for several tools in one response, for example adding to the cart and calculating shipping. - Each result carries its block's
tool_use_id. Failures go back as a result withis_error: true; they are never dropped. - All results go together in a single
usermessage at the end of the turn.
Scroll the figure sideways to see all of it
By default the model decides whether to call a tool or answer directly. tool_choice controls that, and on the newest models it changed:
tool_choice | What it does | Claude Opus 5.5 |
|---|---|---|
{"type": "auto"} | The model decides; the default when you send tools | Yes |
{"type": "none"} | No tools are used | Yes |
{"type": "any"} | Must use one of the tools | No: 400 error |
{"type": "tool", "name": "..."} | Must use that tool | No: 400 error |
According to the define tools page, forcing with any or tool returns a 400 on Claude Opus 5.5, Claude Sonnet 5.5, Claude Fable 5.2 and 5.1, and Claude Mythos 5.2 and 5.1; Claude Opus 5 and older models accept it. The suggested alternative is auto with strict: true and instructions in the prompt. With auto you can also set disable_parallel_tool_use: true to get at most one tool call per response.
Handling tool errors
There are three kinds of error, and each one is handled differently. The first is the kind the model can fix: a sku that does not exist, a quantity out of range, a four-digit ZIP code. It goes back as a tool_result with is_error: true and a message that says what went wrong and what to do, as the handle tool calls page recommends: not "failed", but "SKU INVENTED-1 does not exist. Use search_products to get it.". The model may call the tool again with corrected input, which is why the loop has a cap.
The second is your own failure: the database is down or there is a bug. Send the model a generic message with is_error: true and put the real detail in your logs. A stack trace inside a tool_result does not help the model and can end up in the reply to the customer.
The third is a format error, and the API returns it as a 400. The tool_result blocks must be in the message right after the one with the tool_use, with nothing in between, and they come first in the content array; any text goes after them. If a result is missing you get an error such as "tool_use ids were found without tool_result blocks immediately after". Network errors, rate limits (429) and server errors are retried by the SDK: maxRetries defaults to 2, and when retries run out it throws typed errors such as Anthropic.RateLimitError.
Validating what the model asks for
In the SDK types, input is unknown, and that is how you should treat it: as user input. Strict mode guarantees the shape, not your business rules. A perfectly formatted sku may not exist, and a valid integer may be 50 when only 3 are left. This is the add_to_cart case inside the function that runs the tools:
// inside runTool(name, input, cart), after: const args = fields(input);
case "add_to_cart": {
const product = CATALOG.find((p) => p.sku === args.sku);
if (!product) throw new ToolError(`SKU ${String(args.sku)} does not exist. Use search_products to get it.`);
const quantity = args.quantity;
if (typeof quantity !== "number" || !Number.isInteger(quantity) || quantity < 1 || quantity > MAX_PER_ITEM) {
throw new ToolError(`Quantity must be a whole number from 1 to ${MAX_PER_ITEM}.`);
}
const total = (cart.get(product.sku) ?? 0) + quantity;
if (total > product.stock) throw new ToolError(`Only ${product.stock} units of ${product.sku} are available.`);
cart.set(product.sku, total);
return JSON.stringify({ sku: product.sku, quantity: total, subtotal: subtotal(cart) });
}
- It looks up the product with the
skuthe model sent. If there is none, the error tells the model how to get a real one. - It checks that the quantity is a whole number from 1 to 10, the limit the strict schema cannot express.
- It adds what is already in the cart and compares the total with the stock, so two calls for 8 cannot put 16 units of a product with 12 in the cart.
- It saves the quantity and returns a subtotal computed from the catalog price, never from a price sent by the model.
Scroll the figure sideways to see all of it
Beyond each tool's code, four design rules. First, accept nothing from the model that your server already knows: price, discount, cart ID and customer ID come from the session and the database. Second, give it no tool that charges money or confirms orders; the customer pays at checkout, with their own click. Third, treat what your tools return as untrusted when it comes from third parties, such as reviews or supplier descriptions: Anthropic warns that this content can carry hidden instructions and recommends keeping it inside tool_result blocks. Fourth, checking stock when adding to the cart does not reserve it: if two people buy the last unit, that is the inventory overselling problem, and you solve it at payment time. If the assistant is public, also add rate limiting per session.
Common mistakes
- One-line descriptions. "Adds to cart" says nothing about where the
skucomes from or the quantity range, so the model guesses. - Relying on
strictfor business rules. It guarantees types and fields, not that the product exists or is in stock. - Putting
minimumormaximumin a strict schema. The API returns a 400; the limit belongs in your code. - Sending results in several messages, or with text first. Every
tool_resultgoes together in the nextusermessage, first. - Dropping the result of a tool that failed. Every
tool_useneeds itstool_result, withis_error: trueif it failed. - Using
tool_choice: anyon Claude Opus 5.5. It returns a 400. Useautoand say it in the prompt. - A loop with no cap. Set a maximum number of turns.
Frequently asked questions
Are function calling and tool use the same thing?
Yes. Anthropic uses "tool use" and says it is also called function calling. Other APIs use special roles such as tool or function; in the Claude API, tool_use and tool_result blocks travel inside the assistant and user messages.
Can I force the model to call a tool?
It depends on the model. On Claude Opus 5 and older, yes, with tool_choice set to any or tool. On Claude Opus 5.5, Sonnet 5.5, and Fable and Mythos 5.1 and 5.2 that returns a 400: use auto, ask for the tool in the prompt and check whether a tool_use block came back.
Do I have to write the loop by hand?
No. The SDK ships a tool runner that runs your functions and sends the results for you. Writing the loop once by hand shows you what happens and lets you control limits, logging and errors your way; the loop above is about 40 lines.
How many tokens do tools cost?
Tool definitions, tool_use blocks and tool_result blocks count as normal tokens. On top of that, sending tools makes the API add its own system prompt: per the docs, 286 tokens on Claude Opus 5.5 with auto or none. Longer descriptions cost a little more, but they are what improves the calls the most.
Checklist
- Every tool has a valid name and a three- or four-sentence description.
- Schemas have
strict: true,requiredandadditionalProperties: false. - Numeric limits are in the description and in your code, not in the schema.
- The assistant
contentgoes back into the history unchanged. - Every
tool_usegets atool_resultwith its id, all in one message. - Fixable errors go back with
is_error: trueand a message that says what to do. - The loop has a turn cap and handles
refusalandmax_tokens. - Price, cart and customer come from your server, never from the model.
- No tool charges money or confirms orders.
With this in place, the model can work the cart without touching anything it should not. If you later want it to answer questions with your shipping and returns policies, the next step is giving it your documents with RAG.
Saw this on Instagram? Comment TOOLS on the Reel and I'll send you the guide.
Written by

Published November 19, 2026