Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Ship openai toolset with composio core
haxzie312e61a5c9af
diff --git a/packages/core/package.json b/packages/core/package.jsonindex 2a8da7a95..7743fcb61 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -2,7 +2,20 @@"name": "@composio/core","version": "1.0.0","description": "",- "main": "dist/index.js",+ "main": "src/index.ts",+ "type": "module",+ "publishConfig": {+ "access": "public",+ "main": "dist/index.js",+ "types": "dist/index.d.ts"+ },+ "exports": {+ ".": {+ "import": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "require": "./dist/index.cjs"+ }+ },"scripts": {"build": "tsup","test": "echo \"Error: no test specified\" && exit 1"@@ -19,6 +32,7 @@},"dependencies": {"@composio/client": "0.1.0-alpha.7",+ "openai": "^4.94.0","pusher-js": "^8.4.0","zod": "^3.24.2"}diff --git a/packages/core/src/composio.ts b/packages/core/src/composio.tsindex d7f07651d..159733183 100644--- a/packages/core/src/composio.ts+++ b/packages/core/src/composio.ts@@ -14,9 +14,10 @@ import { getSDKConfig } from "./utils/sdk";import logger from "./utils/logger";import { IS_DEVELOPMENT_OR_CI } from "./utils/constants";import { checkForLatestVersionFromNPM } from "./utils/version";+import { OpenAIToolset } from "./toolset/OpenAIToolset";-export type ComposioConfig<TToolset extends BaseComposioToolset<any, any>> = {+export type ComposioConfig<TToolset extends BaseComposioToolset<any, any> = OpenAIToolset> = {apiKey?: string;baseURL?: string;allowTracking?: boolean;@@ -31,7 +32,7 @@ export type ComposioConfig<TToolset extends BaseComposioToolset<any, any>> = {* This is the core class for Composio.* It is used to initialize the Composio SDK and provide a global configuration.*/-export class Composio<TToolset extends BaseComposioToolset<any, any>> {+export class Composio<TToolset extends BaseComposioToolset<any, any> = OpenAIToolset> {private readonly DEFAULT_USER_ID = "default";readonly FILE_NAME = "core/composio.ts";diff --git a/packages/core/src/toolset/BaseToolset.ts b/packages/core/src/toolset/BaseToolset.tsindex 10819f904..53963ca86 100644--- a/packages/core/src/toolset/BaseToolset.ts+++ b/packages/core/src/toolset/BaseToolset.ts@@ -1,6 +1,6 @@-import { Toolset } from "../types/toolset.types";-import { Tool, BaseTool, ToolListParams } from "../types/tool.types";-import { Composio } from "../composio";+import type { Toolset } from "../types/toolset.types";+import type { Tool, ToolListParams } from "../types/tool.types";+import type { Composio } from "../composio";/*** Base toolset implementation with proper generic defaultsdiff --git a/packages/core/src/toolset/OpenAIToolset.ts b/packages/core/src/toolset/OpenAIToolset.tsnew file mode 100644index 000000000..2722fed85--- /dev/null+++ b/packages/core/src/toolset/OpenAIToolset.ts@@ -0,0 +1,260 @@+/**+ * OpenAI ToolSet+ *+ * This is a default toolset for Composio SDK.+ * This will be shipped with the SDK and users don't need to install it separately.+ */+import { OpenAI } from "openai";+import { Stream } from "openai/streaming";+import { BaseComposioToolset } from "./BaseToolset";+import { Tool, ToolListParams } from "../types/tool.types";++export type OpenAiTool = OpenAI.ChatCompletionTool;+export type OpenAiToolCollection = Array<OpenAiTool>;+export class OpenAIToolset extends BaseComposioToolset<OpenAiToolCollection, OpenAiTool> {+ static readonly FRAMEWORK_NAME = "openai";+ readonly FILE_NAME = "toolsets/openai/src/index.ts";++ /**+ * Absract method to wrap a tool in the toolset.+ * This method is implemented by the toolset.+ * @param tool - The tool to wrap.+ * @returns The wrapped tool.+ */+ _wrapTool = (tool: Tool): OpenAiTool => {+ const formattedSchema: OpenAI.FunctionDefinition = {+ name: tool.slug!,+ description: tool.description!,+ parameters: tool.input_parameters!,+ };+ return {+ type: "function",+ function: formattedSchema,+ };+ };++ /**+ * Get all the tools from the Composio in OpenAI format.+ * @param params - The parameters for the tool list.+ * @returns The tools.+ */+ async getTools(params?: ToolListParams): Promise<OpenAiToolCollection> {+ const tools = await this.client?.tools.list(params);+ return tools?.items.map((tool) => this._wrapTool(tool as Tool)) ?? [];+ }++ /**+ * @TODO include the connectedAccountId / app name in the tool call+ * @param tool+ * @param userId+ * @returns+ */+ async executeToolCall(+ tool: OpenAI.ChatCompletionMessageToolCall,+ userId?: string+ ): Promise<string> {++ if (!this.client) {+ throw new Error("Client not set");+ }++ /**+ * @TODO: This is redundant, we should be able to get the tool name from the tool call+ */+ const toolSchema = await this.client.tools.get(tool.function.name);+ const appName = toolSchema?.toolkit?.name.toLowerCase();+ const connectedAccountId = this.client.getConnectedAccountId(appName);++ const payload = {+ entity_id: userId ?? this.client.userId,+ connected_account_id: connectedAccountId,+ arguments: JSON.parse(tool.function.arguments),+ }++ const results = await this.client.tools.execute(toolSchema.slug, payload);++ return JSON.stringify(results);+ }++ /**+ * Handle the tool call from the assistant.+ *+ * @param {OpenAI.ChatCompletion} chatCompletion - The chat completion object.+ * @param {string} userId - The user id.+ * @returns {Promise<string[]>} The results of the tool call.+ */+ async handleToolCall (chatCompletion: OpenAI.ChatCompletion, userId?: string) {+ const outputs: string[] = [];+ for (const message of chatCompletion.choices) {+ if (message.message.tool_calls) {+ outputs.push(+ await this.executeToolCall(message.message.tool_calls[0], userId)+ );+ }+ }+ return outputs;+ };++ /**+ * Handles all the tool calls from the assistant.+ *+ * @param {OpenAI.Beta.Threads.Run} run - The run object.+ * @param {string} userId - The user id.+ * @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} The tool outputs.+ */+ async handleAssistantMessage(run: OpenAI.Beta.Threads.Run, userId?: string) {+ const tool_calls =+ run.required_action?.submit_tool_outputs?.tool_calls || [];+ const tool_outputs: Array<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput> =+ await Promise.all(+ tool_calls.map(async (tool_call) => {+ // @TOOD: Log the tool call++ // Execute each tool call and get the response+ const tool_response = await this.executeToolCall(+ tool_call as OpenAI.ChatCompletionMessageToolCall,+ userId+ );++ // @TODO: Log the tool response++ return {+ tool_call_id: tool_call.id,+ output: JSON.stringify(tool_response),+ };+ })+ );+ return tool_outputs;+ }++ /**+ * Waits for the assistant stream and handles the tool calls.+ *+ * @param {OpenAI} client - The OpenAI client.+ * @param {Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>} runStream - The run stream.+ * @param {OpenAI.Beta.Threads.Thread} thread - The thread object.+ * @param {string} userId - The user id.+ * @returns {AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>} The run stream.+ */+ async *waitAndHandleAssistantStreamToolCalls( client: OpenAI,+ runStream: Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>,+ thread: OpenAI.Beta.Threads.Thread,+ userId?: string) {++ // @TODO: Log the run stream+ const defaultUserId = this.client?.userId;+ let runId = null;++ // Start processing the runStream events+ for await (const event of runStream) {+ yield event; // Yield each event from the stream as it arrives++ if (event.event === "thread.run.created") {+ const { id } = event.data;+ runId = id;+ }++ if (!runId) {+ continue;+ }++ // Handle the 'requires_action' event+ if (event.event === "thread.run.requires_action") {+ const toolOutputs = await this.handleAssistantMessage(+ event.data,+ userId ?? defaultUserId+ );++ // Submit the tool outputs+ await client.beta.threads.runs.submitToolOutputs(thread.id, runId, {+ tool_outputs: toolOutputs,+ });+ }++ // Break if the run status becomes inactive+ if (+ [+ "thread.run.completed",+ "thread.run.failed",+ "thread.run.cancelled",+ "thread.run.expired",+ ].includes(event.event)+ ) {+ break;+ }+ }++ if (!runId) {+ throw new Error("No run ID found");+ }++ // Handle any final actions after the stream ends+ let finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);++ while (+ ["queued", "in_progress", "requires_action"].includes(finalRun.status)+ ) {+ if (finalRun.status === "requires_action") {+ const toolOutputs = await this.handleAssistantMessage(+ finalRun,+ userId ?? defaultUserId+ );++ // Submit tool outputs+ finalRun = await client.beta.threads.runs.submitToolOutputs(+ thread.id,+ runId,+ {+ tool_outputs: toolOutputs,+ }+ );+ } else {+ // Update the run status+ finalRun = await client.beta.threads.runs.retrieve(thread.id, runId);+ await new Promise((resolve) => setTimeout(resolve, 500)); // Wait before rechecking+ }+ }++ }++ /**+ * Waits for the assistant tool calls and handles them.+ *+ * @param {OpenAI} client - The OpenAI client.+ * @param {OpenAI.Beta.Threads.Run} run - The run object.+ * @param {OpenAI.Beta.Threads.Thread} thread - The thread object.+ * @param {string} userId - The user id.+ * @returns {Promise<OpenAI.Beta.Threads.Run>} The run object.+ */+ async waitAndHandleAssistantToolCalls(+ client: OpenAI,+ run: OpenAI.Beta.Threads.Run,+ thread: OpenAI.Beta.Threads.Thread,+ userId?: string+ ) {+ const defaultUserId = this.client?.userId;+ while (["queued", "in_progress", "requires_action"].includes(run.status)) {+ // logger.debug(`Current run status: ${run.status}`);+ const tool_outputs = await this.handleAssistantMessage(+ run,+ userId ?? defaultUserId+ );+ if (run.status === "requires_action") {+ // logger.debug(+ // `Submitting tool outputs for run ID: ${run.id} in thread ID: ${thread.id}`+ // );+ run = await client.beta.threads.runs.submitToolOutputs(+ thread.id,+ run.id,+ {+ tool_outputs: tool_outputs,+ }+ );+ } else {+ run = await client.beta.threads.runs.retrieve(thread.id, run.id);+ await new Promise((resolve) => setTimeout(resolve, 500));+ }+ }+ return run;+ }+}\ No newline at end of filediff --git a/packages/toolsets/cloudflare/package.json b/packages/toolsets/cloudflare/package.jsonindex 1fffbf2c0..d59aaec04 100644--- a/packages/toolsets/cloudflare/package.json+++ b/packages/toolsets/cloudflare/package.json@@ -2,7 +2,20 @@"name": "@composio/cloudflare-toolset","version": "1.0.0","description": "",- "main": "index.js",+ "main": "src/index.ts",+ "type": "module",+ "publishConfig": {+ "access": "public",+ "main": "dist/index.js",+ "types": "dist/index.d.ts"+ },+ "exports": {+ ".": {+ "import": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "require": "./dist/index.cjs"+ }+ },"scripts": {"build": "tsup","test": "echo \"Error: no test specified\" && exit 1"diff --git a/packages/toolsets/langchain/package.json b/packages/toolsets/langchain/package.jsonindex cfc560d4c..0d41ce613 100644--- a/packages/toolsets/langchain/package.json+++ b/packages/toolsets/langchain/package.json@@ -2,7 +2,20 @@"name": "@composio/langchain-toolset","version": "1.0.0","description": "",- "main": "index.js",+ "main": "src/index.ts",+ "type": "module",+ "publishConfig": {+ "access": "public",+ "main": "dist/index.js",+ "types": "dist/index.d.ts"+ },+ "exports": {+ ".": {+ "import": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "require": "./dist/index.cjs"+ }+ },"scripts": {"build": "tsup","test": "echo \"Error: no test specified\" && exit 1"diff --git a/packages/toolsets/openai/package.json b/packages/toolsets/openai/package.jsonindex e6639673d..1262a5d36 100644--- a/packages/toolsets/openai/package.json+++ b/packages/toolsets/openai/package.json@@ -2,7 +2,20 @@"name": "@composio/openai-toolset","version": "1.0.0","description": "",- "main": "dist/index.js",+ "main": "src/index.ts",+ "type": "module",+ "publishConfig": {+ "access": "public",+ "main": "dist/index.js",+ "types": "dist/index.d.ts"+ },+ "exports": {+ ".": {+ "import": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "require": "./dist/index.cjs"+ }+ },"scripts": {"build": "tsup","test": "echo \"Error: no test specified\" && exit 1"diff --git a/packages/toolsets/openai/src/index.ts b/packages/toolsets/openai/src/index.tsindex 6525c640b..5cf551343 100644--- a/packages/toolsets/openai/src/index.ts+++ b/packages/toolsets/openai/src/index.ts@@ -1,24 +1,21 @@-import { BaseComposioToolset, ToolListParams } from "@composio/core";-import { Tool } from "@composio/core";+import { BaseComposioToolset } from "@composio/core";+import type { Tool, ToolListParams } from "@composio/core";import { OpenAI } from "openai";import { Stream } from "openai/streaming";-type OpenAiToolCollection = Array<OpenAI.ChatCompletionTool>;-export class OpenAIToolset extends BaseComposioToolset<OpenAiToolCollection, OpenAI.ChatCompletionTool> {+export type OpenAiTool = OpenAI.ChatCompletionTool;+export type OpenAiToolCollection = Array<OpenAiTool>;+export class OpenAIToolset extends BaseComposioToolset<OpenAiToolCollection, OpenAiTool> {static readonly FRAMEWORK_NAME = "openai";readonly FILE_NAME = "toolsets/openai/src/index.ts";- constructor() {- super();- }-/*** Absract method to wrap a tool in the toolset.* This method is implemented by the toolset.* @param tool - The tool to wrap.* @returns The wrapped tool.*/- _wrapTool = (tool: Tool): OpenAI.ChatCompletionTool => {+ _wrapTool = (tool: Tool): OpenAiTool => {const formattedSchema: OpenAI.FunctionDefinition = {name: tool.slug!,description: tool.description!,@@ -35,7 +32,7 @@ export class OpenAIToolset extends BaseComposioToolset<OpenAiToolCollection, Ope* @param params - The parameters for the tool list.* @returns The tools.*/- async getTools(params?: ToolListParams): Promise<Array<OpenAI.ChatCompletionTool>> {+ async getTools(params?: ToolListParams): Promise<OpenAiToolCollection> {const tools = await this.client?.tools.list(params);return tools?.items.map((tool) => this._wrapTool(tool as Tool)) ?? [];}diff --git a/packages/toolsets/vercel/package.json b/packages/toolsets/vercel/package.jsonindex 2caf86691..1f08e1625 100644--- a/packages/toolsets/vercel/package.json+++ b/packages/toolsets/vercel/package.json@@ -2,7 +2,20 @@"name": "@composio/vercel-toolset","version": "1.0.0","description": "",- "main": "index.js",+ "main": "src/index.ts",+ "type": "module",+ "publishConfig": {+ "access": "public",+ "main": "dist/index.js",+ "types": "dist/index.d.ts"+ },+ "exports": {+ ".": {+ "import": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "require": "./dist/index.cjs"+ }+ },"scripts": {"build": "tsup","test": "echo \"Error: no test specified\" && exit 1"diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1251d7ee5..7fa54f6c9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -36,6 +36,9 @@ importers:'@composio/client':specifier: 0.1.0-alpha.7version: 0.1.0-alpha.7+ openai:+ specifier: ^4.94.0+ version: 4.94.0([email protected])pusher-js:specifier: ^8.4.0version: 8.4.0diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 5c64f4ba2..29acc3c8d 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -1,4 +1,3 @@packages:- - 'packages/core'- - 'packages/toolsets/*'+ - 'packages/**'- 'examples/*'\ No newline at end of file