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.

add openai toolset

haxzie78344e5af642
diff --git a/packages/core/src/composio.ts b/packages/core/src/composio.ts
index e2209c758..897135d7b 100644
--- a/packages/core/src/composio.ts
+++ b/packages/core/src/composio.ts
@@ -10,13 +10,15 @@ import { ConnectedAccounts } from "./models/ConnectedAccounts";
import { ToolListParams } from "@composio/client/resources/tools";
import { BaseComposioToolset } from "./toolset/BaseToolset";
+
export type ComposioConfig<TTool, T extends BaseComposioToolset<TTool>> = {
apiKey?: string;
baseURL?: string;
- runtime?: string;
allowTracking?: boolean;
allowTracing?: boolean;
toolset?: T;
+ userId?: string;
+ connectedAccountIds?: Record<string, string>;
};
/**
@@ -24,14 +26,28 @@ export type ComposioConfig<TTool, T extends BaseComposioToolset<TTool>> = {
* It is used to initialize the Composio SDK and provide a global configuration.
*/
export class Composio<TTool, T extends BaseComposioToolset<TTool>> {
+
+ private readonly DEFAULT_USER_ID = "default";
+ private static readonly FILE_NAME = "core/composio.ts";
+
/**
* The Composio API client.
* @type {ComposioClient}
*/
private client: ComposioClient;
+ /**
+ * The configuration for the Composio SDK.
+ * @type {ComposioConfig<TTool, T>}
+ */
private config: ComposioConfig<TTool, T>;
+ /**
+ * Context variables for the Composio SDK.
+ */
+ userId?: string;
+ connectedAccountIds?: Record<string, string>;
+
/**
* Core models for Composio.
*/
@@ -67,6 +83,12 @@ export class Composio<TTool, T extends BaseComposioToolset<TTool>> {
*/
this.config = config;
+ /**
+ * Set the context variables for the Composio SDK.
+ */
+ this.userId = config.userId?? this.DEFAULT_USER_ID; // entity id of the user
+ this.connectedAccountIds = config.connectedAccountIds?? {}; // app name -> account id of the connected account
+
/**
* Set the default toolset, if not provided by the user.
*/
@@ -83,6 +105,15 @@ export class Composio<TTool, T extends BaseComposioToolset<TTool>> {
this.connectedAccounts = new ConnectedAccounts(this.client);
}
+ /**
+ * Get the connected account id for the given app name.
+ * @param appName - The name of the app.
+ * @returns {string | undefined} The connected account id for the given app name.
+ */
+ getConnectedAccountId(appName: string): string | undefined {
+ return this.connectedAccountIds?.[appName];
+ }
+
/**
* Get the Composio SDK client.
* @returns {ComposioClient} The Composio API client.
diff --git a/packages/toolsets/openai/src/index.ts b/packages/toolsets/openai/src/index.ts
index 4727ae238..782ced256 100644
--- a/packages/toolsets/openai/src/index.ts
+++ b/packages/toolsets/openai/src/index.ts
@@ -1,12 +1,18 @@
import { BaseComposioToolset, Composio, Toolset } from "@composio/core";
import { Tool } from "@composio/core";
import { OpenAI } from "openai";
+import { Stream } from "openai/streaming";
export class OpenAIToolset extends BaseComposioToolset<OpenAI.ChatCompletionTool> {
static readonly FRAMEWORK_NAME = "openai";
- static readonly DEFAULT_USER_ID = "default";
private static 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): OpenAI.ChatCompletionTool => {
const formattedSchema: OpenAI.FunctionDefinition = {
name: tool.name!,
@@ -19,6 +25,31 @@ export class OpenAIToolset extends BaseComposioToolset<OpenAI.ChatCompletionTool
};
};
+ /**
+ * Get all the tools from the client.
+ * @returns {Promise<OpenAI.ChatCompletionTool[]>} The tools.
+ */
+ async getTools (): Promise<OpenAI.ChatCompletionTool[]> {
+ if (!this.client) {
+ throw new Error("Client not set");
+ }
+ const tools = await this.client.tools.list();
+ return tools.items.map((tool) => this._wrapTool(tool as Tool));
+ }
+
+ /**
+ * Get a tool from the client.
+ * @param id - The id of the tool.
+ * @returns {Promise<OpenAI.ChatCompletionTool>} The tool.
+ */
+ async getTool (id: string): Promise<OpenAI.ChatCompletionTool> {
+ if (!this.client) {
+ throw new Error("Client not set");
+ }
+ const tool = await this.client.tools.get(id);
+ return this._wrapTool(tool as Tool);
+ }
+
/**
* @TODO include the connectedAccountId / app name in the tool call
* @param tool
@@ -35,20 +66,24 @@ export class OpenAIToolset extends BaseComposioToolset<OpenAI.ChatCompletionTool
}
const toolSchema = await this.client.tools.get(tool.function.name);
+ const appName = toolSchema?.name.toLowerCase();
const results = await this.client.tools.execute(toolSchema.name, {
arguments: JSON.parse(tool.function.arguments),
- entity_id: userId,
+ entity_id: userId ?? this.client.userId,
+ connected_account_id: this.client.getConnectedAccountId(appName)
});
return JSON.stringify(results);
}
/**
+ * Handle the tool call from the assistant.
*
- * @param tool
- * @returns
+ * @param {OpenAI.ChatCompletion} chatCompletion - The chat completion object.
+ * @param {string} userId - The user id.
+ * @returns {Promise<string[]>} The results of the tool call.
*/
- handleToolCall = async (chatCompletion: OpenAI.ChatCompletion, userId?: string) => {
+ async handleToolCall (chatCompletion: OpenAI.ChatCompletion, userId?: string) {
const outputs: string[] = [];
for (const message of chatCompletion.choices) {
if (message.message.tool_calls) {
@@ -60,16 +95,166 @@ export class OpenAIToolset extends BaseComposioToolset<OpenAI.ChatCompletionTool
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
- handleAssistantMessage(run: OpenAI.Beta.Threads.Run, userId?: string) {
- const threadId = run.thread_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
+
+ return {
+ tool_call_id: tool_call.id,
+ output: JSON.stringify(tool_response),
+ };
+ })
+ );
+ return tool_outputs;
}
- async *waitAndHandleAssistantStreamToolCalls() {
+ /**
+ * 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
- async waitAndHandleAssistantToolCalls() {
+ 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