{"id":"6b08c25038c84264c20274dc","slug":"tool-use","title":"Tool use: jak model językowy wywołuje funkcje Twojej aplikacji","summary":"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.","servedLang":"pl","availableLangs":["pl","en"],"topics":["tool-use","ai-agents","mcp","ai-guardrails"],"techs":["python","typescript","dotnet"],"tags":["tool-use","function-calling","json-schema","structured-outputs","tool-runner","claude"],"level":"intermediate","kind":"article","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":15,"stats":{"views":3,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:35:44.634Z","updatedAt":"2026-11-27T10:04:53.384Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"rose","background":"hex","weaveResources":true,"toc":"right"},"seoDescription":"Tool use (function calling) dla programistów: definicje narzędzi w JSON Schema, pętla tool_use i tool_result, strict, tool_choice, równoległe wywołania, obsługa błędów, tool runner i autoryzacja. Kod w Pythonie, TypeScript i C#.","wordCount":2993,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"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. "},{"type":"text","text":"Tool use","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"function calling","marks":[{"type":"italic"}]},{"type":"text","text":") to mechanizm, w którym model dostaje opis dostępnych funkcji, a zamiast odpowiedzi tekstowej może zwrócić ustrukturyzowane żądanie: „wywołaj "},{"type":"text","text":"get_order_status","marks":[{"type":"code"}]},{"type":"text","text":" z "},{"type":"text","text":"order_id = 1042","marks":[{"type":"code"}]},{"type":"text","text":"”. Kod wykonuje "},{"type":"text","text":"Twoja aplikacja","marks":[{"type":"bold"}]},{"type":"text","text":" – model tylko decyduje, co i z jakimi argumentami wywołać."}]},{"type":"stats","attrs":{"items":[{"value":"4","label":"kroki jednej rundy","hint":"definicje → tool_use → wykonanie → tool_result"},{"value":"1","label":"wiadomość z wynikami","hint":"wszystkie tool_result naraz, nawet przy wielu wywołaniach"},{"value":"0","label":"linii kodu wykonuje model","hint":"wykonanie, uprawnienia i skutki uboczne są po Twojej stronie"}]}},{"type":"callout","attrs":{"variant":"info","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Narzędzie to nazwa, opis i schemat JSON argumentów. Opis jest najważniejszy: mówi modelowi, "},{"type":"text","text":"kiedy","marks":[{"type":"bold"}]},{"type":"text","text":" narzędzia użyć i czego ono nie zwraca."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Pętla: model zwraca bloki "},{"type":"text","text":"tool_use","marks":[{"type":"code"}]},{"type":"text","text":" ("},{"type":"text","text":"stop_reason: \"tool_use\"","marks":[{"type":"code"}]},{"type":"text","text":"), aplikacja je wykonuje i odsyła bloki "},{"type":"text","text":"tool_result","marks":[{"type":"code"}]},{"type":"text","text":" w jednej wiadomości użytkownika – aż model odpowie tekstem."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Autoryzacja, limity i potwierdzenia ryzykownych akcji należą do kodu. Model może poprosić o cudze zamówienie; to aplikacja musi odmówić."}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"problem-asystent-ktory-zgaduje-status-zamowienia"},"content":[{"type":"text","text":"Problem: asystent, który zgaduje status zamówienia"}]},{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"paragraph","content":[{"type":"text","text":"Pierwszy odruch programisty to wyrażenia regularne: wyłapać "},{"type":"text","text":"#\\d+","marks":[{"type":"code"}]},{"type":"text","text":", 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."}]},{"type":"heading","attrs":{"level":2,"id":"intuicja-model-jako-dyspozytor-aplikacja-jako-kuchnia"},"content":[{"type":"text","text":"Intuicja: model jako dyspozytor, aplikacja jako kuchnia"}]},{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"sequenceDiagram\n  participant K as Klient\n  participant A as Aplikacja\n  participant M as Model (API)\n  participant S as Serwis zamówień\n  K->>A: „Gdzie jest zamówienie 1042? Czy szpinakowe mają orzechy?”\n  A->>M: wiadomość + definicje narzędzi\n  M-->>A: tool_use: get_order_status(1042)<br/>tool_use: check_allergens(spinach pierogi)\n  A->>S: autoryzacja + zapytania\n  S-->>A: in_delivery, 12 min · gluten, mleko, orzechy włoskie\n  A->>M: tool_result × 2 (jedna wiadomość)\n  M-->>A: tekst: „Kurier będzie za ok. 12 minut. Uwaga: sos zawiera orzechy włoskie.”\n  A->>K: odpowiedź","caption":"Jedna rozmowa z narzędziami: model proponuje wywołania, aplikacja je wykonuje"}},{"type":"heading","attrs":{"level":2,"id":"anatomia-definicji-narzedzia"},"content":[{"type":"text","text":"Anatomia definicji narzędzia"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Pole"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Co zawiera"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Na co uważać"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"name","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"krótka, jednoznaczna nazwa: "},{"type":"text","text":"get_order_status","marks":[{"type":"code"}]},{"type":"text","text":", nie "},{"type":"text","text":"order","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nazwa pojawia się w historii; nie zmieniaj jej bez potrzeby"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"description","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"co robi narzędzie, "},{"type":"text","text":"kiedy","marks":[{"type":"bold"}]},{"type":"text","text":" go użyć, czego nie zwraca, ograniczenia"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"to najważniejsze pole – za krótki opis to najczęstsza przyczyna złych wyborów"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"input_schema","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"JSON Schema argumentów z opisami pól, "},{"type":"text","text":"enum","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"required","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nazwy i opisy pól to wskazówki dla modelu – pisz je jak dokumentację API"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"strict","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"true","marks":[{"type":"code"}]},{"type":"text","text":" gwarantuje argumenty zgodne ze schematem"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"wymaga "},{"type":"text","text":"additionalProperties: false","marks":[{"type":"code"}]},{"type":"text","text":" i listy "},{"type":"text","text":"required","marks":[{"type":"code"}]}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"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ą)."}]},{"type":"heading","attrs":{"level":2,"id":"petla-tool-use-krok-po-kroku"},"content":[{"type":"text","text":"Pętla tool use krok po kroku"}]},{"type":"orderedList","attrs":{"start":1},"content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Wysyłasz wiadomości i listę narzędzi."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Jeśli model chce skorzystać z narzędzia, odpowiedź ma "},{"type":"text","text":"stop_reason: \"tool_use\"","marks":[{"type":"code"}]},{"type":"text","text":" i zawiera jeden lub więcej bloków "},{"type":"text","text":"tool_use","marks":[{"type":"code"}]},{"type":"text","text":" z "},{"type":"text","text":"id","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"name","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"input","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Dopisujesz "},{"type":"text","text":"całą","marks":[{"type":"bold"}]},{"type":"text","text":" odpowiedź asystenta do historii (z blokami myślenia i "},{"type":"text","text":"tool_use","marks":[{"type":"code"}]},{"type":"text","text":" – bez zmian)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Wykonujesz każde wywołanie i budujesz bloki "},{"type":"text","text":"tool_result","marks":[{"type":"code"}]},{"type":"text","text":" z pasującym "},{"type":"text","text":"tool_use_id","marks":[{"type":"code"}]},{"type":"text","text":". Błędy oznaczasz "},{"type":"text","text":"is_error: true","marks":[{"type":"code"}]},{"type":"text","text":" z czytelnym komunikatem."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Wysyłasz "},{"type":"text","text":"wszystkie","marks":[{"type":"bold"}]},{"type":"text","text":" wyniki w jednej wiadomości użytkownika i wracasz do kroku 2 – aż model odpowie tekstem ("},{"type":"text","text":"end_turn","marks":[{"type":"code"}]},{"type":"text","text":") albo skończy się limit rund."}]}]}]},{"type":"codeGroup","attrs":{"title":"Pętla tool use napisana ręcznie"},"content":[{"type":"codeBlock","attrs":{"language":"python","filename":"order_assistant.py"},"content":[{"type":"text","text":"import anthropic\n\nclient = anthropic.Anthropic()\n\n# Stand-ins for the real order service and menu database.\nORDERS = {\"1042\": {\"customer_id\": \"c-7\", \"status\": \"in_delivery\", \"eta_minutes\": 12}}\nALLERGENS = {\"spinach pierogi\": [\"gluten\", \"milk\", \"walnuts\"], \"ruskie pierogi\": [\"gluten\", \"milk\"]}\n\nTOOLS = [\n    {\n        \"name\": \"get_order_status\",\n        \"description\": \"Returns status and ETA of one of the signed-in customer's orders. \"\n        \"Use it whenever the customer asks where an order is or when it will arrive.\",\n        \"strict\": True,\n        \"input_schema\": {\n            \"type\": \"object\",\n            \"properties\": {\"order_id\": {\"type\": \"string\", \"description\": \"Order number without '#', e.g. 1042\"}},\n            \"required\": [\"order_id\"],\n            \"additionalProperties\": False,\n        },\n    },\n    {\n        \"name\": \"check_allergens\",\n        \"description\": \"Returns the allergens of a menu item. Use it for every question about \"\n        \"ingredients or allergies - menu recipes change, so never answer those from memory.\",\n        \"strict\": True,\n        \"input_schema\": {\n            \"type\": \"object\",\n            \"properties\": {\"dish\": {\"type\": \"string\", \"description\": \"Dish name as on the menu\"}},\n            \"required\": [\"dish\"],\n            \"additionalProperties\": False,\n        },\n    },\n]\n\n\ndef run_tool(name: str, args: dict, customer_id: str) -> str:\n    if name == \"get_order_status\":\n        order = ORDERS.get(args[\"order_id\"])\n        # Authorization lives in code: the model never decides whose data it may see.\n        if order is None or order[\"customer_id\"] != customer_id:\n            raise LookupError(f\"No order {args['order_id']} for this customer.\")\n        return f\"status={order['status']}, eta={order['eta_minutes']} min\"\n    if name == \"check_allergens\":\n        allergens = ALLERGENS.get(args[\"dish\"].lower())\n        if allergens is None:\n            raise LookupError(f\"Unknown dish '{args['dish']}'. Ask the customer to pick from the menu.\")\n        return \", \".join(allergens)\n    raise LookupError(f\"Unknown tool {name}\")\n\n\ndef answer(question: str, customer_id: str, max_rounds: int = 5) -> str:\n    messages = [{\"role\": \"user\", \"content\": question}]\n    for _ in range(max_rounds):\n        response = client.messages.create(\n            model=\"claude-opus-5-5\", max_tokens=4096, tools=TOOLS, messages=messages\n        )\n        if response.stop_reason != \"tool_use\":\n            if response.stop_reason in (\"max_tokens\", \"refusal\"):\n                raise RuntimeError(f\"Stopped early: {response.stop_reason}\")\n            return \"\".join(b.text for b in response.content if b.type == \"text\")\n\n        messages.append({\"role\": \"assistant\", \"content\": response.content})\n        results = []\n        for block in response.content:  # the model may request several tools at once\n            if block.type != \"tool_use\":\n                continue\n            try:\n                output = run_tool(block.name, block.input, customer_id)\n                results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id, \"content\": output})\n            except LookupError as err:\n                results.append({\"type\": \"tool_result\", \"tool_use_id\": block.id, \"content\": str(err), \"is_error\": True})\n        messages.append({\"role\": \"user\", \"content\": results})  # all results in ONE message\n    raise RuntimeError(\"Too many tool rounds\")\n\n\nprint(answer(\"Where is order #1042, and do the spinach pierogi contain nuts?\", customer_id=\"c-7\"))"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"order-assistant.ts"},"content":[{"type":"text","text":"import Anthropic from \"@anthropic-ai/sdk\";\n\nconst client = new Anthropic();\n\n// Stand-ins for the real order service and menu database.\nconst ORDERS: Record<string, { customerId: string; status: string; etaMinutes: number }> = {\n  \"1042\": { customerId: \"c-7\", status: \"in_delivery\", etaMinutes: 12 },\n};\nconst ALLERGENS: Record<string, string[]> = { \"spinach pierogi\": [\"gluten\", \"milk\", \"walnuts\"] };\n\nconst tools: Anthropic.Tool[] = [\n  {\n    name: \"get_order_status\",\n    description:\n      \"Returns status and ETA of one of the signed-in customer's orders. \" +\n      \"Use it whenever the customer asks where an order is or when it will arrive.\",\n    strict: true,\n    input_schema: {\n      type: \"object\",\n      properties: { order_id: { type: \"string\", description: \"Order number without '#', e.g. 1042\" } },\n      required: [\"order_id\"],\n      additionalProperties: false,\n    },\n  },\n  {\n    name: \"check_allergens\",\n    description:\n      \"Returns the allergens of a menu item. Use it for every question about ingredients \" +\n      \"or allergies - menu recipes change, so never answer those from memory.\",\n    strict: true,\n    input_schema: {\n      type: \"object\",\n      properties: { dish: { type: \"string\", description: \"Dish name as on the menu\" } },\n      required: [\"dish\"],\n      additionalProperties: false,\n    },\n  },\n];\n\nfunction runTool(name: string, input: Record<string, string>, customerId: string): string {\n  if (name === \"get_order_status\") {\n    const order = ORDERS[input.order_id];\n    // Authorization lives in code: the model never decides whose data it may see.\n    if (!order || order.customerId !== customerId) throw new Error(`No order ${input.order_id} for this customer.`);\n    return `status=${order.status}, eta=${order.etaMinutes} min`;\n  }\n  if (name === \"check_allergens\") {\n    const allergens = ALLERGENS[input.dish.toLowerCase()];\n    if (!allergens) throw new Error(`Unknown dish '${input.dish}'. Ask the customer to pick from the menu.`);\n    return allergens.join(\", \");\n  }\n  throw new Error(`Unknown tool ${name}`);\n}\n\nexport async function answer(question: string, customerId: string, maxRounds = 5): Promise<string> {\n  const messages: Anthropic.MessageParam[] = [{ role: \"user\", content: question }];\n  for (let round = 0; round < maxRounds; round++) {\n    const response = await client.messages.create({ model: \"claude-opus-5-5\", max_tokens: 4096, tools, messages });\n    if (response.stop_reason !== \"tool_use\") {\n      if (response.stop_reason === \"max_tokens\" || response.stop_reason === \"refusal\") {\n        throw new Error(`Stopped early: ${response.stop_reason}`);\n      }\n      return response.content.flatMap((b) => (b.type === \"text\" ? [b.text] : [])).join(\"\");\n    }\n\n    messages.push({ role: \"assistant\", content: response.content });\n    const results: Anthropic.ToolResultBlockParam[] = [];\n    for (const block of response.content) {\n      if (block.type !== \"tool_use\") continue; // the model may request several tools at once\n      try {\n        const output = runTool(block.name, block.input as Record<string, string>, customerId);\n        results.push({ type: \"tool_result\", tool_use_id: block.id, content: output });\n      } catch (err) {\n        results.push({ type: \"tool_result\", tool_use_id: block.id, content: String(err), is_error: true });\n      }\n    }\n    messages.push({ role: \"user\", content: results }); // all results in ONE message\n  }\n  throw new Error(\"Too many tool rounds\");\n}\n\nconsole.log(await answer(\"Where is order #1042, and do the spinach pierogi contain nuts?\", \"c-7\"));"}]},{"type":"codeBlock","attrs":{"language":"csharp","filename":"OrderAssistant.cs"},"content":[{"type":"text","text":"using System.Text.Json;\nusing Anthropic;\nusing Anthropic.Models.Messages;\n\nAnthropicClient client = new();\n\n// Raw JSON Schema; strict tools need additionalProperties: false.\nstatic InputSchema Schema(string json) =>\n    InputSchema.FromRawUnchecked(JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(json)!);\n\nList<ToolUnion> tools =\n[\n    new Tool\n    {\n        Name = \"get_order_status\",\n        Description = \"Returns status and ETA of one of the signed-in customer's orders. \" +\n                      \"Use it whenever the customer asks where an order is or when it will arrive.\",\n        Strict = true,\n        InputSchema = Schema(\"\"\"\n            {\"type\":\"object\",\"properties\":{\"order_id\":{\"type\":\"string\",\"description\":\"Order number without '#'\"}},\n             \"required\":[\"order_id\"],\"additionalProperties\":false}\n            \"\"\"),\n    },\n];\n\nstring RunTool(string name, IReadOnlyDictionary<string, JsonElement> input, string customerId)\n{\n    // Authorization lives in code: the model never decides whose data it may see.\n    var orderId = input[\"order_id\"].GetString();\n    if (name == \"get_order_status\" && orderId == \"1042\" && customerId == \"c-7\")\n        return \"status=in_delivery, eta=12 min\";\n    throw new InvalidOperationException($\"No order {orderId} for this customer.\");\n}\n\nList<MessageParam> messages = [new UserMessageParam { Content = \"Where is order #1042?\" }];\nfor (var round = 0; round < 5; round++)\n{\n    var response = await client.Messages.Create(new MessageCreateParams\n    {\n        Model = \"claude-opus-5-5\", MaxTokens = 4096, Tools = tools, Messages = messages,\n    });\n    if (response.StopReason != \"tool_use\")\n    {\n        foreach (var text in response.Content.Select(b => b.Value).OfType<TextBlock>())\n            Console.WriteLine(text.Text);\n        break;\n    }\n\n    // Echo the assistant turn (no ToParam helper in C#) and collect ALL tool results.\n    List<ContentBlockParam> assistant = [];\n    List<ContentBlockParam> results = [];\n    foreach (var block in response.Content)\n    {\n        if (block.TryPickText(out var text)) assistant.Add(new TextBlockParam { Text = text.Text });\n        else if (block.TryPickThinking(out var th))\n            assistant.Add(new ThinkingBlockParam { Thinking = th.Thinking, Signature = th.Signature });\n        else if (block.TryPickToolUse(out var call))\n        {\n            assistant.Add(new ToolUseBlockParam { ID = call.ID, Name = call.Name, Input = call.Input });\n            try\n            {\n                results.Add(new ToolResultBlockParam { ToolUseID = call.ID, Content = RunTool(call.Name, call.Input, \"c-7\") });\n            }\n            catch (Exception ex)\n            {\n                results.Add(new ToolResultBlockParam { ToolUseID = call.ID, Content = ex.Message, IsError = true });\n            }\n        }\n    }\n    messages.Add(new AssistantMessageParam { Content = assistant });\n    messages.Add(new UserMessageParam { Content = results }); // all results in ONE message\n}"}]}]}]},"toc":[{"id":"problem-asystent-ktory-zgaduje-status-zamowienia","text":"Problem: asystent, który zgaduje status zamówienia","level":2,"locked":false},{"id":"intuicja-model-jako-dyspozytor-aplikacja-jako-kuchnia","text":"Intuicja: model jako dyspozytor, aplikacja jako kuchnia","level":2,"locked":false},{"id":"anatomia-definicji-narzedzia","text":"Anatomia definicji narzędzia","level":2,"locked":false},{"id":"petla-tool-use-krok-po-kroku","text":"Pętla tool use krok po kroku","level":2,"locked":false},{"id":"tool-runner-petla-ktorej-nie-musisz-pisac","text":"Tool runner: pętla, której nie musisz pisać","level":2,"locked":true},{"id":"tool-choice-strict-i-rownolegle-wywolania","text":"tool_choice, strict i równoległe wywołania","level":2,"locked":true},{"id":"narzedzia-klienckie-i-serwerowe","text":"Narzędzia klienckie i serwerowe","level":2,"locked":true},{"id":"koszt-narzedzi-definicje-tez-sa-tokenami","text":"Koszt narzędzi: definicje też są tokenami","level":2,"locked":true},{"id":"kiedy-tool-use-a-kiedy-nie","text":"Kiedy tool use, a kiedy nie","level":2,"locked":true},{"id":"lista-kontrolna-przed-produkcja","text":"Lista kontrolna przed produkcją","level":2,"locked":true},{"id":"sprawdz-sie","text":"Sprawdź się","level":2,"locked":true},{"id":"co-dalej","text":"Co dalej","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":48,"visibleBlocks":16,"resources":[{"id":"6b0857b33c96f2d34d0b37f1","type":"article","provider":"web","url":"https://www.anthropic.com/engineering/advanced-tool-use","embedUrl":null,"title":"Claude Advanced Tool Use","description":"Claude can now discover, learn, and execute tools dynamically to enable agents that take action in the real world. Here’s how.","author":"@AnthropicAI","thumbnailUrl":"https://assets.claude.com/9a8905b9566374265c6b4c9fa4ac6320db8e31ca.jpg","durationSec":null,"lang":"en","topics":["tool-use"],"techs":["general"],"tags":["ai","hacker-news"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"hn","publishedAt":"2025-11-24T19:21:35.000Z","popularity":81,"verifiedAt":"2026-11-26T11:19:38.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:51.221Z","updatedAt":"2026-11-26T16:00:51.221Z"},{"id":"6b0857be3c96f2d34d0b420d","type":"article","provider":"web","url":"https://martinfowler.com/articles/function-call-LLM.html","embedUrl":null,"title":"Function calling using LLMs","description":"Allowing an LLM to formulate calls to external systems","author":"Martin Fowler","thumbnailUrl":"https://martinfowler.com/articles/function-call-LLM/card.png","durationSec":null,"lang":"en","topics":["tool-use"],"techs":["general"],"tags":["martin-fowler","llm","ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":75,"verifiedAt":"2026-11-26T11:07:20.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:59.965Z","updatedAt":"2026-11-26T16:00:59.965Z"},{"id":"6b0857b43c96f2d34d0b3855","type":"article","provider":"web","url":"https://sketch.dev/blog/agent-loop","embedUrl":null,"title":"The unreasonable effectiveness of an LLM agent loop with tool use","description":"How a simple loop enables powerful AI assistants","author":"Philip Zeyliger","thumbnailUrl":"https://blog.exe.dev/sketch/media/sketch.dev.png","durationSec":null,"lang":"en","topics":["ai-agents","tool-use"],"techs":["general"],"tags":["llm","ai","hacker-news"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"hn","publishedAt":"2025-05-15T19:33:44.000Z","popularity":76,"verifiedAt":"2026-11-26T11:18:43.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:51.221Z","updatedAt":"2026-11-26T16:00:51.221Z"},{"id":"6b0857c83c96f2d34d0b4a51","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=Mvcxa35_PMA","embedUrl":"https://www.youtube-nocookie.com/embed/Mvcxa35_PMA","title":"AI Agents In-Depth – Function Calling, MCP and Tool Use Under the Hood - Alan Smith - NDC AI 2026","description":"This talk was recorded at NDC AI in Oslo, Norway. #ndcai #ndcconferences #developer #softwaredeveloper Attend the next NDC conference near you: https://ndcconferences.com https://ndc-ai.com/ Subscribe to our YouTube channel and learn every day: / @NDC Follow our Social Media!…","author":"NDC Conferences","thumbnailUrl":"https://i.ytimg.com/vi/Mvcxa35_PMA/hqdefault.jpg","durationSec":null,"lang":"en","topics":["ai-agents","mcp","tool-use"],"techs":["general"],"tags":["llm","ai"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2026-07-01T14:29:34.000Z","popularity":56,"verifiedAt":"2026-11-26T11:13:01.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857a93c96f2d34d0b324b","type":"repo","provider":"github","url":"https://github.com/anthropics/claude-cookbooks","embedUrl":null,"title":"anthropics/claude-cookbooks","description":"A collection of notebooks/recipes showcasing some fun and effective ways of using Claude.","author":"anthropics","thumbnailUrl":"https://opengraph.githubassets.com/1/anthropics/claude-cookbooks","durationSec":null,"lang":"en","topics":["prompt-engineering","tool-use","rag"],"techs":["python"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"seed","publishedAt":null,"popularity":95,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:41.389Z","updatedAt":"2026-11-26T16:00:41.389Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[{"slug":"ai-path","title":"AI dla programisty","items":[{"slug":"llm-fundamentals","title":"Podstawy LLM: tokeny, okno kontekstu i przewidywanie następnego słowa","current":false},{"slug":"prompt-engineering","title":"Prompt engineering: jak pisać instrukcje, które model naprawdę wykona","current":false},{"slug":"embeddings-vector-db","title":"Embeddingi i bazy wektorowe: wyszukiwanie po znaczeniu","current":false},{"slug":"rag","title":"RAG: odpowiedzi na podstawie własnych dokumentów","current":false},{"slug":"tool-use","title":"Tool use: jak model językowy wywołuje funkcje Twojej aplikacji","current":true},{"slug":"ai-agents","title":"Agenci AI: model w pętli z narzędziami – i kiedy wystarczy zwykły workflow","current":false},{"slug":"mcp","title":"MCP (Model Context Protocol): jeden standard łączenia AI z narzędziami i danymi","current":false},{"slug":"evals","title":"Ewaluacja aplikacji LLM (evals): testy dla systemów, które nie są deterministyczne","current":false},{"slug":"llm-ops","title":"LLMOps: bramka do modeli, cache, limity, obserwowalność i koszty w produkcji","current":false},{"slug":"ai-guardrails","title":"Guardrails i bezpieczeństwo aplikacji LLM: prompt injection, wycieki danych i uprawnienia narzędzi","current":false},{"slug":"local-llms","title":"Lokalne modele językowe: Ollama, llama.cpp, vLLM, kwantyzacja i realne kompromisy","current":false},{"slug":"fine-tuning","title":"Fine-tuning modeli językowych: kiedy się opłaca, LoRA i QLoRA w praktyce","current":false},{"slug":"ai-coding-assistants","title":"Asystenci programowania AI: od podpowiedzi w edytorze do agenta, który otwiera pull requesty","current":false}]}],"prev":{"slug":"rag","title":"RAG: odpowiedzi na podstawie własnych dokumentów"},"next":{"slug":"ai-agents","title":"Agenci AI: model w pętli z narzędziami – i kiedy wystarczy zwykły workflow"},"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Autorytet","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":38}]}}