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
py 196 lines 6.03 KB
Raw
1 """
2 Custom Tools — local tools + proxy execute with OpenAI Agents SDK.
3
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
10 """
11 # ruff: noqa: E302, E303
12
13 import asyncio
14 import base64
15 import os
16 import sys
17
18 from agents import Agent, Runner
19 from pydantic import BaseModel, Field
20 from composio import Composio
21 from composio_openai_agents import OpenAIAgentsProvider
22
23 composio = Composio(
24 provider=OpenAIAgentsProvider(),
25 )
26
27 # ── 1. Standalone tool — slug/name/description inferred from function ──
28
29
30 class UserLookupInput(BaseModel):
31 user_id: str = Field(description="User ID (e.g. user-1)")
32
33
34 USERS = {
35 "user-1": {"name": "Alice Johnson", "email": "alice@acme.com", "role": "admin"},
36 "user-2": {"name": "Bob Smith", "email": "bob@acme.com", "role": "developer"},
37 }
38
39
40 @composio.experimental.tool()
41 def get_user(input: UserLookupInput, ctx):
42 """Look up an internal user by ID. Returns name, email, and role."""
43 user = USERS.get(input.user_id)
44 if not user:
45 raise ValueError(f'User "{input.user_id}" not found')
46 return user
47
48
49 # ── 2. Standalone tool with overrides ──────────────────────────────────
50
51
52 class GreetInput(BaseModel):
53 name: str = Field(description="Name to greet")
54 style: str = Field(default="friendly", description="Greeting style")
55
56
57 @composio.experimental.tool(
58 slug="GREET_V2",
59 name="Greeting Generator",
60 description="Generate a personalized greeting message in different styles.",
61 )
62 def greet(input: GreetInput, ctx):
63 """This docstring is ignored because description= is set above."""
64 greetings = {
65 "friendly": f"Hey {input.name}! Great to see you!",
66 "formal": f"Dear {input.name}, I hope this message finds you well.",
67 "casual": f"Yo {input.name}, what's up?",
68 }
69 return {"message": greetings.get(input.style, f"Hello {input.name}!")}
70
71
72 # ── 3. Extension tool — inherits Gmail auth via ctx.proxy_execute() ────
73
74
75 class DraftInput(BaseModel):
76 to: str = Field(description="Recipient email address")
77 subject: str = Field(description="Email subject")
78 body: str = Field(description="Email body (plain text)")
79
80
81 @composio.experimental.tool(extends_toolkit="gmail")
82 def create_draft(input: DraftInput, ctx):
83 """Create a real Gmail draft. Appears in the user's drafts folder."""
84 raw_msg = (
85 f"To: {input.to}\r\nSubject: {input.subject}\r\n"
86 f"Content-Type: text/plain; charset=UTF-8\r\n\r\n{input.body}"
87 )
88 raw = base64.urlsafe_b64encode(raw_msg.encode()).decode().rstrip("=")
89 res = ctx.proxy_execute(
90 toolkit="gmail",
91 endpoint="https://gmail.googleapis.com/gmail/v1/users/me/drafts",
92 method="POST",
93 body={"message": {"raw": raw}},
94 )
95 if res["status"] != 200:
96 raise RuntimeError(f"Gmail API error {res['status']}")
97 data = res["data"]
98 return {"draft_id": data["id"], "to": input.to, "subject": input.subject}
99
100
101 # ── 4. Custom toolkit — groups related tools under one namespace ───────
102
103 role_manager = composio.experimental.Toolkit(
104 slug="ROLE_MANAGER",
105 name="Role Manager",
106 description="Manage user roles in the system",
107 )
108
109
110 class SetRoleInput(BaseModel):
111 user_id: str = Field(description="User ID")
112 role: str = Field(description="New role (admin, developer, viewer)")
113
114
115 @role_manager.tool()
116 def set_role(input: SetRoleInput, ctx):
117 """Set a user's role. Returns confirmation."""
118 return {"user_id": input.user_id, "role": input.role, "updated": True}
119
120
121 @role_manager.tool(name="List All Roles")
122 def list_roles(input: UserLookupInput, ctx):
123 """List available roles for a user."""
124 return {"roles": ["admin", "developer", "viewer"], "current": "admin"}
125
126
127 # ── Agent ──────────────────────────────────────────────────────────────
128
129
130 async def run_test(prompt, test_name):
131 print(f"\n{'=' * 60}")
132 print(f"TEST: {test_name}")
133 print(f"{'=' * 60}")
134
135 session = composio.create(
136 user_id="default",
137 toolkits=["gmail", "weathermap"],
138 manage_connections=True,
139 experimental={
140 "local_tools": [get_user, greet, create_draft],
141 "local_toolkits": [role_manager],
142 },
143 )
144 tools = session.tools()
145 agent = Agent(
146 name="Assistant",
147 instructions=(
148 "You are a helpful assistant. Use Composio tools to execute tasks. "
149 "In MULTI_EXECUTE, always pass arguments inside the arguments field."
150 ),
151 model="gpt-4.1-mini",
152 tools=tools,
153 )
154
155 print(f"> {prompt}\n")
156 try:
157 result = await Runner.run(agent, prompt, max_turns=25)
158 print(f"\nAgent: {result.final_output}")
159 return True
160 except Exception as e:
161 print(f"\nERROR: {e}")
162 return False
163
164
165 async def main():
166 # One test per custom-tool pattern: standalone, custom toolkit, extension.
167 tests = [
168 ("Look up user-2", "Standalone (inferred slug/name)"),
169 ("Set user-1 role to developer", "Toolkit tool"),
170 (
171 'Draft an email to bob@acme.com with subject "Test" and body "Hello!"',
172 "Gmail proxy",
173 ),
174 ]
175
176 results = []
177 for prompt, name in tests:
178 ok = await run_test(prompt, name)
179 results.append((name, ok))
180
181 print(f"\n{'=' * 60}")
182 print("RESULTS")
183 print(f"{'=' * 60}")
184 for name, ok in results:
185 print(f" [{'PASS' if ok else 'FAIL'}] {name}")
186 print(f"\n{sum(1 for _, ok in results if ok)}/{len(results)} passed")
187
188 if not all(ok for _, ok in results):
189 sys.exit(1)
190
191
192 if __name__ == "__main__":
193 if not os.environ.get("OPENAI_API_KEY"):
194 print("Error: OPENAI_API_KEY env var required")
195 sys.exit(1)
196 asyncio.run(main())