@devries-cameron20 / composio Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 04:45 UTC

next
ts 240 lines 7.76 KB
Raw
1 /**
2 * OpenAI Agents Provider
3 * To be used with the @openai/agents package
4 *
5 * Author: Musthaq Ahamad <musthaq@composio.dev>
6 * Reference: https://openai.github.io/openai-agents-js/
7 *
8 * This provider provides a set of tools for interacting with OpenAI's Agents API.
9 *
10 * @packageDocumentation
11 * @module providers/openai-agents
12 */
13 import {
14 BaseAgenticProvider,
15 Tool as ComposioTool,
16 ExecuteToolFn,
17 McpUrlResponse,
18 McpServerGetResponse,
19 normalizeToolArguments,
20 deduplicateJsonSchemaRequiredArrays,
21 dereferenceJsonSchema,
22 logger,
23 omitNullToolArguments,
24 toStrictJsonSchema,
25 } from '@composio/core';
26 import type { Tool as OpenAIAgentTool } from '@openai/agents';
27 import { tool as createOpenAIAgentTool } from '@openai/agents';
28
29 type OpenAIAgentsToolCollection = Array<OpenAIAgentTool>;
30
31 /** The strict JSON Schema parameter shape the Agents SDK accepts. */
32 type StrictToolParameters = Extract<
33 Parameters<typeof createOpenAIAgentTool>[0]['parameters'],
34 { additionalProperties: false }
35 >;
36
37 /** Parameters registered for a tool without input parameters under strict mode. */
38 const EMPTY_OBJECT_SCHEMA = {
39 type: 'object',
40 properties: {},
41 required: [],
42 additionalProperties: false,
43 } as const;
44 export class OpenAIAgentsProvider extends BaseAgenticProvider<
45 OpenAIAgentsToolCollection,
46 OpenAIAgentTool,
47 McpServerGetResponse
48 > {
49 readonly name = 'openai-agents';
50 private strict: boolean | null;
51
52 /**
53 * Creates a new instance of the OpenAIAgentsProvider.
54 *
55 * This provider enables integration with the @openai/agents package,
56 * allowing Composio tools to be used with OpenAI Agents.
57 *
58 * @example
59 * ```typescript
60 * // Initialize the OpenAIAgentsProvider
61 * const provider = new OpenAIAgentsProvider();
62 *
63 * // Use with Composio
64 * const composio = new Composio({
65 * apiKey: 'your-api-key',
66 * provider: new OpenAIAgentsProvider()
67 * });
68 *
69 * // Use the provider to wrap tools for @openai/agents
70 * const agentTools = provider.wrapTools(composioTools, composio.tools.execute);
71 * ```
72 */
73 constructor(options?: { strict?: boolean }) {
74 super();
75 this.strict = options?.strict ?? false;
76 }
77
78 /**
79 * Transform MCP URL response into Anthropic-specific format.
80 * By default, Anthropic uses the standard format (same as default),
81 * but this method is here to show providers can customize if needed.
82 *
83 * @param data - The MCP URL response data
84 * @returns Standard MCP server response format
85 */
86 wrapMcpServerResponse(data: McpUrlResponse): McpServerGetResponse {
87 // Anthropic uses the standard format
88 return data.map(item => ({
89 url: new URL(item.url),
90 name: item.name,
91 })) as McpServerGetResponse;
92 }
93
94 /**
95 * Wraps a Composio tool in a OpenAI Agents tool format.
96 *
97 * This method transforms a Composio tool definition into the format
98 * expected by @openai/agents for function calling.
99 *
100 * @param {ComposioTool} composioTool - The Composio tool to wrap
101 * @param {ExecuteToolFn} executeTool - Function to execute the tool
102 * @returns {OpenAIAgentsTool} The wrapped OpenAI Agents tool
103 *
104 * @example
105 * ```typescript
106 * // Wrap a single tool for use with Vercel AI SDK
107 * const composioTool = {
108 * slug: 'SEARCH_TOOL',
109 * description: 'Search for information',
110 * inputParameters: {
111 * type: 'object',
112 * properties: {
113 * query: { type: 'string' }
114 * },
115 * required: ['query']
116 * }
117 * };
118 *
119 * // Create a Vercel tool using the provider
120 * const vercelTool = provider.wrapTool(
121 * composioTool,
122 * composio.tools.execute
123 * );
124 *
125 * // Use with Vercel AI SDK
126 * import { StreamingTextResponse, Message } from 'ai';
127 * import { OpenAI } from 'openai';
128 *
129 * export async function POST(req: Request) {
130 * const { messages } = await req.json();
131 * const openai = new OpenAI();
132 *
133 * const response = await openai.chat.completions.create({
134 * model: 'gpt-4',
135 * messages,
136 * tools: [vercelTool]
137 * });
138 *
139 * return new StreamingTextResponse(response.choices[0].message);
140 * }
141 * ```
142 */
143 wrapTool(composioTool: ComposioTool, executeTool: ExecuteToolFn): OpenAIAgentTool {
144 const inputParameters = deduplicateJsonSchemaRequiredArrays(
145 dereferenceJsonSchema(composioTool.inputParameters, { onUnresolved: 'sentinel' })
146 );
147
148 // Strict mode applies OpenAI's structured-output contract at every
149 // depth: all properties required, closed objects, optional properties
150 // widened to accept null instead of being dropped. Tools whose schema
151 // strict mode cannot express are registered without strict mode.
152 const execute = async (params: unknown, strictSource?: Record<string, unknown>) => {
153 // Models occasionally emit tool input as a JSON string rather than an object (issue #2406).
154 const normalized = normalizeToolArguments(params, composioTool.slug);
155 // Under strict mode optional parameters are emitted as required-nullable,
156 // so a null the tool's own schema does not accept means "omitted".
157 return await executeTool(
158 composioTool.slug,
159 strictSource ? omitNullToolArguments(normalized, strictSource) : normalized
160 );
161 };
162
163 if (this.strict) {
164 const strict = toStrictJsonSchema(composioTool.inputParameters ?? EMPTY_OBJECT_SCHEMA);
165 if (strict.unsupported.length === 0) {
166 return createOpenAIAgentTool({
167 name: composioTool.slug,
168 description: composioTool.description ?? '',
169 parameters: strict.schema as StrictToolParameters,
170 strict: true,
171 execute: params => execute(params, strict.source),
172 });
173 }
174 const reasons = strict.unsupported
175 .map(entry => `${entry.path || '<root>'}: ${entry.keyword} (${entry.detail})`)
176 .join('; ');
177 logger.warn(
178 `OpenAIAgentsProvider: tool "${composioTool.slug}" is registered without strict mode because its schema cannot be expressed as strict structured outputs: ${reasons}`
179 );
180 }
181
182 return createOpenAIAgentTool({
183 name: composioTool.slug,
184 description: composioTool.description ?? '',
185 parameters: {
186 type: 'object',
187 properties: inputParameters?.properties || {},
188 required: inputParameters?.required || [],
189 additionalProperties: true,
190 },
191 strict: false,
192 execute: params => execute(params),
193 });
194 }
195
196 /**
197 * Wraps a list of Composio tools as a OpenAI Agents tool collection.
198 *
199 * This method transforms multiple Composio tool definitions into the format
200 * expected by OpenAI Agents for function calling, organizing them
201 * into a dictionary keyed by tool slug.
202 *
203 * @param {ComposioTool[]} tools - Array of Composio tools to wrap
204 * @param {ExecuteToolFn} executeTool - Function to execute the tools
205 * @returns {OpenAIAgentsToolCollection} Dictionary of wrapped tools in OpenAI Agents format
206 *
207 * @example
208 * ```typescript
209 * // Get OpenAI Agents tools from Composio
210 * const composio = new Composio({
211 * apiKey: 'your-api-key',
212 * provider: new OpenAIAgentsProvider()
213 * });
214 *
215 * const tools = await composio.tools.get('default', {
216 * toolkits: ['github'],
217 * });
218 *
219 * import { OpenAI } from '@openai/agents';
220 *
221 * export async function POST(req: Request) {
222 * const { messages } = await req.json();
223 * const openai = new OpenAI();
224 *
225 * const response = await openai.chat.completions.create({
226 * model: 'gpt-4',
227 * messages,
228 * tools: openaiAgentsTools
229 * });
230 *
231 * return new StreamingTextResponse(response.choices[0].message);
232 * }
233 * ```
234 */
235 wrapTools(tools: ComposioTool[], executeTool: ExecuteToolFn): OpenAIAgentsToolCollection {
236 return tools.map(tool => {
237 return this.wrapTool(tool, executeTool);
238 });
239 }
240 }