Polski

Article · Tool use (function calling) · AI agents

Tool use: how a language model calls your application's functions

The model does not run code – it proposes tool calls that follow a schema, and your application executes them and sends the results back. The tool use loop step by step, good tool definitions, errors, parallel calls, the tool runner and security.

By · · 17 min read

On its own, a language model knows only what was in its training data and in the context. It will not check an order's status, look into the allergen database or send a text message. Tool use (function calling) is the mechanism in which the model receives a description of available functions and, instead of a text answer, can return a structured request: "call get_order_status with order_id = 1042". Your application runs the code – the model only decides what to call and with which arguments.

4
steps in one round – definitions → tool_use → execution → tool_result
1
message with the results – all tool_results together, even for several calls
0
lines of code run by the model – execution, permissions and side effects are on your side

The problem: an assistant that guesses the order status

A customer writes in the pierogi chat: "Where is my order #1042, and do the spinach pierogi contain nuts?". An assistant built on a prompt alone has three bad options: invent a status ("it will be there in 15 minutes"), answer about allergens from memory (and the recipe changed last week) or send the customer to the hotline.

A developer's first instinct is regular expressions: catch #\d+, query the database, paste the result into the prompt. That works until the first "and what about the other order, from yesterday?" or "are the ruskie lactose-free?". You cannot sensibly extract intent and arguments from natural language with rules – and that is exactly what the model does for us once it gets tools.

Intuition: the model as a dispatcher, the application as the kitchen

In the pierogi restaurant the waitress does not cook. She talks to the guest, understands what they want and writes an order slip in an agreed format: dish, quantity, notes. The kitchen fulfils the slip and hands back a plate, and the waitress serves it with a comment. If the slip is illegible or the dish is not on the menu, the kitchen sends it back.

In tool use the model is the waitress: it talks and writes "slips" that follow the schema. The application is the kitchen: it validates, checks permissions, executes and hands back a result – or an error. The waitress never walks into the cold room.

Diagram: One conversation with tools: the model proposes calls, the application executes them

The anatomy of a tool definition

FieldContainsWatch out for
namea short, unambiguous name: get_order_status, not orderthe name appears in the history; do not rename it without reason
descriptionwhat the tool does, when to use it, what it does not return, limitationsthe most important field – too short a description is the most common cause of bad choices
input_schemaJSON Schema of the arguments with field descriptions, enum, requiredfield names and descriptions are hints for the model – write them like API docs
stricttrue guarantees arguments that match the schemarequires additionalProperties: false and a required list

A tool description is a "man page", not a place for shouting. "Use it whenever the customer asks where an order is" works better than "YOU MUST ALWAYS USE THIS TOOL", which on new models leads to overusing the tool. Instructions like "never answer allergen questions from memory" do make sense, though, when they carry a reason (recipes change).

The tool use loop step by step

  1. You send the messages and the list of tools.
  2. If the model wants to use a tool, the response has stop_reason: "tool_use" and contains one or more tool_use blocks with an id, name and input.
  3. You append the whole assistant response to the history (thinking and tool_use blocks included – unchanged).
  4. You execute every call and build tool_result blocks with the matching tool_use_id. You mark failures with is_error: true and a readable message.
  5. You send all results in one user message and return to step 2 – until the model answers with text (end_turn) or you run out of rounds.

A hand-written tool use loop

order_assistant.py
import anthropic

client = anthropic.Anthropic()

# Stand-ins for the real order service and menu database.
ORDERS = {"1042": {"customer_id": "c-7", "status": "in_delivery", "eta_minutes": 12}}
ALLERGENS = {"spinach pierogi": ["gluten", "milk", "walnuts"], "ruskie pierogi": ["gluten", "milk"]}

TOOLS = [
    {
        "name": "get_order_status",
        "description": "Returns status and ETA of one of the signed-in customer's orders. "
        "Use it whenever the customer asks where an order is or when it will arrive.",
        "strict": True,
        "input_schema": {
            "type": "object",
            "properties": {"order_id": {"type": "string", "description": "Order number without '#', e.g. 1042"}},
            "required": ["order_id"],
            "additionalProperties": False,
        },
    },
    {
        "name": "check_allergens",
        "description": "Returns the allergens of a menu item. Use it for every question about "
        "ingredients or allergies - menu recipes change, so never answer those from memory.",
        "strict": True,
        "input_schema": {
            "type": "object",
            "properties": {"dish": {"type": "string", "description": "Dish name as on the menu"}},
            "required": ["dish"],
            "additionalProperties": False,
        },
    },
]


