Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Ship openai toolset with composio core
haxzie committed
Apr 18, 2025 at 11:24 UTC
312e61a5c9afe8a9e5001ea912fa44e155569be5
11 files changed
+348
-22
packages/core/package.json
+15
-1
@@ -2,7 +2,20 @@
2
"name": "@composio/core",
3
"version": "1.0.0",
4
"description": "",
5
- "main": "dist/index.js",
5
+ "main": "src/index.ts",
6
+ "type": "module",
7
+ "publishConfig": {
8
+ "access": "public",
9
+ "main": "dist/index.js",
10
+ "types": "dist/index.d.ts"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "import": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "require": "./dist/index.cjs"
17
+ }
18
+ },
19
"scripts": {
20
"build": "tsup",
21
"test": "echo \"Error: no test specified\" && exit 1"
@@ -19,6 +32,7 @@
32
},
33
"dependencies": {
34
"@composio/client": "0.1.0-alpha.7",
35
+ "openai": "^4.94.0",
36
"pusher-js": "^8.4.0",
37
"zod": "^3.24.2"
38
}
packages/core/src/composio.ts
+3
-2
@@ -14,9 +14,10 @@ import { getSDKConfig } from "./utils/sdk";
14
import logger from "./utils/logger";
15
import { IS_DEVELOPMENT_OR_CI } from "./utils/constants";
16
import { checkForLatestVersionFromNPM } from "./utils/version";
17
+import { OpenAIToolset } from "./toolset/OpenAIToolset";
18
19
19
-export type ComposioConfig<TToolset extends BaseComposioToolset<any, any>> = {
20
+export type ComposioConfig<TToolset extends BaseComposioToolset<any, any> = OpenAIToolset> = {
21
apiKey?: string;
22
baseURL?: string;
23
allowTracking?: boolean;
@@ -31,7 +32,7 @@ export type ComposioConfig<TToolset extends BaseComposioToolset<any, any>> = {
32
* This is the core class for Composio.
33
* It is used to initialize the Composio SDK and provide a global configuration.
34
*/
34
-export class Composio<TToolset extends BaseComposioToolset<any, any>> {
35
+export class Composio<TToolset extends BaseComposioToolset<any, any> = OpenAIToolset> {
36
37
private readonly DEFAULT_USER_ID = "default";
38
readonly FILE_NAME = "core/composio.ts";
packages/core/src/toolset/BaseToolset.ts
+3
-3
@@ -1,6 +1,6 @@
1
-import { Toolset } from "../types/toolset.types";
2
-import { Tool, BaseTool, ToolListParams } from "../types/tool.types";
3
-import { Composio } from "../composio";
1
+import type { Toolset } from "../types/toolset.types";
2
+import type { Tool, ToolListParams } from "../types/tool.types";
3
+import type { Composio } from "../composio";
4
5
/**
6
* Base toolset implementation with proper generic defaults
packages/core/src/toolset/OpenAIToolset.ts
new
+260
@@ -0,0 +1,260 @@
1
+/**
2
+ * OpenAI ToolSet
3
+ *
4
+ * This is a default toolset for Composio SDK.
5
+ * This will be shipped with the SDK and users don't need to install it separately.
6
+ */
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
+
12
+export type OpenAiTool = OpenAI.ChatCompletionTool;
13
+export type OpenAiToolCollection = Array<OpenAiTool>;
14
+export class OpenAIToolset extends BaseComposioToolset<OpenAiToolCollection, OpenAiTool> {
15
+ static readonly FRAMEWORK_NAME = "openai";
16
+ readonly FILE_NAME = "toolsets/openai/src/index.ts";
17
+
18
+ /**
19
+ * Absract method to wrap a tool in the toolset.
20
+ * This method is implemented by the toolset.
21
+ * @param tool - The tool to wrap.
22
+ * @returns The wrapped tool.
23
+ */
24
+ _wrapTool = (tool: Tool): OpenAiTool => {
25
+ const formattedSchema: OpenAI.FunctionDefinition = {
26
+ name: tool.slug!,
27
+ description: tool.description!,
28
+ parameters: tool.input_parameters!,
29
+ };
30
+ return {
31
+ type: "function",
32
+ function: formattedSchema,
33
+ };
34
+ };
35
+
36
+ /**
37
+ * Get all the tools from the Composio in OpenAI format.
38
+ * @param params - The parameters for the tool list.
39
+ * @returns The tools.
40
+ */
41
+ async getTools(params?: ToolListParams): Promise<OpenAiToolCollection> {
42
+ const tools = await this.client?.tools.list(params);
43
+ return tools?.items.map((tool) => this._wrapTool(tool as Tool)) ?? [];
44
+ }
45
+
46
+ /**
47
+ * @TODO include the connectedAccountId / app name in the tool call
48
+ * @param tool
49
+ * @param userId
50
+ * @returns
51
+ */
52
+ async executeToolCall(
53
+ tool: OpenAI.ChatCompletionMessageToolCall,
54
+ userId?: string
55
+ ): Promise<string> {
56
+
57
+ if (!this.client) {
58
+ throw new Error("Client not set");
59
+ }
60
+
61
+ /**
62
+ * @TODO: This is redundant, we should be able to get the tool name from the tool call
63
+ */
64
+ const toolSchema = await this.client.tools.get(tool.function.name);
65
+ const appName = toolSchema?.toolkit?.name.toLowerCase();
66
+ const connectedAccountId = this.client.getConnectedAccountId(appName);
67
+
68
+ const payload = {
69
+ entity_id: userId ?? this.client.userId,
70
+ connected_account_id: connectedAccountId,
71
+ arguments: JSON.parse(tool.function.arguments),
72
+ }
73
+
74
+ const results = await this.client.tools.execute(toolSchema.slug, payload);
75
+
76
+ return JSON.stringify(results);
77
+ }
78
+
79
+ /**
80
+ * Handle the tool call from the assistant.
81
+ *
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
+ */
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) {
90
+ outputs.push(
91
+ await this.executeToolCall(message.message.tool_calls[0], userId)
92
+ );
93
+ }
94
+ }
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
+
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
+
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
+
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
+
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
packages/toolsets/cloudflare/package.json
+14
-1
@@ -2,7 +2,20 @@
2
"name": "@composio/cloudflare-toolset",
3
"version": "1.0.0",
4
"description": "",
5
- "main": "index.js",
5
+ "main": "src/index.ts",
6
+ "type": "module",
7
+ "publishConfig": {
8
+ "access": "public",
9
+ "main": "dist/index.js",
10
+ "types": "dist/index.d.ts"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "import": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "require": "./dist/index.cjs"
17
+ }
18
+ },
19
"scripts": {
20
"build": "tsup",
21
"test": "echo \"Error: no test specified\" && exit 1"
packages/toolsets/langchain/package.json
+14
-1
@@ -2,7 +2,20 @@
2
"name": "@composio/langchain-toolset",
3
"version": "1.0.0",
4
"description": "",
5
- "main": "index.js",
5
+ "main": "src/index.ts",
6
+ "type": "module",
7
+ "publishConfig": {
8
+ "access": "public",
9
+ "main": "dist/index.js",
10
+ "types": "dist/index.d.ts"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "import": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "require": "./dist/index.cjs"
17
+ }
18
+ },
19
"scripts": {
20
"build": "tsup",
21
"test": "echo \"Error: no test specified\" && exit 1"
packages/toolsets/openai/package.json
+14
-1
@@ -2,7 +2,20 @@
2
"name": "@composio/openai-toolset",
3
"version": "1.0.0",
4
"description": "",
5
- "main": "dist/index.js",
5
+ "main": "src/index.ts",
6
+ "type": "module",
7
+ "publishConfig": {
8
+ "access": "public",
9
+ "main": "dist/index.js",
10
+ "types": "dist/index.d.ts"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "import": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "require": "./dist/index.cjs"
17
+ }
18
+ },
19
"scripts": {
20
"build": "tsup",
21
"test": "echo \"Error: no test specified\" && exit 1"
packages/toolsets/openai/src/index.ts
+7
-10
@@ -1,24 +1,21 @@
1
-import { BaseComposioToolset, ToolListParams } from "@composio/core";
2
-import { Tool } from "@composio/core";
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
-type OpenAiToolCollection = Array<OpenAI.ChatCompletionTool>;
7
-export class OpenAIToolset extends BaseComposioToolset<OpenAiToolCollection, OpenAI.ChatCompletionTool> {
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
11
- constructor() {
12
- super();
13
- }
14
-
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
*/
21
- _wrapTool = (tool: Tool): OpenAI.ChatCompletionTool => {
18
+ _wrapTool = (tool: Tool): OpenAiTool => {
19
const formattedSchema: OpenAI.FunctionDefinition = {
20
name: tool.slug!,
21
description: tool.description!,
@@ -35,7 +32,7 @@ export class OpenAIToolset extends BaseComposioToolset<OpenAiToolCollection, Ope
32
* @param params - The parameters for the tool list.
33
* @returns The tools.
34
*/
38
- async getTools(params?: ToolListParams): Promise<Array<OpenAI.ChatCompletionTool>> {
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
}
packages/toolsets/vercel/package.json
+14
-1
@@ -2,7 +2,20 @@
2
"name": "@composio/vercel-toolset",
3
"version": "1.0.0",
4
"description": "",
5
- "main": "index.js",
5
+ "main": "src/index.ts",
6
+ "type": "module",
7
+ "publishConfig": {
8
+ "access": "public",
9
+ "main": "dist/index.js",
10
+ "types": "dist/index.d.ts"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "import": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "require": "./dist/index.cjs"
17
+ }
18
+ },
19
"scripts": {
20
"build": "tsup",
21
"test": "echo \"Error: no test specified\" && exit 1"
pnpm-lock.yaml
+3
@@ -36,6 +36,9 @@ importers:
36
'@composio/client':
37
specifier: 0.1.0-alpha.7
38
version: 0.1.0-alpha.7
39
+ openai:
40
+ specifier: ^4.94.0
41
+ version: 4.94.0(zod@3.24.2)
42
pusher-js:
43
specifier: ^8.4.0
44
version: 8.4.0
pnpm-workspace.yaml
+1
-2
@@ -1,4 +1,3 @@
1
packages:
2
- - 'packages/core'
3
- - 'packages/toolsets/*'
2
+ - 'packages/**'
3
- 'examples/*'
\ No newline at end of file