@devries-cameron20 / composio Mirror · read-only
Fork 0

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 21, 04:45 UTC

next
ts 224 lines 8.05 KB
Raw
1 /**
2 * Custom Tools + Tool Router Agent
3 *
4 * Uses @composio/openai-agents provider with session.tools() for a proper
5 * multi-turn agent that has both remote Composio tools (via tool router) and
6 * custom local tools executing in-process.
7 *
8 * Demonstrates all three custom tool types:
9 * 1. Standalone tools (no auth) — GET_USER_DETAILS, LIST_USER_KEYS
10 * 2. Extension tool (inherits gmail auth) — FORMAT_GMAIL_EMAIL
11 * 3. Custom toolkit (USER_MANAGEMENT) — SET_USER_ROLE, UPDATE_USER_STATUS
12 *
13 * Usage:
14 * COMPOSIO_API_KEY=... OPENAI_API_KEY=... bun src/custom-tools-agent.ts
15 * COMPOSIO_SESSION_ID=... bun src/custom-tools-agent.ts # reuse a session
16 */
17 import "dotenv/config";
18 import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";
19 import { OpenAIAgentsProvider } from "@composio/openai-agents";
20 import { Agent, run } from "@openai/agents";
21 import { z } from "zod/v3";
22
23 // ── In-memory user store (shared across tools) ───────────────────
24
25 const userStore: Record<string, Record<string, unknown>> = {
26 "user-1": {
27 id: "user-1",
28 name: "Alice Johnson",
29 email: "alice@acme.com",
30 role: "admin",
31 status: "active",
32 created_at: "2024-01-15",
33 },
34 "user-2": {
35 id: "user-2",
36 name: "Bob Smith",
37 email: "bob@acme.com",
38 role: "developer",
39 status: "active",
40 created_at: "2024-03-22",
41 },
42 "user-3": {
43 id: "user-3",
44 name: "Carol Williams",
45 email: "carol@acme.com",
46 role: "viewer",
47 status: "suspended",
48 created_at: "2025-06-10",
49 },
50 };
51
52 // ── 1. Standalone tools (no auth) → LOCAL_<SLUG> ─────────────────
53
54 const getUserDetails = experimental_createTool("GET_USER_DETAILS", {
55 name: "Get user details",
56 description:
57 "Retrieve user profile information including name, email, role, and account status by user ID",
58 inputParams: z.object({
59 user_id: z.string().describe("The unique user identifier"),
60 }),
61 execute: async (input) => {
62 const user = userStore[input.user_id];
63 if (!user) throw new Error(`User "${input.user_id}" not found`);
64 return user;
65 },
66 });
67
68 const listUserKeys = experimental_createTool("LIST_USER_KEYS", {
69 name: "List user API keys",
70 description:
71 "List all active API keys for a given user, including creation date and last used timestamp",
72 inputParams: z.object({
73 user_id: z.string().describe("The user whose keys to list"),
74 include_expired: z.boolean().default(false).describe("Whether to include expired keys"),
75 }),
76 execute: async (input) => {
77 const allKeys: Record<string, Array<Record<string, unknown>>> = {
78 "user-1": [
79 { key_id: "key_abc", prefix: "sk-***abc", created_at: "2025-01-01", last_used: "2026-03-15", expired: false },
80 { key_id: "key_old", prefix: "sk-***old", created_at: "2024-01-01", last_used: "2024-06-01", expired: true },
81 ],
82 "user-2": [
83 { key_id: "key_xyz", prefix: "sk-***xyz", created_at: "2025-06-01", last_used: "2026-03-14", expired: false },
84 ],
85 };
86 const keys = allKeys[input.user_id] ?? [];
87 const filtered = input.include_expired ? keys : keys.filter((k) => !k.expired);
88 return { user_id: input.user_id, api_keys: filtered, total: filtered.length };
89 },
90 });
91
92 // ── 2. Extension tool (inherits gmail auth) → LOCAL_GMAIL_<SLUG> ──
93
94 const formatGmailEmail = experimental_createTool("FORMAT_GMAIL_EMAIL", {
95 name: "Format Gmail email",
96 description: "Format and prepare an email draft with proper HTML formatting for sending via Gmail",
97 extendsToolkit: "gmail",
98 inputParams: z.object({
99 to: z.string().describe("Recipient email address"),
100 subject: z.string().describe("Email subject line"),
101 body: z.string().describe("Email body content in markdown"),
102 }),
103 execute: async (input, ctx) => {
104 const htmlBody = input.body
105 .replace(/\*\*(.*?)\*\*/g, "<b>$1</b>")
106 .replace(/\*(.*?)\*/g, "<i>$1</i>")
107 .replace(/\n/g, "<br>");
108 return {
109 formatted: true,
110 to: input.to,
111 subject: input.subject,
112 html_body: htmlBody,
113 plain_body: input.body,
114 user_id: ctx.userId,
115 };
116 },
117 });
118
119 // ── 3. Custom toolkit (USER_MANAGEMENT) → LOCAL_USER_MANAGEMENT_<SLUG> ──
120
121 const setUserRole = experimental_createTool("SET_USER_ROLE", {
122 name: "Set user role",
123 description: "Change the role of an existing user (admin, developer, viewer)",
124 inputParams: z.object({
125 user_id: z.string().describe("The user to update"),
126 role: z.enum(["admin", "developer", "viewer"]).describe("The new role to assign"),
127 }),
128 execute: async (input) => {
129 const user = userStore[input.user_id];
130 if (!user) throw new Error(`User "${input.user_id}" not found`);
131 const previousRole = user.role;
132 user.role = input.role;
133 return { user_id: input.user_id, previous_role: previousRole, new_role: input.role };
134 },
135 });
136
137 const updateUserStatus = experimental_createTool("UPDATE_USER_STATUS", {
138 name: "Update user status",
139 description: "Activate or suspend a user account",
140 inputParams: z.object({
141 user_id: z.string().describe("The user to update"),
142 status: z.enum(["active", "suspended"]).describe("The new account status"),
143 reason: z.string().optional().describe("Reason for the status change"),
144 }),
145 execute: async (input) => {
146 const user = userStore[input.user_id];
147 if (!user) throw new Error(`User "${input.user_id}" not found`);
148 const previousStatus = user.status;
149 user.status = input.status;
150 return {
151 user_id: input.user_id,
152 previous_status: previousStatus,
153 new_status: input.status,
154 reason: input.reason ?? "No reason provided",
155 };
156 },
157 });
158
159 const userManagement = experimental_createToolkit("USER_MANAGEMENT", {
160 name: "User Management",
161 description: "Tools for managing user profiles, roles, and account status",
162 tools: [setUserRole, updateUserStatus],
163 });
164
165 const localTools = [getUserDetails, listUserKeys, formatGmailEmail];
166 const localToolkits = [userManagement];
167
168 // ── Agent ─────────────────────────────────────────────────────────
169
170 const composio = new Composio({
171 apiKey: process.env.COMPOSIO_API_KEY,
172 baseURL: process.env.COMPOSIO_BASE_URL || undefined,
173 provider: new OpenAIAgentsProvider(),
174 });
175
176 const existingSessionId = process.env.COMPOSIO_SESSION_ID;
177 const session = existingSessionId
178 ? await composio.use(existingSessionId, { localTools, localToolkits })
179 : await composio.create("custom-tools-agent-user", {
180 toolkits: ["weathermap", "gmail"],
181 manageConnections: false,
182 experimental: {
183 localTools,
184 localToolkits,
185 },
186 });
187
188 console.log(`${existingSessionId ? "Reused" : "Created"} session: ${session.sessionId}\n`);
189 const tools = await session.tools();
190
191 const agent = new Agent({
192 name: "Custom Tools Agent",
193 instructions: "You are a helpful assistant. Use Composio tools to execute tasks.",
194 model: "gpt-5.2",
195 tools,
196 });
197
198 const MAX = 3000;
199 function trunc(obj: unknown): string {
200 const json = JSON.stringify(obj, null, 2);
201 return json.length > MAX ? json.slice(0, MAX) + "\n ... (truncated)" : json;
202 }
203
204 agent.on("agent_tool_start", (_ctx, tool, details) => {
205 const toolCall = details.toolCall;
206 const input = toolCall && "arguments" in toolCall ? (toolCall.arguments ?? {}) : {};
207 console.log(`\n ┌─ ${tool.name}`);
208 console.log(` │ INPUT:\n${trunc(input)}`);
209 });
210 agent.on("agent_tool_end", (_ctx, tool, result: unknown) => {
211 let output: unknown;
212 try { output = typeof result === "string" ? JSON.parse(result) : result; } catch { output = result; }
213 console.log(` │ OUTPUT:\n${trunc(output)}`);
214 console.log(` └─ ${tool.name} done`);
215 });
216
217 const prompt = `Do the following tasks:
218 1. Get user-1's profile details and list their API keys
219 2. Promote user-3 (Carol) to developer role and reactivate her account (she was suspended by mistake)
220 3. Get the current weather in Tokyo`;
221
222 console.log(`User: ${prompt}\n`);
223 const result = await run(agent, prompt);
224 console.log(`\nAssistant: ${result.finalOutput}`);