Debian Codegraph @

src/anthropic/lib/tools/_tool_dispatch.py

raw
1 """Shared tool-dispatch helpers for the tool runners.
2
3 Both `client.beta.messages.tool_runner` (the Messages tool runner) and
4 `client.beta.sessions.events.tool_runner` (the sessions-side
5 `anthropic.lib.tools._beta_session_runner.SessionToolRunner`) do the
6 same three small things: index the supplied tools by name, run a runnable tool
7 over a JSON input, and turn an exception raised by a tool into tool-result
8 content. Those steps are factored out here so the two runners stay consistent
9 instead of each carrying its own copy. Consumed by the runner helpers only.
10 """
11
12 from __future__ import annotations
13
14 import inspect
15 from typing import Union, TypeVar, Iterable, Awaitable, cast
16 from typing_extensions import Protocol
17
18 from anyio.to_thread import run_sync
19
20 from ._beta_functions import ToolError, BetaFunctionTool, BetaBuiltinFunctionTool, BetaFunctionToolResultType
21 from ...types.beta.beta_message_param import BetaMessageParam
22 from ...types.beta.beta_compaction_block import BetaCompactionBlock
23 from ...types.beta.beta_content_block_param import BetaContentBlockParam
24 from ...types.beta.beta_request_tool_removal_block_param import BetaRequestToolRemovalBlockParam
25 from ...types.beta.beta_request_tool_addition_block_param import (
26 Tool as _ToolChangeTool,
27 BetaRequestToolAdditionBlockParam,
28 )
29
30 __all__ = ["tool_registry", "tool_error_content", "run_runnable_tool", "available_tool_names"]
31
32
33 class _NamedTool(Protocol):
34 """Anything with a `name` — the shape `tool_registry` indexes on."""
35
36 @property
37 def name(self) -> str: ...
38
39
40 class _CallableTool(Protocol):
41 """A runnable tool: `call` may be sync or async (it returns either the
42 result or an awaitable of it)."""
43
44 def call(self, input: object) -> Union[BetaFunctionToolResultType, Awaitable[BetaFunctionToolResultType]]: ...
45
46
47 NamedToolT = TypeVar("NamedToolT", bound=_NamedTool)
48
49
50 def tool_registry(tools: Iterable[NamedToolT]) -> dict[str, NamedToolT]:
51 """Index `tools` by their `name` for O(1) dispatch lookup.
52
53 On a duplicate name the later tool wins, matching a plain dict comprehension.
54 """
55 return {tool.name: tool for tool in tools}
56
57
58 def available_tool_names(messages: Iterable[BetaMessageParam], tool_names: Iterable[str]) -> set[str]:
59 """Fold mid-conversation `tool_removal` / `tool_addition` blocks over
60 the locally runnable `tool_names`.
61
62 These blocks arrive in `role: "system"` messages, and in the
63 `tool_changes` of a `compaction` block, which stands in for the system
64 messages of the turns it summarized. A `tool_reference` or a by-value
65 `tool_definition` can name a locally runnable tool; MCP references
66 execute server-side, so they (and any unknown block or tool type) are
67 ignored rather than raising.
68 """
69 available = set(tool_names)
70 for message in messages:
71 content = message["content"]
72 if isinstance(content, str):
73 continue
74 for block in content:
75 if message["role"] == "system":
76 _apply_tool_change(block, available)
77 elif message["role"] == "assistant":
78 for change in _compaction_tool_changes(block):
79 _apply_tool_change(change, available)
80 return available
81
82
83 def _compaction_tool_changes(block: BetaContentBlockParam) -> Iterable[BetaContentBlockParam]:
84 """The ``tool_changes`` of a ``compaction`` block, whichever shape it has in history.
85
86 A caller-written block is a dict; one the runner echoed from a response is
87 still the response model, with response-model entries.
88 """
89 if isinstance(block, BetaCompactionBlock):
90 return [cast(BetaContentBlockParam, change.to_dict()) for change in block.tool_changes or ()]
91 if isinstance(block, dict) and block["type"] == "compaction":
92 return block.get("tool_changes") or ()
93 return ()
94
95
96 def _apply_tool_change(block: BetaContentBlockParam, available: set[str]) -> None:
97 """Apply a single `tool_removal` / `tool_addition` block to `available`."""
98 if not isinstance(block, dict):
99 # `BetaContentBlockParam` also admits response-side content-block
100 # models; `tool_removal` / `tool_addition` are request-only
101 # TypedDicts, so a non-dict block is never one of them.
102 return
103 if block["type"] == "tool_removal" or block["type"] == "tool_addition":
104 _apply_tool_reference_change(block, available)
105
106
107 def _apply_tool_reference_change(
108 block: Union[BetaRequestToolRemovalBlockParam, BetaRequestToolAdditionBlockParam], available: set[str]
109 ) -> None:
110 """Fold one `tool_removal` / `tool_addition` block into `available`."""
111 name = _changed_tool_name(block["tool"])
112 if name is None:
113 return
114 if block["type"] == "tool_removal":
115 available.discard(name) # removing an absent name is a set no-op
116 else:
117 available.add(name) # add unconditionally: dispatch still requires a registry hit
118
119
120 def _changed_tool_name(tool: _ToolChangeTool) -> str | None:
121 """The locally runnable tool name a tool-change ``tool`` resolves to.
122
123 `tool_reference` names one directly and `tool_definition` carries one
124 by value; MCP references execute server-side, and unknown types are
125 ignored (forward compatibility), so those resolve to `None`.
126 """
127 if tool["type"] == "tool_reference":
128 return tool["name"]
129 if tool["type"] == "tool_definition":
130 # Not every `tools[]` entry has a `name` (e.g. `mcp_toolset`); those are never locally runnable.
131 name = cast("dict[str, object]", tool["definition"]).get("name")
132 return name if isinstance(name, str) else None
133 return None
134
135
136 def tool_error_content(exc: BaseException) -> BetaFunctionToolResultType:
137 """Render an exception raised by a tool as tool-result content.
138
139 A `ToolError` carries its own structured content; anything else is
140 rendered with `repr` (which, unlike `str`, keeps the exception type).
141 The caller owns the `is_error` flag and any logging.
142 """
143 if isinstance(exc, ToolError):
144 return exc.content
145 return repr(exc)
146
147
148 async def run_runnable_tool(tool: _CallableTool, input: dict[str, object]) -> BetaFunctionToolResultType:
149 """Call `tool` with `input`, awaiting the result if the tool is async.
150
151 Sync tools run on a worker thread. If the caller cancels (for example on a
152 timeout), the thread is left to finish on its own and its result is
153 dropped.
154 """
155 if isinstance(tool, (BetaFunctionTool, BetaBuiltinFunctionTool)):
156 return await run_sync(tool.call, input, abandon_on_cancel=True)
157 result = tool.call(input)
158 if inspect.isawaitable(result):
159 return await result
160 return result