Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
docs(python): update e2e examples to use decorator API
Dhawal Upadhyay4bc4476ba87c
diff --git a/python/examples/custom_tools_agent_test.py b/python/examples/custom_tools_agent_test.pyindex cfeaa48c0..f979f4d00 100644--- a/python/examples/custom_tools_agent_test.py+++ b/python/examples/custom_tools_agent_test.py@@ -1,11 +1,7 @@"""-Custom Tools Agent Test — full LLM agent loop with OpenAI Agents SDK.+Custom Tools Agent Test — decorator API with OpenAI Agents SDK.-Tests all custom tool patterns end-to-end through an actual multi-turn agent:-1. Standalone custom tool (GET_USER) — local execution, no auth-2. Custom toolkit tool (SET_ROLE) — local execution, grouped under ROLE_MANAGER-3. Extension tool (CREATE_DRAFT) — local execution, inherits Gmail auth via proxy_execute-4. Remote Composio tool (weathermap) — backend execution+Tests all custom tool patterns end-to-end through a real LLM agent loop.Usage:COMPOSIO_API_KEY=... OPENAI_API_KEY=... python examples/custom_tools_agent_test.py@@ -19,13 +15,15 @@ import sysfrom agents import Agent, Runnerfrom pydantic import BaseModel, Field-from composio import Composio, experimental_create_tool, experimental_create_toolkit+from composio import Composiofrom composio_openai_agents import OpenAIAgentsProvider+composio = Composio(provider=OpenAIAgentsProvider())+++# ── 1. Standalone tool ──────────────────────────────────────────-# ── Custom tools ────────────────────────────────────────────────-# 1. Standalone tool (no auth)class UserLookupInput(BaseModel):user_id: str = Field(description="User ID (e.g. user-1)")@@ -35,97 +33,73 @@ USERS = {"user-2": {"name": "Bob Smith", "email": "[email protected]", "role": "developer"},}-get_user = experimental_create_tool(- "GET_USER",- name="Get user",- description="Look up an internal user by ID. Returns name, email, and role.",- input_params=UserLookupInput,- execute=lambda input, ctx: USERS.get(input.user_id)- or (_ for _ in ()).throw(ValueError(f'User "{input.user_id}" not found')),-)+def get_user(input: UserLookupInput, ctx):+ """Look up an internal user by ID. Returns name, email, and role."""+ user = USERS.get(input.user_id)+ if not user:+ raise ValueError(f'User "{input.user_id}" not found')+ return user-# 2. Custom toolkit with grouped tools-class SetRoleInput(BaseModel):- user_id: str = Field(description="User ID")- role: str = Field(description="New role (admin, developer, viewer)")--role_manager = experimental_create_toolkit(- "ROLE_MANAGER",- name="Role Manager",- description="Manage user roles in the system",- tools=[- experimental_create_tool(- "SET_ROLE",- name="Set role",- description="Set a user's role. Returns confirmation with updated role.",- input_params=SetRoleInput,- execute=lambda input, ctx: {- "user_id": input.user_id,- "role": input.role,- "updated": True,- "message": f"Role for {input.user_id} changed to {input.role}",- },- ),- ],-)+# ── 2. Extension tool (Gmail proxy) ─────────────────────────────-# 3. Extension tool — inherits Gmail auth, calls real API via proxy_executeclass DraftInput(BaseModel):to: str = Field(description="Recipient email address")subject: str = Field(description="Email subject")body: str = Field(description="Email body (plain text)")-def create_draft_fn(input: DraftInput, ctx):- """Create a real Gmail draft via proxy_execute."""- raw_message = (- f"To: {input.to}\r\n"- f"Subject: {input.subject}\r\n"- f"Content-Type: text/plain; charset=UTF-8\r\n"- f"\r\n"- f"{input.body}"[email protected](extends_toolkit="gmail")+def create_draft(input: DraftInput, ctx):+ """Create a real Gmail draft. Appears in the user's drafts folder."""+ raw_msg = (+ f"To: {input.to}\r\nSubject: {input.subject}\r\n"+ f"Content-Type: text/plain; charset=UTF-8\r\n\r\n{input.body}")- raw = base64.urlsafe_b64encode(raw_message.encode()).decode().rstrip("=")-+ raw = base64.urlsafe_b64encode(raw_msg.encode()).decode().rstrip("=")res = ctx.proxy_execute(toolkit="gmail",endpoint="https://gmail.googleapis.com/gmail/v1/users/me/drafts",method="POST",body={"message": {"raw": raw}},)-if res["status"] != 200:- raise RuntimeError(f"Gmail API error {res['status']}: {res.get('data')}")+ raise RuntimeError(f"Gmail API error {res['status']}")data = res["data"]- return {- "draft_id": data["id"],- "message_id": data["message"]["id"],- "to": input.to,- "subject": input.subject,- }---create_draft = experimental_create_tool(- "CREATE_DRAFT",- name="Create Gmail draft",- description="Create a real Gmail draft. Appears in the user's drafts folder.",- extends_toolkit="gmail",- input_params=DraftInput,- execute=create_draft_fn,+ return {"draft_id": data["id"], "to": input.to, "subject": input.subject}+++# ── 3. Custom toolkit ───────────────────────────────────────────+++class SetRoleInput(BaseModel):+ user_id: str = Field(description="User ID")+ role: str = Field(description="New role (admin, developer, viewer)")+++role_manager = composio.experimental.Toolkit(+ slug="ROLE_MANAGER",+ name="Role Manager",+ description="Manage user roles in the system",)-# ── Test runner ─────────────────────────────────────────────────+@role_manager.tool()+def set_role(input: SetRoleInput, ctx):+ """Set a user's role. Returns confirmation."""+ return {"user_id": input.user_id, "role": input.role, "updated": True}+++# ── Agent test runner ───────────────────────────────────────────-async def run_test(composio, prompt, test_name):- """Run a single agent test with the given prompt."""- print(f"\n{'='*60}")+async def run_test(prompt, test_name):+ print(f"\n{'=' * 60}")print(f"TEST: {test_name}")- print(f"{'='*60}")+ print(f"{'=' * 60}")session = composio.create(user_id="default",@@ -136,9 +110,7 @@ async def run_test(composio, prompt, test_name):"custom_toolkits": [role_manager],},)- print(f"Session: {session.session_id}")tools = session.tools()- print(f"Tools: {len(tools)}")agent = Agent(name="Assistant",@@ -161,72 +133,59 @@ async def run_test(composio, prompt, test_name):async def main():- composio = Composio(provider=OpenAIAgentsProvider())-results = []-- # Test 1: Standalone custom tool only- ok = await run_test(- composio,- "Look up user-2's information",- "Standalone custom tool (GET_USER)",+ results.append(+ ("Standalone (GET_USER)", await run_test("Look up user-2", "Standalone")))- results.append(("Standalone custom tool", ok))-- # Test 2: Custom toolkit tool- ok = await run_test(- composio,- "Set user-1's role to developer",- "Custom toolkit tool (SET_ROLE)",+ results.append(+ (+ "Toolkit (SET_ROLE)",+ await run_test("Set user-1 role to developer", "Toolkit"),+ ))- results.append(("Custom toolkit tool", ok))-- # Test 3: Mixed — local + local toolkit- ok = await run_test(- composio,- "Look up user-1 and then set their role to viewer",- "Mixed local tools (GET_USER + SET_ROLE)",+ results.append(+ (+ "Mixed local",+ await run_test(+ "Look up user-1 and set their role to viewer", "Mixed local"+ ),+ ))- results.append(("Mixed local tools", ok))-- # Test 4: Remote Composio tool (weathermap, no auth needed)- ok = await run_test(- composio,- "What is the current weather in San Francisco?",- "Remote Composio tool (weathermap)",+ results.append(+ (+ "Remote (weathermap)",+ await run_test("What is the weather in Tokyo?", "Remote"),+ ))- results.append(("Remote Composio tool", ok))-- # Test 5: Gmail proxy execute (CREATE_DRAFT via ctx.proxy_execute)- ok = await run_test(- composio,- 'Create a Gmail draft to [email protected] with subject "Hello from Python SDK" and body "Testing custom tools proxy_execute!"',- "Gmail proxy execute (CREATE_DRAFT)",+ results.append(+ (+ "Gmail proxy",+ await run_test(+ 'Create a Gmail draft to [email protected] with subject "Test" and body "Hello!"',+ "Gmail proxy",+ ),+ ))- results.append(("Gmail proxy (CREATE_DRAFT)", ok))-- # Test 6: Mixed all paths — local + proxy + remote in one turn- ok = await run_test(- composio,- "Look up user-1, then draft them an email saying hi and include the current weather in San Francisco in the body",- "Mixed all paths (GET_USER + CREATE_DRAFT + weathermap)",+ results.append(+ (+ "Mixed all",+ await run_test(+ "Look up user-1, draft them an email saying hi, include weather in SF",+ "Mixed all",+ ),+ ))- results.append(("Mixed all paths", ok))- # Summary- print(f"\n{'='*60}")+ print(f"\n{'=' * 60}")print("RESULTS")- print(f"{'='*60}")+ print(f"{'=' * 60}")for name, ok in results:- status = "PASS" if ok else "FAIL"- print(f" [{status}] {name}")- passed = sum(1 for _, ok in results if ok)- print(f"\n{passed}/{len(results)} tests passed")+ print(f" [{'PASS' if ok else 'FAIL'}] {name}")+ print(f"\n{sum(1 for _, ok in results if ok)}/{len(results)} passed")if __name__ == "__main__":if not os.environ.get("OPENAI_API_KEY"):print("Error: OPENAI_API_KEY env var required")sys.exit(1)-asyncio.run(main())diff --git a/python/examples/custom_tools_v2.py b/python/examples/custom_tools_v2.pyindex 028a04147..2a4fe0d31 100644--- a/python/examples/custom_tools_v2.py+++ b/python/examples/custom_tools_v2.py@@ -1,22 +1,20 @@"""-Custom Tools v2 — local tools + proxy execute with tool router sessions.--Shows how to create custom tools that run in-process alongside-remote Composio tools. Equivalent of ts/examples/tool-router/src/custom-tools.ts.+Custom Tools v2 — decorator API for tool router sessions.Usage:COMPOSIO_API_KEY=... python examples/custom_tools_v2.py"""-import base64import sysfrom pydantic import BaseModel, Field-from composio import Composio, experimental_create_tool, experimental_create_toolkit+from composio import Composio++composio = Composio()-# ── Custom tools ────────────────────────────────────────────────+# ── 1. Standalone tool (no auth) ────────────────────────────────class UserLookupInput(BaseModel):@@ -29,7 +27,8 @@ USERS = {}-def get_user_fn(input: UserLookupInput, ctx):+def get_user(input: UserLookupInput, ctx):"""Look up an internal user by ID."""user = USERS.get(input.user_id)if not user:@@ -37,62 +36,7 @@ def get_user_fn(input: UserLookupInput, ctx):return user-get_user = experimental_create_tool(- "GET_USER",- name="Get user",- description="Look up an internal user by ID",- input_params=UserLookupInput,- execute=get_user_fn,-)---class DraftInput(BaseModel):- to: str = Field(description="Recipient email address")- subject: str = Field(description="Email subject")- body: str = Field(description="Email body (plain text)")---def create_draft_fn(input: DraftInput, ctx):- """Create a real Gmail draft via the Gmail API."""- raw_message = (- f"To: {input.to}\r\n"- f"Subject: {input.subject}\r\n"- f"Content-Type: text/plain; charset=UTF-8\r\n"- f"\r\n"- f"{input.body}"- )- raw = (- base64.urlsafe_b64encode(raw_message.encode("utf-8"))- .decode("ascii")- .rstrip("=")- )-- res = ctx.proxy_execute(- toolkit="gmail",- endpoint="https://gmail.googleapis.com/gmail/v1/users/me/drafts",- method="POST",- body={"message": {"raw": raw}},- )-- if res["status"] != 200:- raise RuntimeError(f"Gmail API error {res['status']}: {res.get('data')}")- data = res["data"]- return {- "draft_id": data["id"],- "message_id": data["message"]["id"],- "to": input.to,- "subject": input.subject,- }---create_draft = experimental_create_tool(- "CREATE_DRAFT",- name="Create Gmail draft",- description="Create a real Gmail draft via the Gmail API. Appears in the user's drafts folder.",- extends_toolkit="gmail",- input_params=DraftInput,- execute=create_draft_fn,-)+# ── 2. Custom toolkit with grouped tools ────────────────────────class SetRoleInput(BaseModel):@@ -100,114 +44,61 @@ class SetRoleInput(BaseModel):role: str = Field(description="New role (admin, developer, viewer)")-role_manager = experimental_create_toolkit(- "ROLE_MANAGER",+role_manager = composio.experimental.Toolkit(+ slug="ROLE_MANAGER",name="Role Manager",description="Manage user roles",- tools=[- experimental_create_tool(- "SET_ROLE",- name="Set role",- description="Set a user's role",- input_params=SetRoleInput,- execute=lambda input, ctx: {- "user_id": input.user_id,- "role": input.role,- "updated": True,- },- ),- ],)+@role_manager.tool()+def set_role(input: SetRoleInput, ctx):+ """Set a user's role."""+ return {+ "user_id": input.user_id,+ "role": input.role,+ "updated": True,+ }++# ── Session ─────────────────────────────────────────────────────def main():- composio = Composio()-print("Creating session with custom tools...")session = composio.create(user_id="default",- toolkits=["gmail"],experimental={- "custom_tools": [get_user, create_draft],+ "custom_tools": [get_user],"custom_toolkits": [role_manager],},)print(f"Session ID: {session.session_id}")- # List registered custom toolsprint("\n── Registered custom tools ──")for tool in session.custom_tools():print(f" {tool.slug} ({tool.toolkit or 'standalone'})")- print("\n── Registered custom toolkits ──")- for tk in session.custom_toolkits():- print(f" {tk.slug}: {[t.slug for t in tk.tools]}")-- # Test 1: Execute standalone custom tool (local, no network)- print("\n── Test 1: Execute GET_USER (standalone, local) ──")+ print("\n── Test: GET_USER ──")result = session.execute("GET_USER", arguments={"user_id": "user-1"})- print(f" Result: {result}")- assert result["data"]["name"] == "Alice Johnson", "GET_USER failed!"- assert result["error"] is None- print(" ✓ Passed")-- # Test 2: Execute by final slug- print("\n── Test 2: Execute LOCAL_GET_USER (by final slug) ──")- result = session.execute("LOCAL_GET_USER", arguments={"user_id": "user-2"})- print(f" Result: {result}")- assert result["data"]["name"] == "Bob Smith", "LOCAL_GET_USER failed!"- print(" ✓ Passed")-- # Test 3: Execute toolkit tool- print("\n── Test 3: Execute SET_ROLE (toolkit tool) ──")+ print(f" {result}")+ assert result["data"]["name"] == "Alice Johnson"+ print(" PASS")++ print("\n── Test: SET_ROLE ──")result = session.execute("SET_ROLE", arguments={"user_id": "user-1", "role": "viewer"})- print(f" Result: {result}")- assert result["data"]["updated"] is True, "SET_ROLE failed!"- print(" ✓ Passed")+ print(f" {result}")+ assert result["data"]["updated"] is True+ print(" PASS")- # Test 4: Validation error- print("\n── Test 4: Validation error (missing required field) ──")+ print("\n── Test: Validation error ──")result = session.execute("GET_USER", arguments={})- print(f" Result: error={result['error'][:80]}...")- assert result["error"] is not None, "Should have validation error!"- print(" ✓ Passed")-- # Test 5: Execute error- print("\n── Test 5: Execute error (user not found) ──")- result = session.execute("GET_USER", arguments={"user_id": "nonexistent"})- print(f" Result: error={result['error']}")- assert result["error"] is not None, "Should have execution error!"- print(" ✓ Passed")-- # Test 6: Pydantic defaults applied- print("\n── Test 6: Get tools (provider-wrapped) ──")- tools = session.tools()- print(f" Got {len(tools)} tools")- print(" ✓ Passed")-- # Test 7: Proxy execute (if Gmail is connected)- if "--with-gmail" in sys.argv:- print("\n── Test 7: CREATE_DRAFT via proxy_execute ──")- result = session.execute(- "CREATE_DRAFT",- arguments={- "to": "[email protected]",- "subject": "Test from Python custom tools",- "body": "Hello from the Python SDK custom tools e2e test!",- },- )- print(f" Result: {result}")- if result["error"]:- print(f" ⚠ Gmail draft failed (may need connection): {result['error']}")- else:- print(f" ✓ Draft created: {result['data']}")-- print("\n══ All tests passed! ══")+ assert result["error"] is not None+ print(" PASS")++ print("\nAll tests passed!")if __name__ == "__main__":