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 94 lines 2.52 KB
Raw
1 """
2 Tool Router direct_tools session preset with OpenAI Agents.
3
4 SESSION_PRESET_DIRECT_TOOLS is a shortcut for sessions where the full allowed
5 tool set is known upfront. It loads all tools allowed by the filters directly
6 into session.tools() and the MCP tool list.
7
8 Usage:
9 COMPOSIO_API_KEY=... OPENAI_API_KEY=... python examples/tool_router/direct_tools_preset.py
10 """
11
12 import os
13
14 from agents import Agent, Runner
15 from composio_openai_agents import OpenAIAgentsProvider
16 from pydantic import BaseModel, Field
17
18 from composio import Composio, SESSION_PRESET_DIRECT_TOOLS
19
20
21 def require_env(name: str) -> str:
22 value = os.environ.get(name)
23 if not value:
24 raise RuntimeError(f"Set {name} before running this example.")
25 return value
26
27
28 composio = Composio(
29 api_key=require_env("COMPOSIO_API_KEY"),
30 provider=OpenAIAgentsProvider(),
31 )
32 require_env("OPENAI_API_KEY")
33
34
35 class UserNoteInput(BaseModel):
36 username: str = Field(description="Hacker News username, for example pg")
37
38
39 hn_research = composio.experimental.Toolkit(
40 slug="HN_RESEARCH",
41 name="Hacker News research",
42 description="Internal research notes for Hacker News users.",
43 )
44
45
46 @hn_research.tool(
47 slug="GET_USER_NOTE",
48 name="Get Hacker News user note",
49 description="Return an internal research note for a Hacker News username.",
50 )
51 def get_user_note(input: UserNoteInput, ctx):
52 username = input.username.lower()
53 return {
54 "username": input.username,
55 "note": (
56 "Paul Graham; YC co-founder and essayist."
57 if username == "pg"
58 else f"No curated internal note for {input.username}."
59 ),
60 }
61
62
63 session = composio.create(
64 user_id="direct-tools-example-user",
65 session_preset=SESSION_PRESET_DIRECT_TOOLS,
66 toolkits=["hackernews"],
67 tools={"hackernews": {"enable": ["HACKERNEWS_GET_USER"]}},
68 experimental={
69 "local_toolkits": [hn_research],
70 },
71 )
72
73 tools = session.tools()
74 tool_names = [tool.name for tool in tools]
75 assert "HACKERNEWS_GET_USER" in tool_names
76 assert "LOCAL_HN_RESEARCH_GET_USER_NOTE" in tool_names
77 assert "COMPOSIO_SEARCH_TOOLS" not in tool_names
78
79 print("Direct tools exposed to the agent:")
80 for tool in tools:
81 print(f"- {tool.name}")
82
83 agent = Agent(
84 name="Direct Tools Demo Agent",
85 instructions="Use the provided tools to perform the task.",
86 model=os.environ.get("OPENAI_MODEL", "gpt-5.5"),
87 tools=tools,
88 )
89
90 result = Runner.run_sync(
91 agent,
92 'Look up user "pg" on Hacker News and include any internal research note.',
93 )
94 print(result.final_output)