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 22, 02:00 UTC
refactor(python): merge examples into one file, fix mypy shadowing
- Remove custom_tools_v2.py, keep single custom_tools_agent_test.py - Add override examples (slug, name, description) with inline comments - Add toolkit tool with overridden name - Fix mypy: rename entry -> local_entry to avoid shadowing CustomToolsMapEntry from earlier loop Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Dhawal Upadhyay committed
Mar 23, 2026 at 17:55 UTC
d1abe5df5641bf4e3faaddc51b085eeda0d97910
3 files changed
+75
-159
python/composio/core/models/tool_router_session.py
+4
-4
@@ -305,7 +305,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
305
# Build local result entries matching backend format
306
local_entries = []
307
for idx, result in local_results:
308
- entry: t.Dict[str, t.Any] = {
308
+ local_entry: t.Dict[str, t.Any] = {
309
"response": {
310
"successful": result["successful"],
311
"data": result["data"],
@@ -313,9 +313,9 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
313
"tool_slug": parsed[idx]["tool_slug"],
314
}
315
if result.get("error"):
316
- entry["response"]["error"] = result["error"]
317
- entry["error"] = result["error"]
318
- local_entries.append(entry)
316
+ local_entry["response"]["error"] = result["error"]
317
+ local_entry["error"] = result["error"]
318
+ local_entries.append(local_entry)
319
320
# Merge: remotes first, locals appended (matches TS behavior —
321
# remote results may be stored in workbench with index references)
python/examples/custom_tools_agent_test.py
+71
-52
@@ -1,7 +1,9 @@
1
"""
2
-Custom Tools Agent Test — decorator API with OpenAI Agents SDK.
2
+Custom Tools — local tools + proxy execute with OpenAI Agents SDK.
3
4
-Tests all custom tool patterns end-to-end through a real LLM agent loop.
4
+Shows how to create custom tools that run in-process alongside
5
+remote Composio tools. Includes all three patterns: standalone,
6
+extension (Gmail proxy), and custom toolkit.
7
8
Usage:
9
COMPOSIO_API_KEY=... OPENAI_API_KEY=... python examples/custom_tools_agent_test.py
@@ -21,7 +23,7 @@ from composio_openai_agents import OpenAIAgentsProvider
23
composio = Composio(provider=OpenAIAgentsProvider())
24
25
24
-# ── 1. Standalone tool ──────────────────────────────────────────
26
+# ── 1. Standalone tool — slug/name/description inferred from function ──
27
28
29
class UserLookupInput(BaseModel):
@@ -43,7 +45,40 @@ def get_user(input: UserLookupInput, ctx):
45
return user
46
47
46
-# ── 2. Extension tool (Gmail proxy) ─────────────────────────────
48
+# slug = GET_USER (from function name)
49
+# name = Get User (humanized)
50
+# description = "Look up an internal user by ID..." (from docstring)
51
+
52
+
53
+# ── 2. Standalone tool with overrides ──────────────────────────────────
54
+
55
+
56
+class GreetInput(BaseModel):
57
+ name: str = Field(description="Name to greet")
58
+ style: str = Field(default="friendly", description="Greeting style")
59
+
60
+
61
+@composio.experimental.tool(
62
+ slug="GREET_V2",
63
+ name="Greeting Generator",
64
+ description="Generate a personalized greeting message in different styles.",
65
+)
66
+def greet(input: GreetInput, ctx):
67
+ """This docstring is ignored because description= is set above."""
68
+ greetings = {
69
+ "friendly": f"Hey {input.name}! Great to see you!",
70
+ "formal": f"Dear {input.name}, I hope this message finds you well.",
71
+ "casual": f"Yo {input.name}, what's up?",
72
+ }
73
+ return {"message": greetings.get(input.style, f"Hello {input.name}!")}
74
+
75
+
76
+# slug = GREET_V2 (overridden, not GREET)
77
+# name = Greeting Generator (overridden, not Greet)
78
+# description = "Generate a personalized..." (overridden, not docstring)
79
+
80
+
81
+# ── 3. Extension tool — inherits Gmail auth via ctx.proxy_execute() ────
82
83
84
class DraftInput(BaseModel):
@@ -72,12 +107,7 @@ def create_draft(input: DraftInput, ctx):
107
return {"draft_id": data["id"], "to": input.to, "subject": input.subject}
108
109
75
-# ── 3. Custom toolkit ───────────────────────────────────────────
76
-
77
-
78
-class SetRoleInput(BaseModel):
79
- user_id: str = Field(description="User ID")
80
- role: str = Field(description="New role (admin, developer, viewer)")
110
+# ── 4. Custom toolkit — groups related tools under one namespace ───────
111
112
113
role_manager = composio.experimental.Toolkit(
@@ -87,13 +117,24 @@ role_manager = composio.experimental.Toolkit(
117
)
118
119
120
+class SetRoleInput(BaseModel):
121
+ user_id: str = Field(description="User ID")
122
+ role: str = Field(description="New role (admin, developer, viewer)")
123
+
124
+
125
@role_manager.tool()
126
def set_role(input: SetRoleInput, ctx):
127
"""Set a user's role. Returns confirmation."""
128
return {"user_id": input.user_id, "role": input.role, "updated": True}
129
130
96
-# ── Agent test runner ───────────────────────────────────────────
131
+@role_manager.tool(name="List All Roles")
132
+def list_roles(input: UserLookupInput, ctx):
133
+ """List available roles for a user."""
134
+ return {"roles": ["admin", "developer", "viewer"], "current": "admin"}
135
+
136
+
137
+# ── Agent ──────────────────────────────────────────────────────────────
138
139
140
async def run_test(prompt, test_name):
@@ -106,7 +147,7 @@ async def run_test(prompt, test_name):
147
toolkits=["gmail", "weathermap"],
148
manage_connections=True,
149
experimental={
109
- "custom_tools": [get_user, create_draft],
150
+ "custom_tools": [get_user, greet, create_draft],
151
"custom_toolkits": [role_manager],
152
},
153
)
@@ -133,48 +174,26 @@ async def run_test(prompt, test_name):
174
175
176
async def main():
136
- results = []
137
- results.append(
138
- ("Standalone (GET_USER)", await run_test("Look up user-2", "Standalone"))
139
- )
140
- results.append(
141
- (
142
- "Toolkit (SET_ROLE)",
143
- await run_test("Set user-1 role to developer", "Toolkit"),
144
- )
145
- )
146
- results.append(
147
- (
148
- "Mixed local",
149
- await run_test(
150
- "Look up user-1 and set their role to viewer", "Mixed local"
151
- ),
152
- )
153
- )
154
- results.append(
155
- (
156
- "Remote (weathermap)",
157
- await run_test("What is the weather in Tokyo?", "Remote"),
158
- )
159
- )
160
- results.append(
177
+ tests = [
178
+ ("Look up user-2", "Standalone (inferred slug/name)"),
179
+ ("Generate a formal greeting for Alice", "Standalone (overridden slug/name)"),
180
+ ("Set user-1 role to developer", "Toolkit tool"),
181
+ ("Look up user-1 and set their role to viewer", "Mixed local tools"),
182
+ ("What is the weather in Tokyo?", "Remote (weathermap)"),
183
(
162
- "Gmail proxy",
163
- await run_test(
164
- 'Create a Gmail draft to bob@acme.com with subject "Test" and body "Hello!"',
165
- "Gmail proxy",
166
- ),
167
- )
168
- )
169
- results.append(
184
+ 'Draft an email to bob@acme.com with subject "Test" and body "Hello!"',
185
+ "Gmail proxy (extends_toolkit)",
186
+ ),
187
(
171
- "Mixed all",
172
- await run_test(
173
- "Look up user-1, draft them an email saying hi, include weather in SF",
174
- "Mixed all",
175
- ),
176
- )
177
- )
188
+ "Look up user-1, draft them an email saying hi, include weather in SF",
189
+ "Mixed all paths",
190
+ ),
191
+ ]
192
+
193
+ results = []
194
+ for prompt, name in tests:
195
+ ok = await run_test(prompt, name)
196
+ results.append((name, ok))
197
198
print(f"\n{'=' * 60}")
199
print("RESULTS")
python/examples/custom_tools_v2.py
deleted
-103
@@ -1,103 +0,0 @@
1
-"""
2
-Custom Tools v2 — decorator API for tool router sessions.
3
-
4
-Usage:
5
- COMPOSIO_API_KEY=... python examples/custom_tools_v2.py
6
-"""
7
-
8
-from pydantic import BaseModel, Field
9
-
10
-from composio import Composio
11
-
12
-
13
-composio = Composio()
14
-
15
-# ── 1. Standalone tool (no auth) ────────────────────────────────
16
-
17
-
18
-class UserLookupInput(BaseModel):
19
- user_id: str = Field(description="User ID (e.g. user-1)")
20
-
21
-
22
-USERS = {
23
- "user-1": {"name": "Alice Johnson", "email": "alice@acme.com", "role": "admin"},
24
- "user-2": {"name": "Bob Smith", "email": "bob@acme.com", "role": "developer"},
25
-}
26
-
27
-
28
-@composio.experimental.tool()
29
-def get_user(input: UserLookupInput, ctx):
30
- """Look up an internal user by ID."""
31
- user = USERS.get(input.user_id)
32
- if not user:
33
- raise ValueError(f'User "{input.user_id}" not found')
34
- return user
35
-
36
-
37
-# ── 2. Custom toolkit with grouped tools ────────────────────────
38
-
39
-
40
-class SetRoleInput(BaseModel):
41
- user_id: str = Field(description="User ID")
42
- role: str = Field(description="New role (admin, developer, viewer)")
43
-
44
-
45
-role_manager = composio.experimental.Toolkit(
46
- slug="ROLE_MANAGER",
47
- name="Role Manager",
48
- description="Manage user roles",
49
-)
50
-
51
-
52
-@role_manager.tool()
53
-def set_role(input: SetRoleInput, ctx):
54
- """Set a user's role."""
55
- return {
56
- "user_id": input.user_id,
57
- "role": input.role,
58
- "updated": True,
59
- }
60
-
61
-
62
-# ── Session ─────────────────────────────────────────────────────
63
-
64
-
65
-def main():
66
- print("Creating session with custom tools...")
67
- session = composio.create(
68
- user_id="default",
69
- experimental={
70
- "custom_tools": [get_user],
71
- "custom_toolkits": [role_manager],
72
- },
73
- )
74
- print(f"Session ID: {session.session_id}")
75
-
76
- print("\n── Registered custom tools ──")
77
- for tool in session.custom_tools():
78
- print(f" {tool.slug} ({tool.toolkit or 'standalone'})")
79
-
80
- print("\n── Test: GET_USER ──")
81
- result = session.execute("GET_USER", arguments={"user_id": "user-1"})
82
- print(f" {result}")
83
- assert result["data"]["name"] == "Alice Johnson"
84
- print(" PASS")
85
-
86
- print("\n── Test: SET_ROLE ──")
87
- result = session.execute(
88
- "SET_ROLE", arguments={"user_id": "user-1", "role": "viewer"}
89
- )
90
- print(f" {result}")
91
- assert result["data"]["updated"] is True
92
- print(" PASS")
93
-
94
- print("\n── Test: Validation error ──")
95
- result = session.execute("GET_USER", arguments={})
96
- assert result["error"] is not None
97
- print(" PASS")
98
-
99
- print("\nAll tests passed!")
100
-
101
-
102
-if __name__ == "__main__":
103
- main()