def run_tool(name: str, args: dict, customer_id: str) -> str:
    if name == "get_order_status":
        order = ORDERS.get(args["order_id"])
        # Authorization lives in code: the model never decides whose data it may see.
        if order is None or order["customer_id"] != customer_id:
            raise LookupError(f"No order {args['order_id']} for this customer.")
        return f"status={order['status']}, eta={order['eta_minutes']} min"
    if name == "check_allergens":
        allergens = ALLERGENS.get(args["dish"].lower())
        if allergens is None:
            raise LookupError(f"Unknown dish '{args['dish']}'. Ask the customer to pick from the menu.")
        return ", ".join(allergens)
    raise LookupError(f"Unknown tool {name}")


def answer(question: str, customer_id: str, max_rounds: int = 5) -> str:
    messages = [{"role": "user", "content": question}]
    for _ in range(max_rounds):
        response = client.messages.create(
            model="claude-opus-5-5", max_tokens=4096, tools=TOOLS, messages=messages
        )
        if response.stop_reason != "tool_use":
            if response.stop_reason in ("max_tokens", "refusal"):
                raise RuntimeError(f"Stopped early: {response.stop_reason}")
            return "".join(b.text for b in response.content if b.type == "text")

        messages.append({"role": "assistant", "content": response.content})
        results = []
        for block in response.content:  # the model may request several tools at once
            if block.type != "tool_use":
                continue
            try:
                output = run_tool(block.name, block.input, customer_id)
                results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
            except LookupError as err:
                results.append({"type": "tool_result", "tool_use_id": block.id, "content": str(err), "is_error": True})
        messages.append({"role": "user", "content": results})  # all results in ONE message
    raise RuntimeError("Too many tool rounds")


print(answer("Where is order #1042, and do the spinach pierogi contain nuts?", customer_id="c-7"))
order-assistant.ts
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

// Stand-ins for the real order service and menu database.
const ORDERS: Record<string, { customerId: string; status: string; etaMinutes: number }> = {
  "1042": { customerId: "c-7", status: "in_delivery", etaMinutes: 12 },
};
const ALLERGENS: Record<string, string[]> = { "spinach pierogi": ["gluten", "milk", "walnuts"] };

const tools: Anthropic.Tool[] = [
  {
    name: "get_order_status",
    description:
      "Returns status and ETA of one of the signed-in customer's orders. " +
      "Use it whenever the customer asks where an order is or when it will arrive.",
    strict: true,
    input_schema: {
      type: "object",
      properties: { order_id: { type: "string", description: "Order number without '#', e.g. 1042" } },
      required: ["order_id"],
      additionalProperties: false,
    },
  },
  {
    name: "check_allergens",
    description:
      "Returns the allergens of a menu item. Use it for every question about ingredients " +
      "or allergies - menu recipes change, so never answer those from memory.",
    strict: true,
    input_schema: {
      type: "object",
      properties: { dish: { type: "string", description: "Dish name as on the menu" } },
      required: ["dish"],
      additionalProperties: false,
    },
  },
];

function runTool(name: string, input: Record<string, string>, customerId: string): string {
  if (name === "get_order_status") {
    const order = ORDERS[input.order_id];
    // Authorization lives in code: the model never decides whose data it may see.
    if (!order || order.customerId !== customerId) throw new Error(`No order ${input.order_id} for this customer.`);
    return `status=${order.status}, eta=${order.etaMinutes} min`;
  }
  if (name === "check_allergens") {
    const allergens = ALLERGENS[input.dish.toLowerCase()];
    if (!allergens) throw new Error(`Unknown dish '${input.dish}'. Ask the customer to pick from the menu.`);
    return allergens.join(", ");
  }
  throw new Error(`Unknown tool ${name}`);
}

