@devries-cameron20 / composio Mirror · read-only / commits / 3a3bf6b8d
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 23, 04:15 UTC

Fix openai toolset

haxzie committed Apr 18, 2025 at 12:11 UTC 3a3bf6b8d12549c4d4855bc691115b0e3fa829b0
8 files changed +25 -302
examples/openai/package.json
-2
@@ -12,9 +12,7 @@
12 "license": "ISC",
13 "packageManager": "pnpm@10.8.0",
14 "dependencies": {
15 - "@composio/client": "0.1.0-alpha.7",
15 "@composio/core": "workspace:*",
17 - "@composio/openai-toolset": "workspace:*",
16 "openai": "^4.94.0"
17 },
18 "devDependencies": {
examples/openai/src/index.ts
+2 -3
@@ -1,15 +1,14 @@
1 import { Composio } from "@composio/core";
2 -import { OpenAIToolset } from "@composio/openai-toolset";
2 import { OpenAI } from "openai";
3
4 const openai = new OpenAI({
5 apiKey: process.env.OPENAI_API_KEY,
6 });
7
9 -// Initialize Composio with OpenAI Toolset
8 +// Initialize Composio
9 +// OpenAI Toolset is automatically installed and initialized
10 const composio = new Composio({
11 apiKey: process.env.COMPOSIO_API_KEY,
12 - toolset: new OpenAIToolset(),
12 });
13
14 // Fetch all the tools from the Composio API
packages/core/src/index.ts
+5 -1
@@ -12,6 +12,9 @@ import { jsonSchemaToModel } from "./utils/jsonSchema";
12 import type { InstrumentedInstance } from "./types/telemetry.types";
13 import { BaseTelemetryTransport } from "./telemetry/TelemetryTransport";
14
15 +// toolsets exports
16 +import { OpenAIToolset } from "./toolset/OpenAIToolset";
17 +
18 export {
19 Composio,
20 ComposioToolset,
@@ -22,5 +25,6 @@ export {
25 Toolset,
26 jsonSchemaToModel,
27 InstrumentedInstance,
25 - BaseTelemetryTransport
28 + BaseTelemetryTransport ,
29 + OpenAIToolset
30 };
packages/core/src/telemetry/Telemetry.ts
-3
@@ -87,10 +87,7 @@ export class Telemetry<U extends InstrumentedInstance> {
87
88 this.batchProcessor.pushItem(telemetryPayload);
89
90 -
91 - // @TODO: Add a try catch here to create global error handler
90 try {
93 -
91 return await originalMethod.apply(instance, args);
92 } catch (error) {
93 const telemetryPayload: TelemetryPayload = {
packages/core/src/toolset/OpenAIToolset.ts
+9 -6
@@ -8,6 +8,7 @@ import { OpenAI } from "openai";
8 import { Stream } from "openai/streaming";
9 import { BaseComposioToolset } from "./BaseToolset";
10 import { Tool, ToolListParams } from "../types/tool.types";
11 +import logger from "../utils/logger";
12
13 export type OpenAiTool = OpenAI.ChatCompletionTool;
14 export type OpenAiToolCollection = Array<OpenAiTool>;
@@ -44,10 +45,10 @@ export class OpenAIToolset extends BaseComposioToolset<OpenAiToolCollection, Ope
45 }
46
47 /**
47 - * @TODO include the connectedAccountId / app name in the tool call
48 - * @param tool
49 - * @param userId
50 - * @returns
48 + * Execute a tool call.
49 + * @param {OpenAI.ChatCompletionMessageToolCall} tool - The tool to execute.
50 + * @param {string} userId - The user id.
51 + * @returns {Promise<string>} The result of the tool call.
52 */
53 async executeToolCall(
54 tool: OpenAI.ChatCompletionMessageToolCall,
@@ -108,15 +109,17 @@ export class OpenAIToolset extends BaseComposioToolset<OpenAiToolCollection, Ope
109 const tool_outputs: Array<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput> =
110 await Promise.all(
111 tool_calls.map(async (tool_call) => {
111 - // @TOOD: Log the tool call
112 +
113 + logger.debug(`Executing tool call: ${tool_call.id}`);
114
115 // Execute each tool call and get the response
116 const tool_response = await this.executeToolCall(
117 tool_call as OpenAI.ChatCompletionMessageToolCall,
118 userId
119 );
120 +
121
119 - // @TODO: Log the tool response
122 + logger.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
123
124 return {
125 tool_call_id: tool_call.id,
packages/toolsets/openai/package.json
+4 -4
@@ -24,12 +24,12 @@
24 "author": "",
25 "license": "ISC",
26 "packageManager": "pnpm@10.8.0",
27 - "dependencies": {
28 - "@composio/core": "workspace:*",
29 - "openai": "^4.94.0"
30 - },
27 "devDependencies": {
28 "tsup": "^8.4.0",
29 "typescript": "^5.8.3"
30 + },
31 + "dependencies": {
32 + "@composio/core": "workspace:^",
33 + "ai": "^4.3.8"
34 }
35 }
packages/toolsets/openai/src/index.ts
+1 -254
@@ -1,254 +1 @@
1 -import { BaseComposioToolset } from "@composio/core";
2 -import type { Tool, ToolListParams } from "@composio/core";
3 -import { OpenAI } from "openai";
4 -import { Stream } from "openai/streaming";
5 -
6 -export type OpenAiTool = OpenAI.ChatCompletionTool;
7 -export type OpenAiToolCollection = Array<OpenAiTool>;
8 -export class OpenAIToolset extends BaseComposioToolset<OpenAiToolCollection, OpenAiTool> {
9 - static readonly FRAMEWORK_NAME = "openai";
10 - readonly FILE_NAME = "toolsets/openai/src/index.ts";
11 -
12 - /**
13 - * Absract method to wrap a tool in the toolset.
14 - * This method is implemented by the toolset.
15 - * @param tool - The tool to wrap.
16 - * @returns The wrapped tool.
17 - */
18 - _wrapTool = (tool: Tool): OpenAiTool => {
19 - const formattedSchema: OpenAI.FunctionDefinition = {
20 - name: tool.slug!,
21 - description: tool.description!,
22 - parameters: tool.input_parameters!,
23 - };
24 - return {
25 - type: "function",
26 - function: formattedSchema,
27 - };
28 - };
29 -
30 - /**
31 - * Get all the tools from the Composio in OpenAI format.
32 - * @param params - The parameters for the tool list.
33 - * @returns The tools.
34 - */
35 - async getTools(params?: ToolListParams): Promise<OpenAiToolCollection> {
36 - const tools = await this.client?.tools.list(params);
37 - return tools?.items.map((tool) => this._wrapTool(tool as Tool)) ?? [];
38 - }
39 -
40 - /**
41 - * @TODO include the connectedAccountId / app name in the tool call
42 - * @param tool
43 - * @param userId
44 - * @returns
45 - */
46 - async executeToolCall(
47 - tool: OpenAI.ChatCompletionMessageToolCall,
48 - userId?: string
49 - ): Promise<string> {
50 -
51 - if (!this.client) {
52 - throw new Error("Client not set");
53 - }
54 -
55 - /**
56 - * @TODO: This is redundant, we should be able to get the tool name from the tool call
57 - */
58 - const toolSchema = await this.client.tools.get(tool.function.name);
59 - const appName = toolSchema?.toolkit?.name.toLowerCase();
60 - const connectedAccountId = this.client.getConnectedAccountId(appName);
61 -
62 - const payload = {
63 - entity_id: userId ?? this.client.userId,
64 - connected_account_id: connectedAccountId,
65 - arguments: JSON.parse(tool.function.arguments),
66 - }
67 -
68 - const results = await this.client.tools.execute(toolSchema.slug, payload);
69 -
70 - return JSON.stringify(results);
71 - }
72 -
73 - /**
74 - * Handle the tool call from the assistant.
75 - *
76 - * @param {OpenAI.ChatCompletion} chatCompletion - The chat completion object.
77 - * @param {string} userId - The user id.
78 - * @returns {Promise<string[]>} The results of the tool call.
79 - */
80 - async handleToolCall (chatCompletion: OpenAI.ChatCompletion, userId?: string) {
81 - const outputs: string[] = [];
82 - for (const message of chatCompletion.choices) {
83 - if (message.message.tool_calls) {
84 - outputs.push(
85 - await this.executeToolCall(message.message.tool_calls[0], userId)
86 - );
87 - }
88 - }
89 - return outputs;
90 - };
91 -
92 - /**
93 - * Handles all the tool calls from the assistant.
94 - *
95 - * @param {OpenAI.Beta.Threads.Run} run - The run object.
96 - * @param {string} userId - The user id.
97 - * @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} The tool outputs.
98 - */
99 - async handleAssistantMessage(run: OpenAI.Beta.Threads.Run, userId?: string) {
100 - const tool_calls =
101 - run.required_action?.submit_tool_outputs?.tool_calls || [];
102 - const tool_outputs: Array<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput> =
103 - await Promise.all(
104 - tool_calls.map(async (tool_call) => {
105 - // @TOOD: Log the tool call
106 -
107 - // Execute each tool call and get the response
108 - const tool_response = await this.executeToolCall(
109 - tool_call as OpenAI.ChatCompletionMessageToolCall,
110 - userId
111 - );
112 -
113 - // @TODO: Log the tool response
114 -
115 - return {
116 - tool_call_id: tool_call.id,
117 - output: JSON.stringify(tool_response),
118 - };
119 - })
120 - );
121 - return tool_outputs;
122 - }
123 -
124 - /**
125 - * Waits for the assistant stream and handles the tool calls.
126 - *
127 - * @param {OpenAI} client - The OpenAI client.
128 - * @param {Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>} runStream - The run stream.
129 - * @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
130 - * @param {string} userId - The user id.
131 - * @returns {AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>} The run stream.
132 - */
133 - async *waitAndHandleAssistantStreamToolCalls( client: OpenAI,
134 - runStream: Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>,
135 - thread: OpenAI.Beta.Threads.Thread,
136 - userId?: string) {
137 -
138 - // @TODO: Log the run stream
139 - const defaultUserId = this.client?.userId;
140 - let runId = null;
141 -
142 - // Start processing the runStream events
143 - for await (const event of runStream) {
144 - yield event; // Yield each event from the stream as it arrives
145 -
146 - if (event.event === "thread.run.created") {
147 - const { id } = event.data;
148 - runId = id;
149 - }
150 -
151 - if (!runId) {
152 - continue;
153 - }
154 -
155 - // Handle the 'requires_action' event
156 - if (event.event === "thread.run.requires_action") {
157 - const toolOutputs = await this.handleAssistantMessage(
158 - event.data,
159 - userId ?? defaultUserId
160 - );
161 -
162 - // Submit the tool outputs
163 - await client.beta.threads.runs.submitToolOutputs(thread.id, runId, {
164 - tool_outputs: toolOutputs,
165 - });
166 - }
167 -
168 - // Break if the run status becomes inactive
169 - if (
170 - [
171 - "thread.run.completed",
172 - "thread.run.failed",
173 - "thread.run.cancelled",
174 - "thread.run.expired",
175 - ].includes(event.event)
176 - ) {
177 - break;
178 - }
179 - }
180 -
181 - if (!runId) {
182 - throw new Error("No run ID found");
183 - }
184 -
185 - // Handle any final actions after the stream ends
186 - let finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
187 -
188 - while (
189 - ["queued", "in_progress", "requires_action"].includes(finalRun.status)
190 - ) {
191 - if (finalRun.status === "requires_action") {
192 - const toolOutputs = await this.handleAssistantMessage(
193 - finalRun,
194 - userId ?? defaultUserId
195 - );
196 -
197 - // Submit tool outputs
198 - finalRun = await client.beta.threads.runs.submitToolOutputs(
199 - thread.id,
200 - runId,
201 - {
202 - tool_outputs: toolOutputs,
203 - }
204 - );
205 - } else {
206 - // Update the run status
207 - finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);
208 - await new Promise((resolve) => setTimeout(resolve, 500)); // Wait before rechecking
209 - }
210 - }
211 -
212 - }
213 -
214 - /**
215 - * Waits for the assistant tool calls and handles them.
216 - *
217 - * @param {OpenAI} client - The OpenAI client.
218 - * @param {OpenAI.Beta.Threads.Run} run - The run object.
219 - * @param {OpenAI.Beta.Threads.Thread} thread - The thread object.
220 - * @param {string} userId - The user id.
221 - * @returns {Promise<OpenAI.Beta.Threads.Run>} The run object.
222 - */
223 - async waitAndHandleAssistantToolCalls(
224 - client: OpenAI,
225 - run: OpenAI.Beta.Threads.Run,
226 - thread: OpenAI.Beta.Threads.Thread,
227 - userId?: string
228 - ) {
229 - const defaultUserId = this.client?.userId;
230 - while (["queued", "in_progress", "requires_action"].includes(run.status)) {
231 - // logger.debug(`Current run status: ${run.status}`);
232 - const tool_outputs = await this.handleAssistantMessage(
233 - run,
234 - userId ?? defaultUserId
235 - );
236 - if (run.status === "requires_action") {
237 - // logger.debug(
238 - // `Submitting tool outputs for run ID: ${run.id} in thread ID: ${thread.id}`
239 - // );
240 - run = await client.beta.threads.runs.submitToolOutputs(
241 - thread.id,
242 - run.id,
243 - {
244 - tool_outputs: tool_outputs,
245 - }
246 - );
247 - } else {
248 - run = await client.beta.threads.runs.retrieve(thread.id, run.id);
249 - await new Promise((resolve) => setTimeout(resolve, 500));
250 - }
251 - }
252 - return run;
253 - }
254 -}
\ No newline at end of file
1 +export { OpenAIToolset } from "@composio/core";
\ No newline at end of file
pnpm-lock.yaml
+4 -29
@@ -14,15 +14,9 @@ importers:
14
15 examples/openai:
16 dependencies:
17 - '@composio/client':
18 - specifier: 0.1.0-alpha.7
19 - version: 0.1.0-alpha.7
17 '@composio/core':
18 specifier: workspace:*
19 version: link:../../packages/core
23 - '@composio/openai-toolset':
24 - specifier: workspace:*
25 - version: link:../../packages/toolsets/openai
20 openai:
21 specifier: ^4.94.0
22 version: 4.94.0(zod@3.24.2)
@@ -34,25 +28,6 @@ importers:
28 specifier: ^5.8.3
29 version: 5.8.3
30
37 - packages/base:
38 - dependencies:
39 - '@composio/client':
40 - specifier: 0.1.0-alpha.7
41 - version: 0.1.0-alpha.7
42 - zod:
43 - specifier: ^3.24.2
44 - version: 3.24.2
45 - devDependencies:
46 - tsup:
47 - specifier: ^8.4.0
48 - version: 8.4.0(tsx@4.19.3)(typescript@5.8.3)
49 - tsx:
50 - specifier: ^4.19.3
51 - version: 4.19.3
52 - typescript:
53 - specifier: ^5.8.3
54 - version: 5.8.3
55 -
31 packages/core:
32 dependencies:
33 '@composio/client':
@@ -113,11 +88,11 @@ importers:
88 packages/toolsets/openai:
89 dependencies:
90 '@composio/core':
116 - specifier: workspace:*
91 + specifier: workspace:^
92 version: link:../../core
118 - openai:
119 - specifier: ^4.94.0
120 - version: 4.94.0(zod@3.24.2)
93 + ai:
94 + specifier: ^4.3.8
95 + version: 4.3.8(react@19.1.0)(zod@3.24.2)
96 devDependencies:
97 tsup:
98 specifier: ^8.4.0