| 1 |
# Tools helpers |
| 2 |
|
| 3 |
To define a tool, you can use the `@beta_tool` decorator on any python function like so: |
| 4 |
|
| 5 |
```python |
| 6 |
from anthropic import beta_tool |
| 7 |
|
| 8 |
@beta_tool |
| 9 |
def sum(left: int, right: int) -> str: |
| 10 |
"""Adds two integers together. |
| 11 |
Args: |
| 12 |
left (int): The first integer to add. |
| 13 |
right (int): The second integer to add. |
| 14 |
Returns: |
| 15 |
int: The sum of left and right integers. |
| 16 |
""" |
| 17 |
|
| 18 |
return str(left + right) |
| 19 |
``` |
| 20 |
|
| 21 |
> [!TIP] |
| 22 |
> If you're using the async client, replace `@beta_tool` with `@beta_async_tool` and define the function with `async def`. |
| 23 |
|
| 24 |
The `@beta_tool` decorator will inspect the function arguments and the docstring to extract a json schema representation of the given function, in this case it'll be turned into: |
| 25 |
|
| 26 |
```json |
| 27 |
{ |
| 28 |
"name": "sum", |
| 29 |
"description": "Adds two integers together.", |
| 30 |
"input_schema": { |
| 31 |
"additionalProperties": false, |
| 32 |
"properties": { |
| 33 |
"left": { |
| 34 |
"description": "The first integer to add.", |
| 35 |
"title": "Left", |
| 36 |
"type": "integer" |
| 37 |
}, |
| 38 |
"right": { |
| 39 |
"description": "The second integer to add.", |
| 40 |
"title": "Right", |
| 41 |
"type": "integer" |
| 42 |
} |
| 43 |
}, |
| 44 |
"required": ["left", "right"], |
| 45 |
"type": "object" |
| 46 |
} |
| 47 |
} |
| 48 |
``` |
| 49 |
|
| 50 |
If you want to implement calling the tool yourself, you can then pass the to the API like so: |
| 51 |
|
| 52 |
```python |
| 53 |
message = client.beta.messages.create( |
| 54 |
tools=[get_weather], |
| 55 |
# ... |
| 56 |
max_tokens=1024, |
| 57 |
model="claude-sonnet-4-5-20250929", |
| 58 |
messages=[{"role": "user", "content": "What is 2 + 2?"}], |
| 59 |
) |
| 60 |
``` |
| 61 |
|
| 62 |
or you can use our [tool runner](#tool-runner)! |
| 63 |
|
| 64 |
## Tool runner |
| 65 |
|
| 66 |
We provide a `client.beta.messages.tool_runner()` method that can automatically call tools defined with `@beta_tool()`. This method returns a `BetaToolRunner` class that is an iterator where each iteration yields a new `BetaMessage` instance from an API call. Iteration is driven by each message's `stop_reason`: on `tool_use` the runner executes the requested tools and sends the results back, on `pause_turn` or `compaction` it sends the turn back unchanged so the server can resume it, and on any other stop reason it stops after yielding that final message without running tools. |
| 67 |
|
| 68 |
```py |
| 69 |
runner = client.beta.messages.tool_runner( |
| 70 |
max_tokens=1024, |
| 71 |
model="claude-sonnet-4-5-20250929", |
| 72 |
tools=[sum], |
| 73 |
messages=[{"role": "user", "content": "What is 9 + 10?"}], |
| 74 |
) |
| 75 |
for message in runner: |
| 76 |
rich.print(message) |
| 77 |
``` |
| 78 |
|
| 79 |
### Compacting the conversation |
| 80 |
|
| 81 |
With the `compact-2026-09-04` beta you decide when a conversation is compacted: a request with the `compaction` param returns a single `compaction` block, which then replaces the messages it summarizes. In a tool runner, call `runner.compact_before_next_turn()` and the runner does this for you. |
| 82 |
|
| 83 |
```py |
| 84 |
runner = client.beta.messages.tool_runner( |
| 85 |
max_tokens=1024, |
| 86 |
model="claude-sonnet-4-5-20250929", |
| 87 |
betas=["compact-2026-09-04"], |
| 88 |
tools=[search_docs], |
| 89 |
messages=[{"role": "user", "content": "Find every page that mentions rate limits."}], |
| 90 |
) |
| 91 |
for message in runner: |
| 92 |
if message.usage.input_tokens > 100_000: |
| 93 |
runner.compact_before_next_turn() |
| 94 |
``` |
| 95 |
|
| 96 |
The call only schedules the compaction. Once the current turn has finished, including any tool calls, the runner requests a summary, replaces its message history with the compaction response the API returns, and carries on. A turn that was paused (`pause_turn`) is resumed and finished first. If the current turn is the last one, the runner compacts and then stops. If you call it before iterating, the compaction is the first request. |
| 97 |
|
| 98 |
The compaction response is yielded like any other message and doesn't count towards `max_iterations`. It has `stop_reason == "compaction"`, the summary is in `message.content[0].content`, and its top-level `usage.input_tokens` and `usage.output_tokens` are 0: what the compaction cost is in `usage.iterations`. Calling `compact_before_next_turn()` while handling that message does nothing, so a threshold like the one above doesn't compact twice. |
| 99 |
|
| 100 |
`compact_before_next_turn()` takes the same config as the `compaction` param of `messages.create()`, for example to give your own summarization instructions: |
| 101 |
|
| 102 |
```py |
| 103 |
runner.compact_before_next_turn({"type": "summarize", "instructions": "Keep the page URLs found so far."}) |
| 104 |
``` |
| 105 |
|
| 106 |
A few things to know: |
| 107 |
|
| 108 |
- Calling it again before the compaction runs replaces the pending one. |
| 109 |
- The runner doesn't add the beta for you, so pass `betas=["compact-2026-09-04"]`. |
| 110 |
- `context_management`, `stop_sequences`, a `tool_choice` that forces a tool (`any` or `tool`) and the output format (`output_format` or `output_config["format"]`, including the one in each of the `fallbacks`) are left out of the compaction request, because the API doesn't accept them together with `compaction`, and are sent again afterwards. `compact_before_next_turn()` raises if `context_management` has a `compact_*` edit. |
| 111 |
- While you're handling the compaction response, `append_messages()` and replacing `messages` with `set_messages_params()` raise, because the compaction response is about to replace the messages. Other params can still be changed. |
| 112 |
- If the API returns no summary, the runner logs a warning and keeps the history as it is. |
| 113 |
- If the run ends on a turn that was cut short with tool calls that never ran (`stop_reason == "max_tokens"`, for example), the pending compaction is skipped with a warning. It is also skipped if the run stops at `max_iterations` or you `break` out of the loop. |
| 114 |
- The `compaction` param itself can't be set on a tool runner, because every request in the loop would compact again. |
| 115 |
|
| 116 |
### Adding and removing tools during a run |
| 117 |
|
| 118 |
Changing the `tools` param in the middle of a conversation misses the prompt cache for everything sent so far. With the `inline-tools-2026-09-15` beta a tool change is sent as a message instead, and `runner.add_tools()` and `runner.remove_tools()` do that for you. `tools` is sent exactly as you first passed it on every request. |
| 119 |
|
| 120 |
```py |
| 121 |
runner = client.beta.messages.tool_runner( |
| 122 |
max_tokens=1024, |
| 123 |
model="claude-sonnet-4-5-20250929", |
| 124 |
betas=["inline-tools-2026-09-15"], |
| 125 |
tools=[get_time], |
| 126 |
messages=[{"role": "user", "content": "Find a slot for a 30 minute call with Sam next week."}], |
| 127 |
) |
| 128 |
for message in runner: |
| 129 |
if calendar.just_connected(): |
| 130 |
runner.add_tools(find_free_slots) |
| 131 |
if calendar.just_disconnected(): |
| 132 |
runner.remove_tools(find_free_slots) # or by name: "find_free_slots" |
| 133 |
``` |
| 134 |
|
| 135 |
`add_tools()` takes what `tool_runner(tools=...)` takes: function tools and raw tool definitions. The whole definition is sent to the model either way. |
| 136 |
|
| 137 |
- A function tool can be called from the request that carries its definition. If a tool of the same name is already there, the new function replaces it straight away: a call the model has already made in the message you're handling runs the new one. |
| 138 |
- Raw definitions are for server tools, such as `{"type": "web_search_20250305", "name": "web_search"}`, which the API runs. The tool runner never runs one: a call to it gets a "not found" error result and a warning, and it stops running a function tool of the same name straight away. |
| 139 |
- An `mcp_toolset` definition also needs its server in `mcp_servers`, which `add_tools()` doesn't change. |
| 140 |
|
| 141 |
`remove_tools()` takes the tools themselves or their names. |
| 142 |
|
| 143 |
- The tool stops being run straight away: a call the model already made in the message you're handling gets the same "not found" error result as a call to an unknown tool. To bring it back, pass it to `add_tools()` again. |
| 144 |
- Removing a server tool only tells the model. |
| 145 |
|
| 146 |
A few things to know: |
| 147 |
|
| 148 |
- Changes made while you're handling a message are sent together as one `role: "system"` message, in the order you made them, right after that turn's tool results. Changes made before iterating follow the initial messages. |
| 149 |
- After a paused turn (`pause_turn`) the turn is sent back as it came, and the changes go out with the request after that. |
| 150 |
- Changes still waiting when the run ends are never sent. |
| 151 |
- The runner doesn't add the beta for you, so pass `betas=["inline-tools-2026-09-15"]`. |
| 152 |
- Changing `tools` with `set_messages_params()` still works, but misses the prompt cache. |
| 153 |
- Use either these methods or `tool_addition` / `tool_removal` blocks you append yourself for a given tool, not both. |
| 154 |
- In the rare case where a compaction response comes back without `tool_changes` even though the messages it summarized added or removed tools, the model goes back to the tools in `tools`, and the tool runner doesn't detect it. Call `add_tools()` / `remove_tools()` again after that compaction if you need the change restored. |
| 155 |
|
| 156 |
## ToolError |
| 157 |
|
| 158 |
To report an error from a tool back to the model, raise a `ToolError`. Unlike a plain exception, `ToolError` accepts content blocks, allowing you to include images or other structured content in the error response: |
| 159 |
|
| 160 |
```py |
| 161 |
from anthropic import beta_tool |
| 162 |
from anthropic.lib.tools import ToolError |
| 163 |
|
| 164 |
@beta_tool |
| 165 |
def take_screenshot(url: str) -> str: |
| 166 |
"""Take a screenshot of a URL.""" |
| 167 |
if not is_valid_url(url): |
| 168 |
raise ToolError(f"Invalid URL: {url}") |
| 169 |
result = capture(url) |
| 170 |
if result.error: |
| 171 |
# Include the error screenshot so the model can see what went wrong |
| 172 |
raise ToolError([ |
| 173 |
{"type": "text", "text": f"Failed to load page: {result.error}"}, |
| 174 |
{"type": "image", "source": {"type": "base64", "data": result.screenshot, "media_type": "image/png"}}, |
| 175 |
]) |
| 176 |
return result.data |
| 177 |
``` |
| 178 |
|
| 179 |
If a plain exception is raised, its `repr()` will be sent to the model as a text error and logged. `ToolError` is not logged since it represents an intentional error response. |