Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | /** |
| 2 | * OpenAI ToolSet |
| 3 | * |
| 4 | * Author: Musthaq Ahamad <musthaq@composio.dev> |
| 5 | * Legacy Reference: https://github.com/ComposioHQ/composio/blob/master/js/src/toolsets/openai.ts |
| 6 | * |
| 7 | * This is a default provider for Composio SDK. |
| 8 | * This will be shipped with the SDK and users don't need to install it separately. |
| 9 | */ |
| 10 | import { OpenAI } from 'openai'; |
| 11 | import { BaseNonAgenticProvider } from './BaseProvider'; |
| 12 | import { Tool } from '../types/tool.types'; |
| 13 | import { ExecuteToolModifiers } from '../types/modifiers.types'; |
| 14 | import { |
| 15 | ExecuteToolFnOptions, |
| 16 | ToolCallExecutionTarget, |
| 17 | ToolCallSession, |
| 18 | } from '../types/provider.types'; |
| 19 | import { McpUrlResponse, McpServerGetResponse } from '../types/mcp.types'; |
| 20 | import { normalizeToolArguments } from '../utils/toolArguments'; |
| 21 | import { deduplicateJsonSchemaRequiredArrays } from '../utils/jsonSchema'; |
| 22 | |
| 23 | export type OpenAiTool = OpenAI.ChatCompletionTool; |
| 24 | export type OpenAiToolCollection = Array<OpenAiTool>; |
| 25 | |
| 26 | export class OpenAIProvider extends BaseNonAgenticProvider< |
| 27 | OpenAiToolCollection, |
| 28 | OpenAiTool, |
| 29 | McpServerGetResponse |
| 30 | > { |
| 31 | readonly name = 'openai'; |
| 32 | |
| 33 | /** |
| 34 | * Creates a new instance of the OpenAIProvider. |
| 35 | * |
| 36 | * This is the default provider for the Composio SDK and is automatically |
| 37 | * available without additional installation. |
| 38 | * |
| 39 | * @example |
| 40 | * ```typescript |
| 41 | * // The OpenAIProvider is used by default when initializing Composio |
| 42 | * const composio = new Composio({ |
| 43 | * apiKey: 'your-api-key' |
| 44 | * }); |
| 45 | * |
| 46 | * // You can also explicitly specify it |
| 47 | * const composio = new Composio({ |
| 48 | * apiKey: 'your-api-key', |
| 49 | * provider: new OpenAIProvider() |
| 50 | * }); |
| 51 | * ``` |
| 52 | */ |
| 53 | constructor() { |
| 54 | super(); |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Transform MCP URL response into OpenAI-specific format. |
| 59 | * OpenAI uses the standard format by default. |
| 60 | * |
| 61 | * @param data - The MCP URL response data |
| 62 | * @returns Standard MCP server response format |
| 63 | */ |
| 64 | override wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse { |
| 65 | return data.map(item => ({ |
| 66 | url: new URL(item.url), |
| 67 | name: item.name, |
| 68 | })); |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * Wraps a Composio tool in the OpenAI function calling format. |
| 73 | * |
| 74 | * This method transforms a Composio tool definition into the format |
| 75 | * expected by OpenAI's function calling API. |
| 76 | * |
| 77 | * @param tool - The Composio tool to wrap |
| 78 | * @returns The wrapped tool in OpenAI format |
| 79 | * |
| 80 | * @example |
| 81 | * ```typescript |
| 82 | * // Wrap a single tool for use with OpenAI |
| 83 | * const composioTool = { |
| 84 | * slug: 'SEARCH_TOOL', |
| 85 | * description: 'Search for information', |
| 86 | * inputParameters: { |
| 87 | * type: 'object', |
| 88 | * properties: { |
| 89 | * query: { type: 'string' } |
| 90 | * }, |
| 91 | * required: ['query'] |
| 92 | * } |
| 93 | * }; |
| 94 | * |
| 95 | * const openAITool = provider.wrapTool(composioTool); |
| 96 | * ``` |
| 97 | */ |
| 98 | override wrapTool = (tool: Tool): OpenAiTool => { |
| 99 | const formattedSchema: OpenAI.FunctionDefinition = { |
| 100 | name: tool.slug, |
| 101 | description: tool.description, |
| 102 | parameters: deduplicateJsonSchemaRequiredArrays(tool.inputParameters), |
| 103 | }; |
| 104 | return { |
| 105 | type: 'function', |
| 106 | function: formattedSchema, |
| 107 | }; |
| 108 | }; |
| 109 | |
| 110 | /** |
| 111 | * Wraps multiple Composio tools in the OpenAI function calling format. |
| 112 | * |
| 113 | * This method transforms a list of Composio tools into the format |
| 114 | * expected by OpenAI's function calling API. |
| 115 | * |
| 116 | * @param tools - Array of Composio tools to wrap |
| 117 | * @returns Array of wrapped tools in OpenAI format |
| 118 | * |
| 119 | * @example |
| 120 | * ```typescript |
| 121 | * // Wrap multiple tools for use with OpenAI |
| 122 | * const composioTools = [ |
| 123 | * { |
| 124 | * slug: 'SEARCH_TOOL', |
| 125 | * description: 'Search for information', |
| 126 | * inputParameters: { |
| 127 | * type: 'object', |
| 128 | * properties: { |
| 129 | * query: { type: 'string' } |
| 130 | * } |
| 131 | * } |
| 132 | * }, |
| 133 | * { |
| 134 | * slug: 'WEATHER_TOOL', |
| 135 | * description: 'Get weather information', |
| 136 | * inputParameters: { |
| 137 | * type: 'object', |
| 138 | * properties: { |
| 139 | * location: { type: 'string' } |
| 140 | * } |
| 141 | * } |
| 142 | * } |
| 143 | * ]; |
| 144 | * |
| 145 | * const openAITools = provider.wrapTools(composioTools); |
| 146 | * ``` |
| 147 | */ |
| 148 | override wrapTools = (tools: Tool[]): OpenAiToolCollection => { |
| 149 | return tools.map(tool => this.wrapTool(tool)); |
| 150 | }; |
| 151 | |
| 152 | /** |
| 153 | * Executes a tool call from OpenAI's chat completion. |
| 154 | * |
| 155 | * This method processes a tool call from OpenAI's chat completion API, |
| 156 | * executes the corresponding Composio tool, and returns the result. |
| 157 | * |
| 158 | * @param {string | ToolCallSession} executionTarget - A user ID for direct tools or the session that produced session tools |
| 159 | * @param {OpenAI.ChatCompletionMessageToolCall} tool - The tool call from OpenAI |
| 160 | * @param {ExecuteToolFnOptions} [options] - Optional execution options |
| 161 | * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers |
| 162 | * @returns {Promise<string>} The result of the tool call as a JSON string |
| 163 | * |
| 164 | * @example |
| 165 | * ```typescript |
| 166 | * // Execute a tool call from OpenAI |
| 167 | * const toolCall = { |
| 168 | * id: 'call_abc123', |
| 169 | * type: 'function', |
| 170 | * function: { |
| 171 | * name: 'SEARCH_TOOL', |
| 172 | * arguments: '{"query":"composio documentation"}' |
| 173 | * } |
| 174 | * }; |
| 175 | * |
| 176 | * const result = await provider.executeToolCall( |
| 177 | * 'user123', |
| 178 | * toolCall, |
| 179 | * { connectedAccountId: 'conn_xyz456' } |
| 180 | * ); |
| 181 | * console.log(JSON.parse(result)); |
| 182 | * ``` |
| 183 | */ |
| 184 | async executeToolCall( |
| 185 | session: ToolCallSession, |
| 186 | tool: OpenAI.ChatCompletionMessageFunctionToolCall |
| 187 | ): Promise<string>; |
| 188 | async executeToolCall( |
| 189 | userId: string, |
| 190 | tool: OpenAI.ChatCompletionMessageFunctionToolCall, |
| 191 | options?: ExecuteToolFnOptions, |
| 192 | modifiers?: ExecuteToolModifiers |
| 193 | ): Promise<string>; |
| 194 | async executeToolCall( |
| 195 | executionTarget: ToolCallExecutionTarget, |
| 196 | tool: OpenAI.ChatCompletionMessageFunctionToolCall, |
| 197 | options?: ExecuteToolFnOptions, |
| 198 | modifiers?: ExecuteToolModifiers |
| 199 | ): Promise<string> { |
| 200 | // OpenAI always serializes tool arguments as a JSON string; normalize tolerates |
| 201 | // empty / object-shaped payloads too (issue #2406). |
| 202 | const arguments_ = normalizeToolArguments(tool.function.arguments, tool.function.name); |
| 203 | const result = await this.executeToolForTarget( |
| 204 | executionTarget, |
| 205 | tool.function.name, |
| 206 | arguments_, |
| 207 | options, |
| 208 | modifiers |
| 209 | ); |
| 210 | return JSON.stringify(result); |
| 211 | } |
| 212 | |
| 213 | /** |
| 214 | * Handles tool calls from OpenAI's chat completion response. |
| 215 | * |
| 216 | * This method processes tool calls from an OpenAI chat completion response, |
| 217 | * executes each tool call, and returns the results. |
| 218 | * |
| 219 | * @param {string | ToolCallSession} executionTarget - A user ID for direct tools or the session that produced session tools |
| 220 | * @param {OpenAI.ChatCompletion} chatCompletion - The chat completion response from OpenAI |
| 221 | * @param {ExecuteToolFnOptions} [options] - Optional execution options |
| 222 | * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers |
| 223 | * @returns {Promise<string[]>} Array of tool execution results as JSON strings |
| 224 | * |
| 225 | * @example |
| 226 | * ```typescript |
| 227 | * // Handle tool calls from a chat completion response |
| 228 | * const chatCompletion = { |
| 229 | * choices: [ |
| 230 | * { |
| 231 | * message: { |
| 232 | * tool_calls: [ |
| 233 | * { |
| 234 | * id: 'call_abc123', |
| 235 | * type: 'function', |
| 236 | * function: { |
| 237 | * name: 'SEARCH_TOOL', |
| 238 | * arguments: '{"query":"composio documentation"}' |
| 239 | * } |
| 240 | * } |
| 241 | * ] |
| 242 | * } |
| 243 | * } |
| 244 | * ] |
| 245 | * }; |
| 246 | * |
| 247 | * const results = await provider.handleToolCalls( |
| 248 | * 'user123', |
| 249 | * chatCompletion, |
| 250 | * { connectedAccountId: 'conn_xyz456' } |
| 251 | * ); |
| 252 | * console.log(results); // Array of tool execution results |
| 253 | * ``` |
| 254 | */ |
| 255 | async handleToolCalls( |
| 256 | session: ToolCallSession, |
| 257 | chatCompletion: OpenAI.ChatCompletion |
| 258 | ): Promise<OpenAI.ChatCompletionToolMessageParam[]>; |
| 259 | async handleToolCalls( |
| 260 | userId: string, |
| 261 | chatCompletion: OpenAI.ChatCompletion, |
| 262 | options?: ExecuteToolFnOptions, |
| 263 | modifiers?: ExecuteToolModifiers |
| 264 | ): Promise<OpenAI.ChatCompletionToolMessageParam[]>; |
| 265 | async handleToolCalls( |
| 266 | executionTarget: ToolCallExecutionTarget, |
| 267 | chatCompletion: OpenAI.ChatCompletion, |
| 268 | options?: ExecuteToolFnOptions, |
| 269 | modifiers?: ExecuteToolModifiers |
| 270 | ): Promise<OpenAI.ChatCompletionToolMessageParam[]> { |
| 271 | this.assertToolCallExecutionOptions(executionTarget, options, modifiers); |
| 272 | const outputs: OpenAI.ChatCompletionToolMessageParam[] = []; |
| 273 | // Only the first choice is actionable: its tool results feed back into a |
| 274 | // single assistant turn. With n > 1, iterating every choice would run each |
| 275 | // tool call once per choice and orphan the tool_call_ids belonging to the |
| 276 | // alternative completions. |
| 277 | const [choice] = chatCompletion.choices; |
| 278 | // A single assistant message can carry several tool calls (parallel tool |
| 279 | // calls, on by default). Each one needs its own tool result, otherwise the |
| 280 | // next request fails since some tool_call_ids go unanswered. |
| 281 | for (const toolCall of choice?.message.tool_calls ?? []) { |
| 282 | if (toolCall.type !== 'function') { |
| 283 | continue; |
| 284 | } |
| 285 | const toolResult = |
| 286 | typeof executionTarget === 'string' |
| 287 | ? await this.executeToolCall(executionTarget, toolCall, options, modifiers) |
| 288 | : await this.executeToolCall(executionTarget, toolCall); |
| 289 | outputs.push({ |
| 290 | role: 'tool', |
| 291 | tool_call_id: toolCall.id, |
| 292 | content: toolResult, |
| 293 | }); |
| 294 | } |
| 295 | return outputs; |
| 296 | } |
| 297 | } |