Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
md 99 lines 5.29 KB
Rendered Raw
1 # composio-anthropic
2
3 Adapts Composio tools to the Claude Messages API tool format and executes the tool calls Claude returns.
4
5 ## Installation
6
7 ```bash
8 pip install composio composio-anthropic anthropic
9 ```
10
11 Set `COMPOSIO_API_KEY` (create one at https://dashboard.composio.dev/settings) and `ANTHROPIC_API_KEY` in your environment.
12
13 ## Quickstart
14
15 `AnthropicProvider` is non-agentic: Claude returns `tool_use` blocks, `handle_tool_calls` executes them, and you send the results back as `tool_result` blocks.
16
17 ```python
18 import json
19 import anthropic
20 from composio import Composio
21 from composio_anthropic import AnthropicProvider
22
23 composio = Composio(provider=AnthropicProvider())
24 client = anthropic.Anthropic()
25
26 # Create a session for your user
27 session = composio.create(user_id="user_123")
28 tools = session.tools()
29
30 messages = [
31 {"role": "user", "content": "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'"}
32 ]
33
34 response = client.messages.create(
35 model="claude-opus-5-5",
36 max_tokens=4096,
37 tools=tools,
38 messages=messages,
39 )
40
41 # Agentic loop: keep executing tool calls until the model responds with text
42 while response.stop_reason == "tool_use":
43 # Results retain each tool_use ID; Python still needs explicit content blocks.
44 results = composio.provider.handle_tool_calls(session=session, response=response)
45 messages.append({"role": "assistant", "content": response.content})
46 messages.append({
47 "role": "user",
48 "content": [
49 {
50 "type": "tool_result",
51 "tool_use_id": result["tool_use_id"],
52 "content": json.dumps(result),
53 "is_error": not result["successful"],
54 }
55 for result in results
56 ]
57 })
58 response = client.messages.create(
59 model="claude-opus-5-5",
60 max_tokens=4096,
61 tools=tools,
62 messages=messages,
63 )
64
65 # Print final response
66 for block in response.content:
67 if block.type == "text":
68 print(block.text)
69 ```
70
71 `handle_tool_calls` extracts every `tool_use` block, executes the matching Composio tools through the supplied session, and returns execution dictionaries in tool-use order. Pass `user_id` instead for tools fetched with `tools.get()`. Claude occasionally emits tool input as a JSON string instead of an object; the provider normalizes this before execution.
72
73 ## Execution contracts
74
75 `execute_tool_call(session=session, tool_call=block)` returns one `AnthropicToolExecutionResponse`; `handle_tool_calls(session=session, response=response)` returns a list. Import both the provider and the response type from `composio_anthropic`.
76
77 Each result contains `tool_use_id`, `data`, `error`, and `successful`. Session-backed results also retain `result_type`, `log_id`, and `instant_charge` when returned. Check `result["successful"]` explicitly. A failed execution can have an empty or `None` error, and a log ID is only for correlation.
78
79 These are Python dictionaries, **not** Anthropic `tool_result` blocks. Serialize with `json.dumps(result)`, pair each block with `result["tool_use_id"]`, and set `is_error` from `not result["successful"]`, as above. Existing code that pairs the ordered results with the original `tool_use` blocks still works. TypeScript's `handleToolCalls` instead returns ready-to-append messages; don't use that contract in Python.
80
81 On older provider releases without `tool_use_id`, keep pairing the ordered results with the original `tool_use` blocks, as in the web guide. The correlation field is additive; the helper still returns execution dictionaries rather than native messages.
82
83 | Entry point | Arguments | Result and outcome check |
84 | --- | --- | --- |
85 | Python `session.execute` | `tool_slug=...`, `arguments={...}` | Pydantic model; `result.result_type == "completed"`. Use `model_dump(mode="json")` or `model_dump_json()` for serialization. No model call ID. |
86 | Python `composio.tools.execute` | `slug=...`, `arguments={...}`, `user_id=...` | `ToolExecutionResponse` dictionary; `result["successful"]`. |
87 | Python `after_execute` modifier | `(tool, toolkit, response)` | Receives and returns a `ToolExecutionResponse` dictionary; check `response["successful"]`, not an attribute. |
88 | Python Anthropic helpers | `session=...` **or** `user_id=...`; `tool_call=...` or `response=...` | Correlated execution dictionaries; `result["successful"]`. |
89
90 Session adapters derive `successful` from `result_type == "completed"`; `"failed"` and `"blocked"` are not successful. `session.execute` itself doesn't run `session.tools(modifiers=...)` callbacks. Direct-execution modifiers can't be passed alongside a session to a provider helper.
91
92 Transport, authentication, and input errors can raise instead of returning a tool result. Handle credential/connection recovery separately from an ordinary returned failure. If a batch raises, earlier calls may already have executed. Don't replay the batch blindly. The execution status, an empty error, or a log ID alone doesn't establish a provider-side side effect; inspect the tool-specific `data`. Retry and idempotency policy stays in your application.
93
94 Building on the Claude Agent SDK instead of the Messages API? Use [`composio-claude-agent-sdk`](../claude_agent_sdk).
95
96 ## Links
97
98 - Anthropic provider docs: https://docs.composio.dev/docs/providers/anthropic
99 - Composio docs: https://docs.composio.dev