---
title: "What is tool use (function calling), and how does the loop work?"
description: "Tool use lets a model ask your code to run a function and read the result. Here is how to define a tool, run the loop and send errors back properly."
url: https://www.danny.engineering/answer/ai/what-is-tool-use-function-calling-and-how-does-the-loop-work
author: Danny
published: 2026-12-03T00:00:00.000Z
updated: 2026-12-03T15:35:00.000Z
tags: ["AI"]
---

# What is tool use (function calling), and how does the loop work?

## The short answer


Tool use, also called function calling, is a way to hand the model a list of functions it is allowed to ask for. The model never runs anything. It replies with a structured request such as "call `get_order` with `{ orderId: 'ORD-10422' }`", your code runs the function, you send the result back, and the model carries on with real data in front of it. The part you own is the loop around that exchange.


```typescript
const tools: Anthropic.Tool[] = [
  {
    name: 'get_order',
    description:
      'Look up one order by its ID. Returns status, items and the delivery date. Use this whenever the user asks about a specific order.',
    input_schema: {
      type: 'object',
      properties: {
        orderId: { type: 'string', description: 'The order ID, e.g. ORD-10422' },
      },
      required: ['orderId'],
      additionalProperties: false,
    },
    strict: true,
  },
];
```


## How it works


An LLM only produces text. What makes tool use work is an agreement about the shape of that text: the API renders your tool definitions into the prompt, and when the model decides a tool would help it emits a `tool_use` content block instead of prose. The API parses that block for you, so you get `block.name`, `block.input` (already a JSON object) and `block.id`, and the response arrives with `stop_reason === 'tool_use'`.


At that point the conversation is paused. The model has asked a question and is waiting for the answer. You run the function yourself, with your own credentials, in your own process, then append two messages to the history: the assistant's message exactly as it came back, and a user message containing one `tool_result` block per request, each tagged with the `tool_use_id` it answers. You call the API again with the longer history. The model reads the results and either asks for more tools or writes its final reply, which ends with `stop_reason === 'end_turn'`.


Two details matter. First, the model may ask for several tools in one response. Run them all, then return every result in a single user message; splitting them across messages confuses the model and discourages it from making parallel calls next time. Second, `strict: true` on the definition makes the API guarantee that `block.input` matches your schema exactly. It needs `additionalProperties: false` and a `required` list, and it removes a whole class of "the model sent a string where I wanted a number" bugs.


## How to do it


### Write the description like documentation


The description is the single most important part of a tool. The model picks tools and fills in arguments by reading it, so say what the tool does, what it returns, and when to use it (and when not to). A plain, specific description beats a clever schema every time. Keep the schema small, name parameters the way a human would, and put examples in the parameter descriptions.


### Run the loop


Here is a compact manual loop. It stops when the model stops asking for tools.


```typescript
const messages: Anthropic.MessageParam[] = [{ role: 'user', content: question }];

while (true) {
  const response = await client.messages.create({
    model: 'claude-sonnet-5-5',
    max_tokens: 4096,
    tools,
    messages,
  });
  messages.push({ role: 'assistant', content: response.content });

  if (response.stop_reason !== 'tool_use') break;

  const results: Anthropic.ToolResultBlockParam[] = [];
  for (const block of response.content) {
    if (block.type !== 'tool_use') continue;
    const value = await runTool(block.name, block.input);
    results.push({ type: 'tool_result', tool_use_id: block.id, content: JSON.stringify(value) });
  }
  messages.push({ role: 'user', content: results });
}
```


`runTool` is your own dispatcher: a `switch` on `block.name` that calls the real function. Add a cap on iterations in production so a confused model cannot loop forever.


### Send errors back as results


If a tool throws, do not throw out of the loop. Return a `tool_result` with `is_error: true` and a plain explanation. The model is good at recovering: it will retry with corrected arguments, try another tool, or tell the user what went wrong.


```typescript
async function safeRun(block: Anthropic.ToolUseBlock): Promise<Anthropic.ToolResultBlockParam> {
  try {
    const value = await runTool(block.name, block.input);
    return { type: 'tool_result', tool_use_id: block.id, content: JSON.stringify(value) };
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    return { type: 'tool_result', tool_use_id: block.id, content: `Error: ${message}`, is_error: true };
  }
}
```


### Or let the SDK run the loop


The Anthropic SDK ships a helper that owns the loop. You define each tool with a Zod schema and a `run` function, and `toolRunner` calls the API, runs your functions, feeds the results back and returns the final message. It is a beta helper, so the import paths live under `beta`.


```typescript
import { betaZodTool } from '@anthropic-ai/sdk/helpers/beta/zod';
import { z } from 'zod';

const getOrder = betaZodTool({
  name: 'get_order',
  description: 'Look up one order by its ID. Returns status, items and delivery date.',
  inputSchema: z.object({ orderId: z.string().describe('e.g. ORD-10422') }),
  run: async ({ orderId }) => JSON.stringify(await db.orders.find(orderId)),
});

const final = await client.beta.messages.toolRunner({
  model: 'claude-sonnet-5-5',
  max_tokens: 4096,
  tools: [getOrder],
  messages: [{ role: 'user', content: 'Where is order ORD-10422?' }],
});
```


Reach for the manual loop when you need control the helper does not give you, for example a custom approval step between calls or no dependency on a beta API.


## Common pitfalls

- **Splitting tool results across messages.** All results for one assistant turn go in one user message. Anything else is an error or, worse, a quiet drop in quality.
- **Treating tool input as trusted.** The arguments were written by the model, which was influenced by whatever the user typed. Validate them and apply your own authorisation checks before touching a database or an external API.
- **Only checking for** **`tool_use`** **and** **`end_turn`****.** A response can also stop with `max_tokens`. If that happens mid tool call, the input will be incomplete; raise `max_tokens` and retry rather than running a half-formed request.
- **Vague descriptions.** "Gets data" tells the model nothing. Say what data, from where, and when to call it. Most "the model picked the wrong tool" bugs are description bugs.
- **Forcing a tool with** **`tool_choice`****.** On current models `tool_choice: { type: 'any' }` and `{ type: 'tool' }` are rejected. Leave it on `auto` and ask for the tool in the prompt, or use structured outputs if you only wanted JSON back.
- **Returning huge results.** A 2 MB JSON dump costs input tokens on every later turn. Trim results to the fields the model needs before you send them back.

## Related reading

- [Tool use overview](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)
- [How to implement tool use](https://platform.claude.com/docs/en/agents-and-tools/tool-use/implement-tool-use)
- [Structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)
- [JSON Schema](https://json-schema.org/)