export async function answer(question: string, customerId: string, maxRounds = 5): Promise<string> {
  const messages: Anthropic.MessageParam[] = [{ role: "user", content: question }];
  for (let round = 0; round < maxRounds; round++) {
    const response = await client.messages.create({ model: "claude-opus-5-5", max_tokens: 4096, tools, messages });
    if (response.stop_reason !== "tool_use") {
      if (response.stop_reason === "max_tokens" || response.stop_reason === "refusal") {
        throw new Error(`Stopped early: ${response.stop_reason}`);
      }
      return response.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
    }

    messages.push({ role: "assistant", content: response.content });
    const results: Anthropic.ToolResultBlockParam[] = [];
    for (const block of response.content) {
      if (block.type !== "tool_use") continue; // the model may request several tools at once
      try {
        const output = runTool(block.name, block.input as Record<string, string>, customerId);
        results.push({ type: "tool_result", tool_use_id: block.id, content: output });
      } catch (err) {
        results.push({ type: "tool_result", tool_use_id: block.id, content: String(err), is_error: true });
      }
    }
    messages.push({ role: "user", content: results }); // all results in ONE message
  }
  throw new Error("Too many tool rounds");
}

console.log(await answer("Where is order #1042, and do the spinach pierogi contain nuts?", "c-7"));
OrderAssistant.cs
using System.Text.Json;
using Anthropic;
using Anthropic.Models.Messages;

AnthropicClient client = new();

// Raw JSON Schema; strict tools need additionalProperties: false.
static InputSchema Schema(string json) =>
    InputSchema.FromRawUnchecked(JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(json)!);

List<ToolUnion> tools =
[
    new Tool
    {
        Name = "get_order_status",
        Description = "Returns status and ETA of one of the signed-in customer's orders. " +
                      "Use it whenever the customer asks where an order is or when it will arrive.",
        Strict = true,
        InputSchema = Schema("""
            {"type":"object","properties":{"order_id":{"type":"string","description":"Order number without '#'"}},
             "required":["order_id"],"additionalProperties":false}
            """),
    },
];

string RunTool(string name, IReadOnlyDictionary<string, JsonElement> input, string customerId)
{
    // Authorization lives in code: the model never decides whose data it may see.
    var orderId = input["order_id"].GetString();
    if (name == "get_order_status" && orderId == "1042" && customerId == "c-7")
        return "status=in_delivery, eta=12 min";
    throw new InvalidOperationException($"No order {orderId} for this customer.");
}

List<MessageParam> messages = [new UserMessageParam { Content = "Where is order #1042?" }];
for (var round = 0; round < 5; round++)
{
    var response = await client.Messages.Create(new MessageCreateParams
    {
        Model = "claude-opus-5-5", MaxTokens = 4096, Tools = tools, Messages = messages,
    });
    if (response.StopReason != "tool_use")
    {
        foreach (var text in response.Content.Select(b => b.Value).OfType<TextBlock>())
            Console.WriteLine(text.Text);
        break;
    }

    // Echo the assistant turn (no ToParam helper in C#) and collect ALL tool results.
    List<ContentBlockParam> assistant = [];
    List<ContentBlockParam> results = [];
    foreach (var block in response.Content)
    {
        if (block.TryPickText(out var text)) assistant.Add(new TextBlockParam { Text = text.Text });
        else if (block.TryPickThinking(out var th))
            assistant.Add(new ThinkingBlockParam { Thinking = th.Thinking, Signature = th.Signature });
        else if (block.TryPickToolUse(out var call))
        {
            assistant.Add(new ToolUseBlockParam { ID = call.ID, Name = call.Name, Input = call.Input });
            try
            {
                results.Add(new ToolResultBlockParam { ToolUseID = call.ID, Content = RunTool(call.Name, call.Input, "c-7") });
            }
            catch (Exception ex)
            {
                results.Add(new ToolResultBlockParam { ToolUseID = call.ID, Content = ex.Message, IsError = true });
            }
        }
    }
    messages.Add(new AssistantMessageParam { Content = assistant });
    messages.Add(new UserMessageParam { Content = results }); // all results in ONE message
}

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • The tool runner: a loop you don't have to write
  • tool_choice, strict and parallel calls
  • Client tools and server tools
  • The cost of tools: definitions are tokens too
  • When to use tools, and when not
  • Pre-production checklist
  • Test yourself
  • What's next

Create a free account · Sign in