@devries-cameron20 / composio-1 / commits / 78344e5af
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.

add openai toolset

haxzie committed Apr 16, 2025 at 15:06 UTC 78344e5af6426a465dd6147761dd386f4ca4dd6e
2 files changed +227 -11
packages/core/src/composio.ts
+32 -1
@@ -10,13 +10,15 @@ import { ConnectedAccounts } from "./models/ConnectedAccounts";
10 import { ToolListParams } from "@composio/client/resources/tools";
11 import { BaseComposioToolset } from "./toolset/BaseToolset";
12
13 +
14 export type ComposioConfig<TTool, T extends BaseComposioToolset<TTool>> = {
15 apiKey?: string;
16 baseURL?: string;
16 - runtime?: string;
17 allowTracking?: boolean;
18 allowTracing?: boolean;
19 toolset?: T;
20 + userId?: string;
21 + connectedAccountIds?: Record<string, string>;
22 };
23
24 /**
@@ -24,14 +26,28 @@ export type ComposioConfig<TTool, T extends BaseComposioToolset<TTool>> = {
26 * It is used to initialize the Composio SDK and provide a global configuration.
27 */
28 export class Composio<TTool, T extends BaseComposioToolset<TTool>> {
29 +
30 + private readonly DEFAULT_USER_ID = "default";
31 + private static readonly FILE_NAME = "core/composio.ts";
32 +
33 /**
34 * The Composio API client.
35 * @type {ComposioClient}
36 */
37 private client: ComposioClient;
38
39 + /**
40 + * The configuration for the Composio SDK.
41 + * @type {ComposioConfig<TTool, T>}
42 + */
43 private config: ComposioConfig<TTool, T>;
44
45 + /**
46 + * Context variables for the Composio SDK.
47 + */
48 + userId?: string;
49 + connectedAccountIds?: Record<string, string>;
50 +
51 /**
52 * Core models for Composio.
53 */
@@ -67,6 +83,12 @@ export class Composio<TTool, T extends BaseComposioToolset<TTool>> {
83 */
84 this.config = config;
85
86 + /**
87 + * Set the context variables for the Composio SDK.
88 + */
89 + this.userId = config.userId?? this.DEFAULT_USER_ID; // entity id of the user
90 + this.connectedAccountIds = config.connectedAccountIds?? {}; // app name -> account id of the connected account
91 +
92 /**
93 * Set the default toolset, if not provided by the user.
94 */
@@ -83,6 +105,15 @@ export class Composio<TTool, T extends BaseComposioToolset<TTool>> {
105 this.connectedAccounts = new ConnectedAccounts(this.client);
106 }
107
108 + /**
109 + * Get the connected account id for the given app name.
110 + * @param appName - The name of the app.
111 + * @returns {string | undefined} The connected account id for the given app name.
112 + */
113 + getConnectedAccountId(appName: string): string | undefined {
114 + return this.connectedAccountIds?.[appName];
115 + }
116 +
117 /**
118 * Get the Composio SDK client.
119 * @returns {ComposioClient} The Composio API client.
packages/toolsets/openai/src/index.ts
+195 -10
@@ -1,12 +1,18 @@
1 import { BaseComposioToolset, Composio, Toolset } from "@composio/core";
2 import { Tool } from "@composio/core";
3 import { OpenAI } from "openai";
4 +import { Stream } from "openai/streaming";
5
6 export class OpenAIToolset extends BaseComposioToolset<OpenAI.ChatCompletionTool> {
7 static readonly FRAMEWORK_NAME = "openai";
7 - static readonly DEFAULT_USER_ID = "default";
8 private static readonly FILE_NAME = "toolsets/openai/src/index.ts";
9
10 + /**
11 + * Absract method to wrap a tool in the toolset.
12 + * This method is implemented by the toolset.
13 + * @param tool - The tool to wrap.
14 + * @returns The wrapped tool.
15 + */
16 _wrapTool = (tool: Tool): OpenAI.ChatCompletionTool => {
17 const formattedSchema: OpenAI.FunctionDefinition = {
18 name: tool.name!,
@@ -19,6 +25,31 @@ export class OpenAIToolset extends BaseComposioToolset<OpenAI.ChatCompletionTool
25 };
26 };
27
28 + /**
29 + * Get all the tools from the client.
30 + * @returns {Promise<OpenAI.ChatCompletionTool[]>} The tools.
31 + */
32 + async getTools (): Promise<OpenAI.ChatCompletionTool[]> {
33 + if (!this.client) {
34 + throw new Error("Client not set");
35 + }
36 + const tools = await this.client.tools.list();
37 + return tools.items.map((tool) => this._wrapTool(tool as Tool));
38 + }
39 +
40 + /**
41 + * Get a tool from the client.
42 + * @param id - The id of the tool.
43 + * @returns {Promise<OpenAI.ChatCompletionTool>} The tool.
44 + */
45 + async getTool (id: string): Promise<OpenAI.ChatCompletionTool> {
46 + if (!this.client) {
47 + throw new Error("Client not set");
48 + }
49 + const tool = await this.client.tools.get(id);
50 + return this._wrapTool(tool as Tool);
51 + }
52 +
53 /**
54 * @TODO include the connectedAccountId / app name in the tool call
55 * @param tool
@@ -35,20 +66,24 @@ export class OpenAIToolset extends BaseComposioToolset<OpenAI.ChatCompletionTool
66 }
67
68 const toolSchema = await this.client.tools.get(tool.function.name);
69 + const appName = toolSchema?.name.toLowerCase();
70 const results = await this.client.tools.execute(toolSchema.name, {
71 arguments: JSON.parse(tool.function.arguments),
40 - entity_id: userId,
72 + entity_id: userId ?? this.client.userId,
73 + connected_account_id: this.client.getConnectedAccountId(appName)
74 });
75
76 return JSON.stringify(results);
77 }
78
79 /**
80 + * Handle the tool call from the assistant.
81 *
48 - * @param tool
49 - * @returns
82 + * @param {OpenAI.ChatCompletion} chatCompletion - The chat completion object.
83 + * @param {string} userId - The user id.
84 + * @returns {Promise<string[]>} The results of the tool call.
85 */
51 - handleToolCall = async (chatCompletion: OpenAI.ChatCompletion, userId?: string) => {
86 + async handleToolCall (chatCompletion: OpenAI.ChatCompletion, userId?: string) {
87 const outputs: string[] = [];
88 for (const message of chatCompletion.choices) {
89 if (message.message.tool_calls) {
@@ -60,16 +95,166 @@ export class OpenAIToolset extends BaseComposioToolset<OpenAI.ChatCompletionTool
95 return outputs;
96 };
97
98 + /**
99 + * Handles all the tool calls from the assistant.
100 + *
101 + * @param {OpenAI.Beta.Threads.Run} run - The run object.
102 + * @param {string} userId - The user id.
103 + * @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} The tool outputs.
104 + */
105 + async handleAssistantMessage(run: OpenAI.Beta.Threads.Run, userId?: string) {
106 + const tool_calls =
107 + run.required_action?.submit_tool_outputs?.tool_calls || [];
108 + const tool_outputs: Array<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput> =
109 + await Promise.all(
110 + tool_calls.map(async (tool_call) => {
111 + // @TOOD: Log the tool call
112
64 - handleAssistantMessage(run: OpenAI.Beta.Threads.Run, userId?: string) {
65 - const threadId = run.thread_id;
113 + // Execute each tool call and get the response
114 + const tool_response = await this.executeToolCall(
115 + tool_call as OpenAI.ChatCompletionMessageToolCall,
116 + userId
117 + );
118 +
119 + // @TODO: Log the tool response
120 +
121 + return {
122 + tool_call_id: tool_call.id,
123 + output: JSON.stringify(tool_response),
124 + };
125 + })
126 + );
127 + return tool_outputs;
128 }
129
68 - async *waitAndHandleAssistantStreamToolCalls() {
130 + /**
131 + * Waits for the assistant stream and handles the tool calls.
132 + *
133 + * @param {OpenAI} client - The OpenAI client.
134 + * @param {Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>} runStream - The run stream.
135 + * @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
136 + * @param {string} userId - The user id.
137 + * @returns {AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>} The run stream.
138 + */
139 + async *waitAndHandleAssistantStreamToolCalls( client: OpenAI,
140 + runStream: Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>,
141 + thread: OpenAI.Beta.Threads.Thread,
142 + userId?: string) {
143 +
144 + // @TODO: Log the run stream
145 + const defaultUserId = this.client?.userId;
146 + let runId = null;
147
70 - }
148 + // Start processing the runStream events
149 + for await (const event of runStream) {
150 + yield event; // Yield each event from the stream as it arrives
151
72 - async waitAndHandleAssistantToolCalls() {
152 + if (event.event === "thread.run.created") {
153 + const { id } = event.data;
154 + runId = id;
155 + }
156 +
157 + if (!runId) {
158 + continue;
159 + }
160 +
161 + // Handle the 'requires_action' event
162 + if (event.event === "thread.run.requires_action") {
163 + const toolOutputs = await this.handleAssistantMessage(
164 + event.data,
165 + userId ?? defaultUserId
166 + );
167 +
168 + // Submit the tool outputs
169 + await client.beta.threads.runs.submitToolOutputs(thread.id, runId, {
170 + tool_outputs: toolOutputs,
171 + });
172 + }
173
174 + // Break if the run status becomes inactive
175 + if (
176 + [
177 + "thread.run.completed",
178 + "thread.run.failed",
179 + "thread.run.cancelled",
180 + "thread.run.expired",
181 + ].includes(event.event)
182 + ) {
183 + break;
184 + }
185 + }
186 +
187 + if (!runId) {
188 + throw new Error("No run ID found");
189 + }
190 +
191 + // Handle any final actions after the stream ends
192 + let finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
193 +
194 + while (
195 + ["queued", "in_progress", "requires_action"].includes(finalRun.status)
196 + ) {
197 + if (finalRun.status === "requires_action") {
198 + const toolOutputs = await this.handleAssistantMessage(
199 + finalRun,
200 + userId ?? defaultUserId
201 + );
202 +
203 + // Submit tool outputs
204 + finalRun = await client.beta.threads.runs.submitToolOutputs(
205 + thread.id,
206 + runId,
207 + {
208 + tool_outputs: toolOutputs,
209 + }
210 + );
211 + } else {
212 + // Update the run status
213 + finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
214 + await new Promise((resolve) => setTimeout(resolve, 500)); // Wait before rechecking
215 + }
216 + }
217 +
218 + }
219 +
220 + /**
221 + * Waits for the assistant tool calls and handles them.
222 + *
223 + * @param {OpenAI} client - The OpenAI client.
224 + * @param {OpenAI.Beta.Threads.Run} run - The run object.
225 + * @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
226 + * @param {string} userId - The user id.
227 + * @returns {Promise<OpenAI.Beta.Threads.Run>} The run object.
228 + */
229 + async waitAndHandleAssistantToolCalls(
230 + client: OpenAI,
231 + run: OpenAI.Beta.Threads.Run,
232 + thread: OpenAI.Beta.Threads.Thread,
233 + userId?: string
234 + ) {
235 + const defaultUserId = this.client?.userId;
236 + while (["queued", "in_progress", "requires_action"].includes(run.status)) {
237 + // logger.debug(`Current run status: ${run.status}`);
238 + const tool_outputs = await this.handleAssistantMessage(
239 + run,
240 + userId ?? defaultUserId
241 + );
242 + if (run.status === "requires_action") {
243 + // logger.debug(
244 + // `Submitting tool outputs for run ID: ${run.id} in thread ID: ${thread.id}`
245 + // );
246 + run = await client.beta.threads.runs.submitToolOutputs(
247 + thread.id,
248 + run.id,
249 + {
250 + tool_outputs: tool_outputs,
251 + }
252 + );
253 + } else {
254 + run = await client.beta.threads.runs.retrieve(thread.id, run.id);
255 + await new Promise((resolve) => setTimeout(resolve, 500));
256 + }
257 + }
258 + return run;
259 }
260 }
\ No newline at end of file