English

Artykuł · Tool use (wywoływanie funkcji) · Agenci AI

Tool use: jak model językowy wywołuje funkcje Twojej aplikacji

Model nie wykonuje kodu – proponuje wywołania narzędzi według schematu, a aplikacja je wykonuje i odsyła wyniki. Pętla tool use krok po kroku, dobre definicje narzędzi, błędy, równoległe wywołania, tool runner i bezpieczeństwo.

Autor · · 15 min czytania

Sam model językowy wie tylko to, co było w danych treningowych i w kontekście. Nie sprawdzi statusu zamówienia, nie zajrzy do bazy alergenów i nie wyśle SMS-a. Tool use (function calling) to mechanizm, w którym model dostaje opis dostępnych funkcji, a zamiast odpowiedzi tekstowej może zwrócić ustrukturyzowane żądanie: „wywołaj get_order_status z order_id = 1042”. Kod wykonuje Twoja aplikacja – model tylko decyduje, co i z jakimi argumentami wywołać.

4
kroki jednej rundy – definicje → tool_use → wykonanie → tool_result
1
wiadomość z wynikami – wszystkie tool_result naraz, nawet przy wielu wywołaniach
0
linii kodu wykonuje model – wykonanie, uprawnienia i skutki uboczne są po Twojej stronie

Problem: asystent, który zgaduje status zamówienia

Klient pisze na czacie pierogarni: „Gdzie jest moje zamówienie #1042 i czy pierogi ze szpinakiem mają orzechy?”. Asystent oparty na samym prompcie ma trzy złe wyjścia: zmyślić status („będzie za 15 minut”), odpowiedzieć z pamięci o alergenach (a receptura zmieniła się w zeszłym tygodniu) albo odesłać klienta do infolinii.

Pierwszy odruch programisty to wyrażenia regularne: wyłapać #\d+, zapytać bazę, wkleić wynik do promptu. Działa do pierwszego „a to drugie zamówienie, z wczoraj?” albo „czy ruskie są bez laktozy?”. Intencji i argumentów w języku naturalnym nie da się sensownie wyłuskać regułami – i właśnie to robi za nas model, gdy dostanie narzędzia.

Intuicja: model jako dyspozytor, aplikacja jako kuchnia

Na sali pierogarni kelnerka nie gotuje. Rozmawia z gościem, rozumie, czego chce, i wypisuje bloczek zamówienia w ustalonym formacie: danie, ilość, uwagi. Kuchnia realizuje bloczek i oddaje talerz, a kelnerka podaje go z komentarzem. Jeśli bloczek jest nieczytelny albo dania nie ma w karcie, kuchnia go odsyła.

W tool use model jest kelnerką: rozmawia i wypisuje „bloczki” zgodne ze schematem. Aplikacja jest kuchnią: waliduje, sprawdza uprawnienia, wykonuje i oddaje wynik – albo błąd. Kelnerka nigdy nie wchodzi do chłodni.

Diagram: Jedna rozmowa z narzędziami: model proponuje wywołania, aplikacja je wykonuje

Anatomia definicji narzędzia

PoleCo zawieraNa co uważać
namekrótka, jednoznaczna nazwa: get_order_status, nie ordernazwa pojawia się w historii; nie zmieniaj jej bez potrzeby
descriptionco robi narzędzie, kiedy go użyć, czego nie zwraca, ograniczeniato najważniejsze pole – za krótki opis to najczęstsza przyczyna złych wyborów
input_schemaJSON Schema argumentów z opisami pól, enum, requirednazwy i opisy pól to wskazówki dla modelu – pisz je jak dokumentację API
stricttrue gwarantuje argumenty zgodne ze schematemwymaga additionalProperties: false i listy required

Opis narzędzia to „strona podręcznika”, nie miejsce na krzyki. „Use it whenever the customer asks where an order is” działa lepiej niż „YOU MUST ALWAYS USE THIS TOOL”, które w nowych modelach prowadzi do nadużywania narzędzia. Instrukcje typu „nigdy nie odpowiadaj o alergenach z pamięci” mają jednak sens, gdy niosą uzasadnienie (receptury się zmieniają).

Pętla tool use krok po kroku

  1. Wysyłasz wiadomości i listę narzędzi.
  2. Jeśli model chce skorzystać z narzędzia, odpowiedź ma stop_reason: "tool_use" i zawiera jeden lub więcej bloków tool_use z id, name i input.
  3. Dopisujesz całą odpowiedź asystenta do historii (z blokami myślenia i tool_use – bez zmian).
  4. Wykonujesz każde wywołanie i budujesz bloki tool_result z pasującym tool_use_id. Błędy oznaczasz is_error: true z czytelnym komunikatem.
  5. Wysyłasz wszystkie wyniki w jednej wiadomości użytkownika i wracasz do kroku 2 – aż model odpowie tekstem (end_turn) albo skończy się limit rund.

Pętla tool use napisana ręcznie

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
}

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • Tool runner: pętla, której nie musisz pisać
  • tool_choice, strict i równoległe wywołania
  • Narzędzia klienckie i serwerowe
  • Koszt narzędzi: definicje też są tokenami
  • Kiedy tool use, a kiedy nie
  • Lista kontrolna przed produkcją
  • Sprawdź się
  • Co dalej

Załóż darmowe konto · Zaloguj się