> ## Documentation Index
> Fetch the complete documentation index at: https://docs.blobhub.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Tool Calling

> The model asks for tools; the flow runs them and posts their results.

A model does not run tools. It answers with **tool calls**, a name and arguments for each, and the flow runs them and
sends back what they returned. A [`genai.chat`](https://docs.blobhub.io/blob-types/workflow/workflows/component-genai-chat) component takes the
tools on its `tools` port, ends on a `tool_call` route when the model stops to call them, and runs again once the
results are in its history. Here the flow runs that loop with a `logic.code` component.

The [Service Desk Agent](https://blobhub.io/workflow-gallery/service-desk-agent) in the workflow gallery shows the loop
running.

## Declaring tools

| Port | Value | Default | Meaning |
| :- | :- | :- | :- |
| `tools` | a list of `{name, description, parameters, strict?}` | empty | The tools the model may call. `parameters` is a JSON schema. |
| `tool_choice` | `auto`, `none` or `required` | `auto` | Whether the model may call a tool, must not, or must. |

Each tool needs a `name` and a `parameters` object; the definition check names the index of one that lacks either.

Two checks hold a flow to the model:

* **The capability.** `tools` is a capability of the
  [catalog](https://docs.blobhub.io/blob-types/workflow/workflows/component-genai-model-language.md#the-catalog). A `genai.chat` that holds
  `tools` needs a model that does it: `model: <id> does not do tools, which its consumers need`. A model the catalog
  does not know passes, and the vendor decides.
* **A forced choice.** Four catalog models refuse `required`. Chat sends them `auto` instead and warns:
  `tool_choice "required" is not supported by <id>: sent "auto"`. The list is on the
  [language model page](https://docs.blobhub.io/blob-types/workflow/workflows/component-genai-model-language.md#the-catalog).

## The `tool_call` route

When the answer ends with `finish` `tool_call`, chat writes its output and ends on `tool_call` instead of `success`. It
applies neither `output_role` nor the `role` of `output_metadata` to that answer
([A tool loop keeps its roles](https://docs.blobhub.io/blob-types/workflow/workflows/component-genai-chat.md#a-tool-loop-keeps-its-roles)).

* Parallel calls are several `tool_call` blocks of one message, each with its own `id`.
* A flow without tools never takes the route.
* A flow that holds `tools` must wire `tool_call`. The definition check refuses it otherwise:
  `tool_call: the flow holds tools, so the tool_call route must be connected`. A route left unwired would fail the run
  at the first call.

## Results

The results go back as one `user` message of `tool_result` blocks, one per call, in order. Each block names the `id` of
the call it answers, and its `content` is blocks: text, `json` or a `file`. Anthropic is sent every result of a turn in
one `user` turn. On Gemini a result that answers no call in the history fails the call:
`tool_result <id> answers no call in the history`.

A message made only of `tool_result` blocks is stored on a thread as a `reply`, the role of the answer it answers,
unless the component that posts it gives it a role, and reads back as a `user` message.

## The `logic.code` helpers

Both are bound in the code Sandbox. See [Code Component](https://docs.blobhub.io/blob-types/workflow/workflows/component-code.md#tools).

```python theme={null}
def tool_calls(message) -> list
    # message: a value envelope ({"type": "message", "message": {...}}) or message data
    # returns [{"id", "name", "arguments"}] in block order; [] for a message with none

def tool_result_message(results) -> dict
    # results: [{"id", "content", "is_error"?}]; content a str (one text block), a list of blocks (as given),
    # or anything else JSON (one json block)
    # returns a message value: role "user", one tool_result block per result, in order
```

A result without an `id` raises `ValueError("tool result <n> has no id")`.

## The loop

```mermaid theme={null}
flowchart LR
  chat["genai.chat<br/>tools, tool_choice"]
  code["logic.code<br/>tool_calls, run each,<br/>tool_result_message"]
  history[("history<br/>a thread, when it is one")]
  done(["success"])

  chat -->|tool_call| code
  code -->|results joined| history
  history -->|read again| chat
  chat -->|success| done
```

1. Chat reads its history and calls the model. The answer holds calls and ends with `finish` `tool_call`.
2. Chat writes the answer to its output and ends on `tool_call`. When its output is wired to a `data.thread`, the answer
   is posted there as an item.
3. A `logic.code` component reads the answer, runs each call and builds the results message. Wired to the same
   `data.thread`, its output is posted as one item, whose parent is the answer's item.
4. Chat runs again and reads the call and its results with the rest of the history. A call's results count right
   after it, ahead of anything posted to the thread while the call ran, so the model reads the call, its results, then
   the rest ([Selecting a History](https://docs.blobhub.io/blob-types/workflow/workflows/selecting-a-history.md)).

Chat ends on `success` once an answer ends with any other `finish`.

### What the loop keeps steady

* **The start is fixed for the run.** A chat's first call in an execution fixes where its history starts. Its later
  calls start in the same place, so a post or a newer anchor that arrives in between does not move the history under
  the loop. See [Selecting a History](https://docs.blobhub.io/blob-types/workflow/workflows/selecting-a-history.md).
* **Reasoning travels with the answer.** A model's reasoning blocks keep the vendor's own record in `vendor_data`. A
  call to the same vendor sends it back unchanged, in order and verbatim, so the vendor can continue its reasoning
  across the calls of the loop; a call to another vendor leaves a `reasoning` block out. See [Data
  Types](https://docs.blobhub.io/blob-types/workflow/workflows/data-types.md). A model on the `gemini` vendor that continues another
  vendor's loop is sent a placeholder thought signature on the first call of each step of the current turn that has none
  ([Reasoning](https://docs.blobhub.io/blob-types/workflow/workflows/component-genai-chat.md#reasoning)).
* **The roles stay `reply`.** Whatever role the chat outputs, the loop's calls are `reply` items, and so are its
  results unless the component running the tools gives them a role. When the chat's role is not `reply`, a listener on
  it hears only the final answer ([A tool loop keeps its
  roles](https://docs.blobhub.io/blob-types/workflow/workflows/component-genai-chat.md#a-tool-loop-keeps-its-roles)).

## Example: a service desk lookup

A `genai.chat` for the Ostrava Pumps service desk holds one tool, `lookup_pump`, and its `tool_call` route goes to this
`logic.code`. The lookup table stands in for an internal system.

```json theme={null}
{
  "name": "lookup_pump",
  "description": "Returns the service status of an Ostrava Pumps unit by serial number.",
  "parameters": {
    "type": "object",
    "properties": {"serial": {"type": "string"}},
    "required": ["serial"]
  }
}
```

```python theme={null}
answer = get_data_input("answer")

SERVICE_RECORDS = {
    "OP-4417": {"model": "OP-300 booster", "status": "in service", "next_service": "2026-12-04"},
    "OP-5120": {"model": "OP-500 high-lift", "status": "awaiting parts", "next_service": None},
}

results = []
for call in tool_calls(answer):
    if call["name"] == "lookup_pump":
        record = SERVICE_RECORDS.get(call["arguments"].get("serial"))
        if record is None:
            results.append({"id": call["id"], "content": "No pump with that serial number.", "is_error": True})
        else:
            results.append({"id": call["id"], "content": record})
    else:
        results.append({"id": call["id"], "content": "Unknown tool: " + call["name"], "is_error": True})

set_data_output("results", tool_result_message(results))
set_result("success")
```

A record is a `dict`, so it becomes one `json` block of the result; the text of an error becomes one `text` block. When
the model asks for two serial numbers at once, `tool_calls` returns two entries and `tool_result_message` returns one
message with two `tool_result` blocks, in the order of the calls.

The `results` output is wired to the same `data.thread` as the chat's output, so each round of the loop is on the thread
for the conversation widget to show.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.