Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Fix openai toolset

haxzie3a3bf6b8d125
diff --git a/examples/openai/package.json b/examples/openai/package.json
index 954be98b4..5be7723a5 100644
--- a/examples/openai/package.json
+++ b/examples/openai/package.json
@@ -12,9 +12,7 @@
"license": "ISC",
"packageManager": "[email protected]",
"dependencies": {
- "@composio/client": "0.1.0-alpha.7",
"@composio/core": "workspace:*",
- "@composio/openai-toolset": "workspace:*",
"openai": "^4.94.0"
},
"devDependencies": {
diff --git a/examples/openai/src/index.ts b/examples/openai/src/index.ts
index e701ce9ea..de0fe2b0a 100644
--- a/examples/openai/src/index.ts
+++ b/examples/openai/src/index.ts
@@ -1,15 +1,14 @@
import { Composio } from "@composio/core";
-import { OpenAIToolset } from "@composio/openai-toolset";
import { OpenAI } from "openai";
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
-// Initialize Composio with OpenAI Toolset
+// Initialize Composio
+// OpenAI Toolset is automatically installed and initialized
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
- toolset: new OpenAIToolset(),
});
// Fetch all the tools from the Composio API
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 5f984a8d6..bd6c52632 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -12,6 +12,9 @@ import { jsonSchemaToModel } from "./utils/jsonSchema";
import type { InstrumentedInstance } from "./types/telemetry.types";
import { BaseTelemetryTransport } from "./telemetry/TelemetryTransport";
+// toolsets exports
+import { OpenAIToolset } from "./toolset/OpenAIToolset";
+
export {
Composio,
ComposioToolset,
@@ -22,5 +25,6 @@ export {
Toolset,
jsonSchemaToModel,
InstrumentedInstance,
- BaseTelemetryTransport
+ BaseTelemetryTransport ,
+ OpenAIToolset
};
diff --git a/packages/core/src/telemetry/Telemetry.ts b/packages/core/src/telemetry/Telemetry.ts
index 4577b08bd..547333ab3 100644
--- a/packages/core/src/telemetry/Telemetry.ts
+++ b/packages/core/src/telemetry/Telemetry.ts
@@ -87,10 +87,7 @@ export class Telemetry<U extends InstrumentedInstance> {
this.batchProcessor.pushItem(telemetryPayload);
-
- // @TODO: Add a try catch here to create global error handler
try {
-
return await originalMethod.apply(instance, args);
} catch (error) {
const telemetryPayload: TelemetryPayload = {
diff --git a/packages/core/src/toolset/OpenAIToolset.ts b/packages/core/src/toolset/OpenAIToolset.ts
index 2722fed85..00a5a67ac 100644
--- a/packages/core/src/toolset/OpenAIToolset.ts
+++ b/packages/core/src/toolset/OpenAIToolset.ts
@@ -8,6 +8,7 @@ import { OpenAI } from "openai";
import { Stream } from "openai/streaming";
import { BaseComposioToolset } from "./BaseToolset";
import { Tool, ToolListParams } from "../types/tool.types";
+import logger from "../utils/logger";
export type OpenAiTool = OpenAI.ChatCompletionTool;
export type OpenAiToolCollection = Array<OpenAiTool>;
@@ -44,10 +45,10 @@ export class OpenAIToolset extends BaseComposioToolset<OpenAiToolCollection, Ope
}
/**
- * @TODO include the connectedAccountId / app name in the tool call
- * @param tool
- * @param userId
- * @returns
+ * Execute a tool call.
+ * @param {OpenAI.ChatCompletionMessageToolCall} tool - The tool to execute.
+ * @param {string} userId - The user id.
+ * @returns {Promise<string>} The result of the tool call.
*/
async executeToolCall(
tool: OpenAI.ChatCompletionMessageToolCall,
@@ -108,15 +109,17 @@ export class OpenAIToolset extends BaseComposioToolset<OpenAiToolCollection, Ope
const tool_outputs: Array<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput> =
await Promise.all(
tool_calls.map(async (tool_call) => {
- // @TOOD: Log the tool call
+
+ logger.debug(`Executing tool call: ${tool_call.id}`);
// 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
+ logger.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
return {
tool_call_id: tool_call.id,
diff --git a/packages/toolsets/openai/package.json b/packages/toolsets/openai/package.json
index 1262a5d36..520d83235 100644
--- a/packages/toolsets/openai/package.json
+++ b/packages/toolsets/openai/package.json
@@ -24,12 +24,12 @@
"author": "",
"license": "ISC",
"packageManager": "[email protected]",
- "dependencies": {
- "@composio/core": "workspace:*",
- "openai": "^4.94.0"
- },
"devDependencies": {
"tsup": "^8.4.0",
"typescript": "^5.8.3"
+ },
+ "dependencies": {
+ "@composio/core": "workspace:^",
+ "ai": "^4.3.8"
}
}
diff --git a/packages/toolsets/openai/src/index.ts b/packages/toolsets/openai/src/index.ts
index 5cf551343..7ff8bb848 100644
--- a/packages/toolsets/openai/src/index.ts
+++ b/packages/toolsets/openai/src/index.ts
@@ -1,254 +1 @@
-import { BaseComposioToolset } from "@composio/core";
-import type { Tool, ToolListParams } from "@composio/core";
-import { OpenAI } from "openai";
-import { Stream } from "openai/streaming";
-
-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 file
+export { OpenAIToolset } from "@composio/core";
\ No newline at end of file
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index cd2518eee..e8b866de7 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -14,15 +14,9 @@ importers:
examples/openai:
dependencies:
- '@composio/client':
- specifier: 0.1.0-alpha.7
- version: 0.1.0-alpha.7
'@composio/core':
specifier: workspace:*
version: link:../../packages/core
- '@composio/openai-toolset':
- specifier: workspace:*
- version: link:../../packages/toolsets/openai
openai:
specifier: ^4.94.0
version: 4.94.0([email protected])
@@ -34,25 +28,6 @@ importers:
specifier: ^5.8.3
version: 5.8.3
- packages/base:
- dependencies:
- '@composio/client':
- specifier: 0.1.0-alpha.7
- version: 0.1.0-alpha.7
- zod:
- specifier: ^3.24.2
- version: 3.24.2
- devDependencies:
- tsup:
- specifier: ^8.4.0
- tsx:
- specifier: ^4.19.3
- version: 4.19.3
- typescript:
- specifier: ^5.8.3
- version: 5.8.3
-
packages/core:
dependencies:
'@composio/client':
@@ -113,11 +88,11 @@ importers:
packages/toolsets/openai:
dependencies:
'@composio/core':
- specifier: workspace:*
+ specifier: workspace:^
version: link:../../core
- openai:
- specifier: ^4.94.0
- version: 4.94.0([email protected])
+ ai:
+ specifier: ^4.3.8
devDependencies:
tsup:
specifier: ^8.4.0