Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 21, 04:45 UTC
| 1 | import typing as t |
| 2 | |
| 3 | from anthropic.types.beta.beta_tool_use_block import BetaToolUseBlock |
| 4 | from anthropic.types.cache_control_ephemeral_param import CacheControlEphemeralParam |
| 5 | from anthropic.types.message import Message as ToolsBetaMessage |
| 6 | from anthropic.types.tool_param import ToolParam |
| 7 | from anthropic.types.tool_use_block import ToolUseBlock |
| 8 | |
| 9 | from composio.core.provider import NonAgenticProvider, ToolCallSession |
| 10 | from composio.types import Modifiers, Tool, ToolExecutionResponse |
| 11 | from composio.utils.shared import ( |
| 12 | ToolSchemaAliases, |
| 13 | alias_tool_input_schema, |
| 14 | normalize_tool_arguments, |
| 15 | ) |
| 16 | |
| 17 | |
| 18 | class AnthropicToolExecutionResponse(ToolExecutionResponse): |
| 19 | """Execution dictionary correlated with the originating Anthropic tool use. |
| 20 | |
| 21 | Not a ``tool_result`` block. Use ``tool_use_id`` for the block's ID, |
| 22 | ``json.dumps(result)`` for its content, and ``not result["successful"]`` |
| 23 | for ``is_error``. Session execution also retains ``result_type``, |
| 24 | ``log_id``, and any returned ``instant_charge``. |
| 25 | """ |
| 26 | |
| 27 | tool_use_id: str |
| 28 | |
| 29 | |
| 30 | class AnthropicProvider( |
| 31 | NonAgenticProvider[ToolParam, list[ToolParam]], |
| 32 | name="anthropic", |
| 33 | ): |
| 34 | """ |
| 35 | Composio toolset for Anthropic Claude platform. |
| 36 | """ |
| 37 | |
| 38 | def __init__(self, cache_tools: bool = False, **kwargs: t.Any) -> None: |
| 39 | """ |
| 40 | :param cache_tools: Attach Anthropic's ephemeral cache_control to the |
| 41 | tool definitions so Claude can reuse the cached tool schemas |
| 42 | across requests. Anthropic allows at most 4 cache_control |
| 43 | breakpoints per request, shared across the system prompt, tools, |
| 44 | and messages, and a breakpoint caches everything up to and |
| 45 | including it — so :meth:`wrap_tools` places a single breakpoint |
| 46 | on the last tool, covering the whole tool list with one |
| 47 | breakpoint. Mirrors the TypeScript |
| 48 | ``AnthropicProvider({ cacheTools: true })`` option. Defaults to |
| 49 | ``False``. |
| 50 | """ |
| 51 | super().__init__(**kwargs) |
| 52 | self.cache_tools = cache_tools |
| 53 | self._aliases: dict[str, ToolSchemaAliases] = {} |
| 54 | |
| 55 | def wrap_tool(self, tool: Tool) -> ToolParam: |
| 56 | """ |
| 57 | Wrap a single tool. |
| 58 | |
| 59 | With ``cache_tools`` enabled the returned tool carries its own |
| 60 | ``cache_control`` breakpoint. If you build a tool list yourself from |
| 61 | several calls, keep the number of breakpoints within Anthropic's |
| 62 | limit, or use :meth:`wrap_tools`, which marks only the last tool. |
| 63 | """ |
| 64 | aliases = alias_tool_input_schema(tool.input_parameters or {}) |
| 65 | self._aliases[tool.slug] = aliases |
| 66 | wrapped = ToolParam( |
| 67 | input_schema=aliases.schema, |
| 68 | name=tool.slug, |
| 69 | description=tool.description, |
| 70 | ) |
| 71 | if self.cache_tools: |
| 72 | wrapped["cache_control"] = CacheControlEphemeralParam(type="ephemeral") |
| 73 | return wrapped |
| 74 | |
| 75 | def wrap_tools(self, tools: t.Sequence[Tool]) -> list[ToolParam]: |
| 76 | """ |
| 77 | Wrap a list of tools. |
| 78 | |
| 79 | With ``cache_tools`` enabled only the last tool in the list carries a |
| 80 | ``cache_control`` breakpoint. The limit of 4 applies to the whole |
| 81 | request, not to one call, so if you concatenate the lists from several |
| 82 | calls, each list's last tool keeps its breakpoint. |
| 83 | """ |
| 84 | wrapped = [self.wrap_tool(tool) for tool in tools] |
| 85 | # A cache_control breakpoint caches every block up to and including |
| 86 | # it, so one breakpoint on the last tool covers the entire tool list. |
| 87 | # Anthropic caps breakpoints at 4 per request (shared with the system |
| 88 | # prompt and messages); a breakpoint on every tool would exceed that |
| 89 | # limit as soon as a caller passes 5+ tools. |
| 90 | if self.cache_tools: |
| 91 | for tool_param in wrapped[:-1]: |
| 92 | tool_param.pop("cache_control", None) |
| 93 | return wrapped |
| 94 | |
| 95 | @t.overload |
| 96 | def execute_tool_call( |
| 97 | self, |
| 98 | user_id: str, |
| 99 | tool_call: ToolUseBlock, |
| 100 | modifiers: t.Optional[Modifiers] = None, |
| 101 | ) -> AnthropicToolExecutionResponse: ... |
| 102 | |
| 103 | @t.overload |
| 104 | def execute_tool_call( |
| 105 | self, |
| 106 | *, |
| 107 | session: ToolCallSession, |
| 108 | tool_call: ToolUseBlock, |
| 109 | ) -> AnthropicToolExecutionResponse: ... |
| 110 | |
| 111 | def execute_tool_call( |
| 112 | self, |
| 113 | user_id: t.Optional[str] = None, |
| 114 | tool_call: t.Optional[ToolUseBlock] = None, |
| 115 | modifiers: t.Optional[Modifiers] = None, |
| 116 | *, |
| 117 | session: t.Optional[ToolCallSession] = None, |
| 118 | ) -> AnthropicToolExecutionResponse: |
| 119 | """ |
| 120 | Execute one tool use and retain its ID with the execution result. |
| 121 | |
| 122 | :param user_id: User ID for direct tool execution. |
| 123 | :param session: Tool Router session that produced session tools. |
| 124 | :param tool_call: Tool call metadata. |
| 125 | :param modifiers: Modifiers to use for executing function calls. |
| 126 | :return: A dictionary with ``tool_use_id``, ``data``, ``error``, and |
| 127 | ``successful``. Session calls also retain ``result_type``, |
| 128 | ``log_id``, and any returned ``instant_charge``. Check |
| 129 | ``successful`` explicitly, even if ``error`` is empty. |
| 130 | Transport/auth/input exceptions propagate, rather than becoming |
| 131 | returned tool failures. |
| 132 | """ |
| 133 | if tool_call is None: |
| 134 | raise TypeError("tool_call is required") |
| 135 | target = self.resolve_tool_call_execution_target( |
| 136 | user_id=user_id, session=session |
| 137 | ) |
| 138 | |
| 139 | # Models occasionally emit tool input as a JSON string rather than a dict (issue #2406). |
| 140 | arguments = normalize_tool_arguments(tool_call.input) |
| 141 | aliases = self._aliases.get(tool_call.name) |
| 142 | if aliases is not None: |
| 143 | arguments = aliases.restore_arguments(arguments) |
| 144 | result = self.execute_tool_for_target( |
| 145 | target=target, |
| 146 | slug=tool_call.name, |
| 147 | arguments=arguments, |
| 148 | modifiers=modifiers, |
| 149 | ) |
| 150 | return {**result, "tool_use_id": tool_call.id} |
| 151 | |
| 152 | @t.overload |
| 153 | def handle_tool_calls( |
| 154 | self, |
| 155 | user_id: str, |
| 156 | response: t.Union[dict, ToolsBetaMessage], |
| 157 | modifiers: t.Optional[Modifiers] = None, |
| 158 | ) -> t.List[AnthropicToolExecutionResponse]: ... |
| 159 | |
| 160 | @t.overload |
| 161 | def handle_tool_calls( |
| 162 | self, |
| 163 | *, |
| 164 | session: ToolCallSession, |
| 165 | response: t.Union[dict, ToolsBetaMessage], |
| 166 | ) -> t.List[AnthropicToolExecutionResponse]: ... |
| 167 | |
| 168 | def handle_tool_calls( |
| 169 | self, |
| 170 | user_id: t.Optional[str] = None, |
| 171 | response: t.Optional[t.Union[dict, ToolsBetaMessage]] = None, |
| 172 | modifiers: t.Optional[Modifiers] = None, |
| 173 | *, |
| 174 | session: t.Optional[ToolCallSession] = None, |
| 175 | ) -> t.List[AnthropicToolExecutionResponse]: |
| 176 | """ |
| 177 | Handle tool calls from Anthropic Claude chat completion object. |
| 178 | |
| 179 | :param response: Message returned by ``anthropic.Anthropic.messages.create``. |
| 180 | :param user_id: User ID for direct tool execution. |
| 181 | :param session: Tool Router session that produced session tools. |
| 182 | :param modifiers: Modifiers to use for executing function calls. |
| 183 | :return: Execution dictionaries in tool-use order, each retaining the |
| 184 | matching ``tool_use_id``. These are not Anthropic content blocks. |
| 185 | Build each block with ``type="tool_result"``, the result's |
| 186 | ``tool_use_id``, ``content=json.dumps(result)``, and |
| 187 | ``is_error=not result["successful"]``. Unlike the TypeScript |
| 188 | helper, this method does not return ready-to-append messages. |
| 189 | Exceptions stop the batch; earlier calls may already have run. |
| 190 | """ |
| 191 | if response is None: |
| 192 | raise TypeError("response is required") |
| 193 | self.resolve_tool_call_execution_target(user_id=user_id, session=session) |
| 194 | if session is not None and modifiers is not None: |
| 195 | raise ValueError( |
| 196 | "Direct execution modifiers cannot be used with a Tool Router session" |
| 197 | ) |
| 198 | if isinstance(response, dict): |
| 199 | response = ToolsBetaMessage(**response) |
| 200 | |
| 201 | outputs: t.List[AnthropicToolExecutionResponse] = [] |
| 202 | for content in response.content: |
| 203 | if isinstance(content, (ToolUseBlock, BetaToolUseBlock)): |
| 204 | result = ( |
| 205 | self.execute_tool_call( |
| 206 | session=session, |
| 207 | tool_call=content, |
| 208 | ) |
| 209 | if session is not None |
| 210 | else self.execute_tool_call( |
| 211 | user_id=t.cast(str, user_id), |
| 212 | tool_call=content, |
| 213 | modifiers=modifiers, |
| 214 | ) |
| 215 | ) |
| 216 | outputs.append(result) |
| 217 | return outputs |