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 support for openai agents and other providers
haxzie committed
Jun 16, 2025 at 17:03 UTC
9d0861d3a4f47d2b1d74227aa973940511d9263e
26 files changed
+1868
-241
.github/workflows/test.yml
+2
-1
@@ -2,8 +2,9 @@ name: Test Typescript SDK
2
3
on:
4
push:
5
- branches: [main]
5
+ branches: [main, next]
6
pull_request:
7
+ branches: [main, next]
8
9
jobs:
10
test:
examples/connected-accounts/src/scopes.ts
new
+7
@@ -0,0 +1,7 @@
1
+import { Composio } from '@composio/core';
2
+
3
+const composio = new Composio();
4
+
5
+const response = await composio.authConfigs.get('ac_3COrKCdQYLNu');
6
+
7
+console.log(JSON.stringify(response, null, 2));
examples/openai/package.json
+6
-2
@@ -6,8 +6,9 @@
6
"main": "index.js",
7
"scripts": {
8
"start": "bun src/index.ts",
9
- "chat": "bun src/chat-completions.ts",
10
- "assistant": "bun src/assistants.ts",
9
+ "start:chat-completion": "bun src/chat-completions.ts",
10
+ "start:assistant": "bun src/assistants.ts",
11
+ "start:agents": "bun src/agents-api/index.ts",
12
"examples": "bun src/examples.ts",
13
"test": "echo \"Error: no test specified\" && exit 1"
14
},
@@ -17,6 +18,9 @@
18
"packageManager": "pnpm@10.8.0",
19
"dependencies": {
20
"@composio/core": "workspace:*",
21
+ "@composio/openai": "workspace:*",
22
+ "@composio/openai-agents": "workspace:*",
23
+ "@openai/agents": "^0.0.7",
24
"dotenv": "^16.4.1",
25
"openai": "^4.94.0",
26
"zod": "^3.24.2"
examples/openai/src/agents-api/index.ts
new
+35
@@ -0,0 +1,35 @@
1
+import { OpenAIAgentsProvider } from '@composio/openai-agents';
2
+import { Composio } from '@composio/core';
3
+import { Agent, run } from '@openai/agents';
4
+
5
+const composio = new Composio({
6
+ provider: new OpenAIAgentsProvider({
7
+ strict: true,
8
+ }),
9
+});
10
+
11
+console.log(`🔄 Fetching tools from composio...`);
12
+const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER', {
13
+ beforeExecute: async (toolSlug, toolkitSlug, params) => {
14
+ console.log(`🔄 Executing tool ${toolSlug} from toolkit ${toolkitSlug}...`);
15
+ return params;
16
+ },
17
+ afterExecute: async (toolSlug, toolkitSlug, result) => {
18
+ console.log(`✅ Tool ${toolSlug} executed`);
19
+ return result;
20
+ },
21
+});
22
+
23
+console.log(`✅ Tools fetched from composio`);
24
+
25
+const agent = new Agent({
26
+ name: 'Hackernews assistant',
27
+ tools: tools,
28
+});
29
+
30
+console.log(`🔄 Running agent...`);
31
+const result = await run(agent, 'Tell me about the user `pg` in hackernews');
32
+console.log(`✅ Received response from agent`);
33
+if (result.finalOutput) {
34
+ console.log(JSON.stringify(result.finalOutput, null, 2));
35
+}
examples/openai/src/agents.ts
new
+11
@@ -0,0 +1,11 @@
1
+import { Composio } from '@composio/core';
2
+import { Agent, webSearchTool, fileSearchTool } from '@openai/agents';
3
+
4
+const composio = new Composio();
5
+
6
+const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
7
+
8
+const agent = new Agent({
9
+ name: 'Travel assistant',
10
+ tools: tools,
11
+});
examples/openai/src/reponses-api/index.ts
new
+55
@@ -0,0 +1,55 @@
1
+import OpenAI from 'openai';
2
+import { Composio } from '@composio/core';
3
+import { OpenAIResponsesProvider } from '@composio/openai';
4
+
5
+const openai = new OpenAI();
6
+const composio = new Composio({
7
+ provider: new OpenAIResponsesProvider(),
8
+});
9
+
10
+console.log(`🔄 Fetching tools from composio...`);
11
+const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
12
+console.log(`✅ Tools fetched from composio`);
13
+
14
+console.log(`🔄 Generating response from OpenAI...`);
15
+const initialResponse = await openai.responses.create({
16
+ model: 'gpt-4.1',
17
+ input: 'Tell me about the user `pg` in hackernews',
18
+ tools,
19
+});
20
+console.log(`✅ Response generated from OpenAI`);
21
+console.log(JSON.stringify(initialResponse.output, null, 2));
22
+
23
+console.log(`🔄 Handling tool calls from response...`);
24
+const modelInputs = await composio.provider.handleResponse(
25
+ 'default',
26
+ initialResponse,
27
+ {},
28
+ {
29
+ beforeExecute: async (toolSlug, toolkitSlug, params) => {
30
+ console.log(`🔄 Executing tool ${toolSlug} from toolkit ${toolkitSlug}...`);
31
+ return params;
32
+ },
33
+ afterExecute: async (toolSlug, toolkitSlug, result) => {
34
+ console.log(`✅ Tool ${toolSlug} executed`);
35
+ return result;
36
+ },
37
+ }
38
+);
39
+
40
+console.log(`🔄 Submitting tool outputs to OpenAI...`);
41
+console.log(JSON.stringify(modelInputs, null, 2));
42
+const finalResponse = await openai.responses.create({
43
+ model: 'gpt-4.1',
44
+ input: [...initialResponse.output, ...modelInputs],
45
+ tools,
46
+});
47
+
48
+console.log(`✅ Tool outputs submitted to OpenAI`);
49
+const finalContent = finalResponse.output[0];
50
+if (finalContent.type === 'message' && finalContent.content[0].type === 'output_text') {
51
+ console.log(`🤖 OpenAI response`, finalContent.content[0].text);
52
+} else {
53
+ console.error(`❌ Unexpected response from OpenAI`);
54
+ console.log(JSON.stringify(finalResponse.output, null, 2));
55
+}
packages/core/src/index.ts
+1
-1
@@ -4,7 +4,7 @@ export { ComposioProvider } from './provider/ComposioProvider';
4
export { BaseAgenticProvider, BaseNonAgenticProvider } from './provider/BaseProvider';
5
export type { BaseComposioProvider } from './provider/BaseProvider';
6
export { OpenAIProvider } from './provider/OpenAIProvider';
7
-export { jsonSchemaToZodSchema } from './utils/jsonSchema';
7
+export { jsonSchemaToZodSchema, removeNonRequiredProperties } from './utils/jsonSchema';
8
export { AuthScheme } from './models/AuthScheme';
9
export * from './types/provider.types';
10
export * from './types/customTool.types';
packages/core/src/models/AuthConfigs.ts
+1
@@ -83,6 +83,7 @@ export class AuthConfigs {
83
createdBy: authConfig.created_by,
84
createdAt: authConfig.created_at,
85
lastUpdatedAt: authConfig.last_updated_at,
86
+ restrictToFollowingTools: authConfig.restrict_to_following_tools,
87
});
88
if (result.error) {
89
throw new ValidationError('Failed to parse auth config response', {
packages/core/src/models/Tools.ts
+1
-14
@@ -40,7 +40,6 @@ import {
40
} from '../errors/ToolErrors';
41
import { ValidationError } from '../errors/ValidationErrors';
42
import { telemetry } from '../telemetry/Telemetry';
43
-import { removeNonRequiredProperties } from '../utils/jsonSchema';
43
/**
44
* This class is used to manage tools in the Composio SDK.
45
* It provides methods to list, get, and execute tools.
@@ -455,19 +454,7 @@ export class Tools<
454
return this.provider.wrapTools([tool], executeToolFn) as TToolCollection;
455
} else {
456
// if the first argument is an object, get a list of tools
458
- let tools = await this.getRawComposioTools(userId, arg2, options?.modifySchema);
459
- // if the strict flag is true, remove all non-required properties from the input and output parameters
460
- if (arg2?.strict) {
461
- tools = tools.map(tool => ({
462
- ...tool,
463
- inputParameters: tool.inputParameters
464
- ? removeNonRequiredProperties(tool.inputParameters)
465
- : undefined,
466
- outputParameters: tool.outputParameters
467
- ? removeNonRequiredProperties(tool.outputParameters)
468
- : undefined,
469
- }));
470
- }
457
+ const tools = await this.getRawComposioTools(userId, arg2, options?.modifySchema);
458
return this.provider.wrapTools(tools, executeToolFn) as TToolCollection;
459
}
460
}
packages/core/src/types/authConfigs.types.ts
+1
@@ -83,6 +83,7 @@ export const AuthConfigRetrieveResponseSchema = z.object({
83
authScheme: AuthSchemeEnum.optional(),
84
credentials: z.record(z.string(), z.unknown()).optional(),
85
expectedInputFields: z.array(z.unknown()).optional(),
86
+ restrictToFollowingTools: z.array(z.string()).optional(),
87
isComposioManaged: z.boolean().optional(),
88
createdBy: z.string().optional(),
89
createdAt: z.string().optional(),
packages/core/src/types/tool.types.ts
-15
@@ -137,12 +137,6 @@ export const ToolListFilterByToolkitsSchema = z.object({
137
cursor: z.string().optional(),
138
limit: z.number().optional(),
139
search: z.string().optional(),
140
- strict: z
141
- .boolean()
142
- .optional()
143
- .describe(
144
- 'If true, all the non-required fields will be removed from the input/output params of the tool'
145
- ),
140
});
141
export type ToolListFilterByToolkits = z.infer<typeof ToolListFilterByToolkitsSchema>;
142
@@ -151,12 +145,6 @@ export const ToolListFilterBySearchSchema = z.object({
145
toolkits: z.array(z.string()).optional(),
146
cursor: z.string().optional(),
147
limit: z.number().optional(),
154
- strict: z
155
- .boolean()
156
- .optional()
157
- .describe(
158
- 'If true, all the non-required fields will be removed from the input/output params of the tool'
159
- ),
148
});
149
export type ToolListFilterBySearch = z.infer<typeof ToolListFilterBySearchSchema>;
150
@@ -167,7 +155,6 @@ type ToolsOnlyParams = {
155
cursor?: never;
156
limit?: never;
157
search?: never;
170
- strict?: boolean;
158
};
159
160
type ToolkitsOnlyParams = {
@@ -177,7 +164,6 @@ type ToolkitsOnlyParams = {
164
cursor?: string;
165
limit?: number;
166
search?: never;
180
- strict?: boolean;
167
};
168
169
type ToolkitSearchOnlyParams = {
@@ -187,7 +173,6 @@ type ToolkitSearchOnlyParams = {
173
cursor?: string;
174
limit?: number;
175
search?: string;
190
- strict?: boolean;
176
};
177
/**
178
* ToolListParams is the parameters for the list of tools.
packages/core/src/utils/jsonSchema.ts
+11
-5
@@ -1,4 +1,4 @@
1
-import { z } from 'zod';
1
+import { z, ZodObject, ZodTypeAny } from 'zod';
2
import { JsonSchemaToZodError } from '../errors';
3
import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
4
@@ -10,7 +10,12 @@ import { jsonSchemaToZod } from '@composio/json-schema-to-zod';
10
* @returns The JSON schema with all non-required properties removed
11
*/
12
export const removeNonRequiredProperties = <
13
- T extends { type: 'object'; properties: Record<string, unknown>; required?: string[] },
13
+ T extends {
14
+ type: 'object';
15
+ properties: Record<string, unknown>;
16
+ required?: string[];
17
+ additionalProperties?: boolean;
18
+ },
19
>(
20
schema: T
21
): T => {
@@ -21,6 +26,7 @@ export const removeNonRequiredProperties = <
26
)
27
);
28
}
29
+ schema.additionalProperties = false;
30
return schema as T;
31
};
32
@@ -63,12 +69,12 @@ export const removeNonRequiredProperties = <
69
* // })
70
* ```
71
*/
66
-export function jsonSchemaToZodSchema(
72
+export function jsonSchemaToZodSchema<T extends z.ZodTypeAny>(
73
jsonSchema: Record<string, unknown>,
74
{ strict }: { strict?: boolean } = {
75
strict: false,
76
}
71
-): z.ZodTypeAny {
77
+): T {
78
try {
79
let schema = jsonSchema;
80
// Remove all non-required properties from the schema if strict is true
@@ -82,7 +88,7 @@ export function jsonSchemaToZodSchema(
88
);
89
}
90
// Convert the JSON schema properties to Zod schema
85
- const zodSchema = jsonSchemaToZod(schema) as z.ZodTypeAny;
91
+ const zodSchema = jsonSchemaToZod(schema) as T;
92
return zodSchema;
93
} catch (error) {
94
throw new JsonSchemaToZodError('Failed to convert JSON Schema to Zod Schema', {
packages/core/test/tools/tools.test.ts
-130
@@ -329,136 +329,6 @@ describe('Tools', () => {
329
330
expect(getRawComposioToolBySlugSpy).toHaveBeenCalledWith(userId, slug, schemaModifier);
331
});
332
-
333
- it('should remove non-required properties when strict mode is enabled', async () => {
334
- const userId = 'test-user';
335
- const filters = {
336
- tools: ['TOOL1'],
337
- strict: true,
338
- };
339
-
340
- const toolWithOptionalParams = {
341
- ...toolMocks.transformedTool,
342
- inputParameters: {
343
- type: 'object',
344
- required: ['requiredParam'],
345
- properties: {
346
- requiredParam: {
347
- type: 'string',
348
- description: 'Required parameter',
349
- },
350
- optionalParam: {
351
- type: 'string',
352
- description: 'Optional parameter',
353
- },
354
- },
355
- },
356
- outputParameters: {
357
- type: 'object',
358
- required: ['requiredOutput'],
359
- properties: {
360
- requiredOutput: {
361
- type: 'string',
362
- description: 'Required output',
363
- },
364
- optionalOutput: {
365
- type: 'string',
366
- description: 'Optional output',
367
- },
368
- },
369
- },
370
- };
371
-
372
- const getRawComposioToolsSpy = vi.spyOn(context.tools, 'getRawComposioTools');
373
- getRawComposioToolsSpy.mockResolvedValueOnce([toolWithOptionalParams as unknown as Tool]);
374
-
375
- context.mockProvider.wrapTools.mockReturnValueOnce('wrapped-tools-collection');
376
-
377
- const result = await context.tools.get(userId, filters);
378
-
379
- expect(context.mockProvider.wrapTools).toHaveBeenCalledWith(
380
- [
381
- {
382
- ...toolWithOptionalParams,
383
- inputParameters: {
384
- type: 'object',
385
- required: ['requiredParam'],
386
- properties: {
387
- requiredParam: {
388
- type: 'string',
389
- description: 'Required parameter',
390
- },
391
- },
392
- },
393
- outputParameters: {
394
- type: 'object',
395
- required: ['requiredOutput'],
396
- properties: {
397
- requiredOutput: {
398
- type: 'string',
399
- description: 'Required output',
400
- },
401
- },
402
- },
403
- },
404
- ],
405
- expect.any(Function)
406
- );
407
- expect(result).toEqual('wrapped-tools-collection');
408
- });
409
-
410
- it('should not modify properties when strict mode is disabled', async () => {
411
- const userId = 'test-user';
412
- const filters = {
413
- tools: ['TOOL1'],
414
- strict: false,
415
- };
416
-
417
- const toolWithOptionalParams = {
418
- ...toolMocks.transformedTool,
419
- inputParameters: {
420
- type: 'object',
421
- required: ['requiredParam'],
422
- properties: {
423
- requiredParam: {
424
- type: 'string',
425
- description: 'Required parameter',
426
- },
427
- optionalParam: {
428
- type: 'string',
429
- description: 'Optional parameter',
430
- },
431
- },
432
- },
433
- outputParameters: {
434
- type: 'object',
435
- required: ['requiredOutput'],
436
- properties: {
437
- requiredOutput: {
438
- type: 'string',
439
- description: 'Required output',
440
- },
441
- optionalOutput: {
442
- type: 'string',
443
- description: 'Optional output',
444
- },
445
- },
446
- },
447
- };
448
-
449
- const getRawComposioToolsSpy = vi.spyOn(context.tools, 'getRawComposioTools');
450
- getRawComposioToolsSpy.mockResolvedValueOnce([toolWithOptionalParams as unknown as Tool]);
451
-
452
- context.mockProvider.wrapTools.mockReturnValueOnce('wrapped-tools-collection');
453
-
454
- const result = await context.tools.get(userId, filters);
455
-
456
- expect(context.mockProvider.wrapTools).toHaveBeenCalledWith(
457
- [toolWithOptionalParams],
458
- expect.any(Function)
459
- );
460
- expect(result).toEqual('wrapped-tools-collection');
461
- });
332
});
333
334
describe('execute', () => {
packages/providers/openai-agents/CHANGELOG.md
new
+181
@@ -0,0 +1,181 @@
1
+# @composio/vercel
2
+
3
+## 0.1.21
4
+
5
+### Patch Changes
6
+
7
+- Add host name support in SDK
8
+- Updated dependencies
9
+ - @composio/core@0.1.21
10
+
11
+## 0.1.20
12
+
13
+### Patch Changes
14
+
15
+- 1ab34ef: Fix json schema support in tools
16
+- Updated dependencies [1ab34ef]
17
+ - @composio/core@0.1.20
18
+
19
+## 0.1.19
20
+
21
+### Patch Changes
22
+
23
+- c8e89d5: Fix telemetry transport
24
+- Updated dependencies [c8e89d5]
25
+ - @composio/core@0.1.19
26
+
27
+## 0.1.18
28
+
29
+### Patch Changes
30
+
31
+- 37a1f01: Feat better connected account creation flow
32
+- Updated dependencies [37a1f01]
33
+ - @composio/core@0.1.18
34
+
35
+## 0.1.17
36
+
37
+### Patch Changes
38
+
39
+- df31cc2: Fix json schema parsing
40
+- Updated dependencies [df31cc2]
41
+ - @composio/core@0.1.17
42
+
43
+## 0.1.16
44
+
45
+### Patch Changes
46
+
47
+- f943ba4: Export all the types from the core SDK
48
+- Updated dependencies [f943ba4]
49
+ - @composio/core@0.1.16
50
+
51
+## 0.1.15
52
+
53
+### Patch Changes
54
+
55
+- 208e320: Update json schema transformations issues related to strict mode
56
+- Updated dependencies [208e320]
57
+ - @composio/core@0.1.15
58
+
59
+## 0.1.14
60
+
61
+### Patch Changes
62
+
63
+- 4ddfafc: Add json schema to zod schema
64
+- Updated dependencies [4ddfafc]
65
+ - @composio/core@0.1.14
66
+
67
+## 0.1.13
68
+
69
+### Patch Changes
70
+
71
+- 040b5a4: Ability to create sessions for transferring request ids
72
+- Updated dependencies [040b5a4]
73
+ - @composio/core@0.1.13
74
+
75
+## 0.1.12
76
+
77
+### Patch Changes
78
+
79
+- c1443db: Improved error handling and telemetry
80
+- b121e73: Update packages to stable version
81
+- f144202: Update tsdocs across all the functions
82
+- ba8d991: Fix initiate connection flows and api issues
83
+- ca59bcd: Update documentations and fix API discrepencies
84
+- e51680c: Fix versioning with changesets
85
+- 0b15376: Add custom toolkit examples
86
+- de3f522: Stable version with test coverage and other stuff
87
+- a2f9537: Update tools.get to accept discriminated unions
88
+- 83a0d15: Test github ci publish
89
+- eeec413: Rename modifiers, add docs and other miscellanious improvements
90
+- Updated dependencies [c1443db]
91
+- Updated dependencies [b121e73]
92
+- Updated dependencies [f144202]
93
+- Updated dependencies [ba8d991]
94
+- Updated dependencies [ca59bcd]
95
+- Updated dependencies [e51680c]
96
+- Updated dependencies [0b15376]
97
+- Updated dependencies [de3f522]
98
+- Updated dependencies [a2f9537]
99
+- Updated dependencies [83a0d15]
100
+- Updated dependencies [eeec413]
101
+ - @composio/core@0.1.12
102
+
103
+## 0.1.12-alpha.16
104
+
105
+### Patch Changes
106
+
107
+- 0b15376: Add custom toolkit examples
108
+- Updated dependencies [0b15376]
109
+ - @composio/core@0.1.12-alpha.16
110
+
111
+## 0.1.12-alpha.15
112
+
113
+### Patch Changes
114
+
115
+- f144202: Update tsdocs across all the functions
116
+- Updated dependencies [f144202]
117
+ - @composio/core@0.1.12-alpha.15
118
+
119
+## 0.1.12-alpha.14
120
+
121
+### Patch Changes
122
+
123
+- 83a0d15: Test github ci publish
124
+- Updated dependencies [83a0d15]
125
+ - @composio/core@0.1.12-alpha.14
126
+
127
+## 0.1.12-alpha.13
128
+
129
+### Patch Changes
130
+
131
+- a2f9537: Update tools.get to accept discriminated unions
132
+- Updated dependencies [a2f9537]
133
+ - @composio/core@0.1.12-alpha.13
134
+
135
+## 0.1.12-alpha.12
136
+
137
+### Patch Changes
138
+
139
+- de3f522: Stable version with test coverage and other stuff
140
+- Updated dependencies [de3f522]
141
+ - @composio/core@0.1.12-alpha.12
142
+
143
+## 0.1.12-alpha.11
144
+
145
+### Patch Changes
146
+
147
+- Improved error handling and telemetry
148
+- Updated dependencies
149
+ - @composio/core@0.1.12-alpha.11
150
+
151
+## 0.1.12-alpha.10
152
+
153
+### Patch Changes
154
+
155
+- eeec413: Rename modifiers, add docs and other miscellanious improvements
156
+- Updated dependencies [eeec413]
157
+ - @composio/core@0.1.12-alpha.10
158
+
159
+## 0.1.12-alpha.9
160
+
161
+### Patch Changes
162
+
163
+- ba8d991: Fix initiate connection flows and api issues
164
+- Updated dependencies [ba8d991]
165
+ - @composio/core@0.1.12-alpha.9
166
+
167
+## 0.1.12-alpha.8
168
+
169
+### Patch Changes
170
+
171
+- ca59bcd: Update documentations and fix API discrepencies
172
+- Updated dependencies [ca59bcd]
173
+ - @composio/core@0.1.12-alpha.8
174
+
175
+## 0.1.12-alpha.7
176
+
177
+### Patch Changes
178
+
179
+- e51680c: Fix versioning with changesets
180
+- Updated dependencies [e51680c]
181
+ - @composio/core@0.1.12-alpha.7
packages/providers/openai-agents/README.md
new
+238
@@ -0,0 +1,238 @@
1
+# @composio/vercel
2
+
3
+The Vercel AI SDK provider for Composio SDK, providing seamless integration with Vercel's AI SDK and tools.
4
+
5
+## Features
6
+
7
+- **Vercel AI SDK Integration**: Seamless integration with Vercel's AI SDK
8
+- **Streaming Support**: First-class support for streaming responses
9
+- **Model Agnostic**: Works with any model supported by Vercel AI SDK (OpenAI, Anthropic, etc.)
10
+- **UI Components**: Integration with Vercel's React components for chat interfaces
11
+- **Tool Execution**: Execute tools with proper parameter handling and streaming
12
+- **Type Safety**: Full TypeScript support with proper type definitions
13
+
14
+## Installation
15
+
16
+```bash
17
+npm install @composio/vercel ai
18
+# or
19
+yarn add @composio/vercel ai
20
+# or
21
+pnpm add @composio/vercel ai
22
+```
23
+
24
+## Environment Variables
25
+
26
+Required environment variables:
27
+
28
+- `COMPOSIO_API_KEY`: Your Composio API key
29
+
30
+Optional environment variables (based on model choice):
31
+
32
+- `OPENAI_API_KEY`: Your OpenAI API key (if using OpenAI)
33
+- `ANTHROPIC_API_KEY`: Your Anthropic API key (if using Anthropic)
34
+- `GEMINI_API_KEY`: Your Google AI API key (if using Gemini)
35
+
36
+## Quick Start
37
+
38
+```typescript
39
+import { Composio } from '@composio/core';
40
+import { VercelProvider } from '@composio/vercel';
41
+
42
+// Initialize Composio with Vercel provider
43
+const composio = new Composio({
44
+ apiKey: 'your-composio-api-key',
45
+ provider: new VercelProvider(),
46
+});
47
+
48
+// Get available tools
49
+const tools = await composio.tools.get('user123', {
50
+ toolkits: ['gmail', 'googlecalendar'],
51
+ limit: 10,
52
+});
53
+
54
+// Get a specific tool
55
+const sendEmailTool = await composio.tools.get('user123', 'GMAIL_SEND_EMAIL');
56
+```
57
+
58
+## Examples
59
+
60
+Check out our complete example implementations:
61
+
62
+- [Basic Vercel Integration](../../examples/vercel/src/index.ts)
63
+
64
+### Basic Chat Completion with Streaming
65
+
66
+```typescript
67
+import { Composio } from '@composio/core';
68
+import { VercelProvider } from '@composio/vercel';
69
+import { useChat } from 'ai/react';
70
+
71
+// Initialize Composio with Vercel provider
72
+const composio = new Composio({
73
+ apiKey: process.env.COMPOSIO_API_KEY,
74
+ provider: new VercelProvider()
75
+});
76
+
77
+// In your React component
78
+function ChatComponent() {
79
+ const { messages, input, handleInputChange, handleSubmit } = useChat({
80
+ api: '/api/chat',
81
+ });
82
+
83
+ return (
84
+ <div>
85
+ {messages.map(m => (
86
+ <div key={m.id}>
87
+ {m.role === 'user' ? 'User: ' : 'AI: '}
88
+ {m.content}
89
+ </div>
90
+ ))}
91
+
92
+ <form onSubmit={handleSubmit}>
93
+ <input
94
+ value={input}
95
+ onChange={handleInputChange}
96
+ placeholder="Say something..."
97
+ />
98
+ <button type="submit">Send</button>
99
+ </form>
100
+ </div>
101
+ );
102
+}
103
+
104
+// In your API route (e.g. app/api/chat/route.ts)
105
+import { streamText } from 'ai';
106
+import { openai } from '@ai-sdk/openai';
107
+
108
+export async function POST(req: Request) {
109
+ const { messages } = await req.json();
110
+ const tools = await composio.tools.get('user123', {
111
+ toolkits: ['gmail'],
112
+ });
113
+
114
+ const result = streamText({
115
+ model: openai('gpt-4'),
116
+ messages,
117
+ tools,
118
+ });
119
+
120
+ return result.toDataStreamResponse();
121
+}
122
+```
123
+
124
+### Tool Execution with Streaming
125
+
126
+```typescript
127
+import { Composio } from '@composio/core';
128
+import { VercelProvider } from '@composio/vercel';
129
+import { streamText } from 'ai';
130
+
131
+const composio = new Composio({
132
+ apiKey: process.env.COMPOSIO_API_KEY,
133
+ provider: new VercelProvider(),
134
+});
135
+
136
+// Example API route that handles tool execution
137
+export async function POST(req: Request) {
138
+ const { messages } = await req.json();
139
+ const tools = await composio.tools.get('user123', {
140
+ toolkits: ['gmail', 'googlecalendar'],
141
+ });
142
+
143
+ const stream = streamText({
144
+ model: openai('gpt-4'),
145
+ messages,
146
+ tools,
147
+ callbacks: {
148
+ onToolCall: async tool => {
149
+ // Execute the tool and return result
150
+ return await composio.provider.executeToolCall(tool);
151
+ },
152
+ },
153
+ });
154
+
155
+ return stream.toDataStreamResponse();
156
+}
157
+```
158
+
159
+## Provider Configuration
160
+
161
+The Vercel provider can be configured with various options:
162
+
163
+```typescript
164
+const provider = new VercelProvider({
165
+ // Default model configuration
166
+ model: openai('gpt-4'),
167
+ // Custom execution modifiers
168
+ modifiers: {
169
+ beforeExecute: params => {
170
+ // Transform parameters before execution
171
+ return params;
172
+ },
173
+ afterExecute: response => {
174
+ // Transform response after execution
175
+ return response;
176
+ },
177
+ },
178
+});
179
+```
180
+
181
+### Strict Mode
182
+
183
+When using tools with Vercel AI SDK, you might need to ensure that all tool parameters are marked as required. This is because Vercel AI SDK's function calling implementation requires all fields to be marked as required. You can enable strict mode when fetching tools to automatically remove all non-required properties from both input and output parameters:
184
+
185
+```typescript
186
+// Get tools with strict mode enabled
187
+const tools = await composio.tools.get('user123', {
188
+ toolkits: ['gmail', 'googlecalendar'],
189
+ strict: true, // This will remove all non-required properties from tool parameters
190
+});
191
+
192
+// Use these tools with Vercel AI SDK
193
+const stream = streamText({
194
+ model: openai('gpt-4'),
195
+ messages,
196
+ tools, // These tools will only have required parameters
197
+});
198
+```
199
+
200
+For more information about strict mode in function calling, see [OpenAI's documentation](https://platform.openai.com/docs/guides/function-calling#strict-mode).
201
+
202
+## API Reference
203
+
204
+### VercelProvider Class
205
+
206
+The `VercelProvider` class extends `BaseComposioProvider` and provides Vercel AI SDK-specific functionality.
207
+
208
+#### Methods
209
+
210
+##### `executeToolCall(tool: ToolCall): Promise<string>`
211
+
212
+Executes a tool call and returns the result.
213
+
214
+```typescript
215
+const result = await provider.executeToolCall(toolCall);
216
+```
217
+
218
+##### `handleToolCalls(stream: AIStream): AsyncGenerator<AIStreamEvent>`
219
+
220
+Handles tool calls from a stream and yields events.
221
+
222
+```typescript
223
+for await (const event of provider.handleToolCalls(stream)) {
224
+ // Handle events
225
+}
226
+```
227
+
228
+## Contributing
229
+
230
+We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for more details.
231
+
232
+## License
233
+
234
+ISC License
235
+
236
+## Support
237
+
238
+For support, please visit our [Documentation](https://docs.composio.dev) or join our [Discord Community](https://discord.gg/composio).
packages/providers/openai-agents/package.json
new
+42
@@ -0,0 +1,42 @@
1
+{
2
+ "name": "@composio/openai-agents",
3
+ "version": "0.1.21",
4
+ "description": "",
5
+ "main": "src/index.ts",
6
+ "type": "module",
7
+ "publishConfig": {
8
+ "access": "public",
9
+ "main": "dist/index.js",
10
+ "types": "dist/index.d.ts"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "import": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "require": "./dist/index.cjs"
17
+ }
18
+ },
19
+ "files": [
20
+ "README.md",
21
+ "dist"
22
+ ],
23
+ "scripts": {
24
+ "build": "tsup",
25
+ "test": "vitest run"
26
+ },
27
+ "keywords": [],
28
+ "author": "",
29
+ "license": "ISC",
30
+ "packageManager": "pnpm@10.8.0",
31
+ "peerDependencies": {
32
+ "@composio/core": "0.1.21",
33
+ "@openai/agents": "^0.0.7"
34
+ },
35
+ "devDependencies": {
36
+ "@composio/core": "workspace:*",
37
+ "tsup": "^8.4.0",
38
+ "typescript": "^5.8.3",
39
+ "vitest": "^3.1.4"
40
+ },
41
+ "gitHead": "4fae6e54d5c150fba955cc5fa314281da5a1e064"
42
+}
packages/providers/openai-agents/src/index.ts
new
+166
@@ -0,0 +1,166 @@
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 Vercel AI SDK.
9
+ *
10
+ * @packageDocumentation
11
+ * @module providers/openai-agents
12
+ */
13
+import {
14
+ BaseAgenticProvider,
15
+ Tool as ComposioTool,
16
+ ExecuteToolFn,
17
+ jsonSchemaToZodSchema,
18
+} from '@composio/core';
19
+import type { Tool as OpenAIAgentTool } from '@openai/agents';
20
+import { tool as createOpenAIAgentTool } from '@openai/agents';
21
+
22
+type OpenAIAgentsToolCollection = Array<OpenAIAgentTool>;
23
+export class OpenAIAgentsProvider extends BaseAgenticProvider<
24
+ OpenAIAgentsToolCollection,
25
+ OpenAIAgentTool
26
+> {
27
+ readonly name = 'openai-agents';
28
+ private strict: boolean | null;
29
+
30
+ /**
31
+ * Creates a new instance of the OpenAIAgentsProvider.
32
+ *
33
+ * This provider enables integration with the @openai/agents package,
34
+ * allowing Composio tools to be used with OpenAI Agents.
35
+ *
36
+ * @example
37
+ * ```typescript
38
+ * // Initialize the OpenAIAgentsProvider
39
+ * const provider = new OpenAIAgentsProvider();
40
+ *
41
+ * // Use with Composio
42
+ * const composio = new Composio({
43
+ * apiKey: 'your-api-key',
44
+ * provider: new OpenAIAgentsProvider()
45
+ * });
46
+ *
47
+ * // Use the provider to wrap tools for @openai/agents
48
+ * const vercelTools = provider.wrapTools(composioTools, composio.tools.execute);
49
+ * ```
50
+ */
51
+ constructor(options?: { strict?: boolean }) {
52
+ super();
53
+ this.strict = options?.strict ?? false;
54
+ }
55
+
56
+ /**
57
+ * Wraps a Composio tool in a OpenAI Agents tool format.
58
+ *
59
+ * This method transforms a Composio tool definition into the format
60
+ * expected by @openai/agents for function calling.
61
+ *
62
+ * @param {ComposioTool} composioTool - The Composio tool to wrap
63
+ * @param {ExecuteToolFn} executeTool - Function to execute the tool
64
+ * @returns {OpenAIAgentsTool} The wrapped OpenAI Agents tool
65
+ *
66
+ * @example
67
+ * ```typescript
68
+ * // Wrap a single tool for use with Vercel AI SDK
69
+ * const composioTool = {
70
+ * slug: 'SEARCH_TOOL',
71
+ * description: 'Search for information',
72
+ * inputParameters: {
73
+ * type: 'object',
74
+ * properties: {
75
+ * query: { type: 'string' }
76
+ * },
77
+ * required: ['query']
78
+ * }
79
+ * };
80
+ *
81
+ * // Create a Vercel tool using the provider
82
+ * const vercelTool = provider.wrapTool(
83
+ * composioTool,
84
+ * composio.tools.execute
85
+ * );
86
+ *
87
+ * // Use with Vercel AI SDK
88
+ * import { StreamingTextResponse, Message } from 'ai';
89
+ * import { OpenAI } from 'openai';
90
+ *
91
+ * export async function POST(req: Request) {
92
+ * const { messages } = await req.json();
93
+ * const openai = new OpenAI();
94
+ *
95
+ * const response = await openai.chat.completions.create({
96
+ * model: 'gpt-4',
97
+ * messages,
98
+ * tools: [vercelTool]
99
+ * });
100
+ *
101
+ * return new StreamingTextResponse(response.choices[0].message);
102
+ * }
103
+ * ```
104
+ */
105
+ wrapTool(composioTool: ComposioTool, executeTool: ExecuteToolFn): OpenAIAgentTool {
106
+ return createOpenAIAgentTool({
107
+ name: composioTool.slug,
108
+ description: composioTool.description ?? '',
109
+ parameters: jsonSchemaToZodSchema(
110
+ (composioTool.inputParameters as Record<string, unknown>) ?? {},
111
+ {
112
+ strict: this.strict ? true : false,
113
+ }
114
+ ),
115
+ execute: async params => {
116
+ const input = typeof params === 'string' ? JSON.parse(params) : params;
117
+ return await executeTool(composioTool.slug, input);
118
+ },
119
+ });
120
+ }
121
+
122
+ /**
123
+ * Wraps a list of Composio tools as a OpenAI Agents tool collection.
124
+ *
125
+ * This method transforms multiple Composio tool definitions into the format
126
+ * expected by OpenAI Agents for function calling, organizing them
127
+ * into a dictionary keyed by tool slug.
128
+ *
129
+ * @param {ComposioTool[]} tools - Array of Composio tools to wrap
130
+ * @param {ExecuteToolFn} executeTool - Function to execute the tools
131
+ * @returns {OpenAIAgentsToolCollection} Dictionary of wrapped tools in OpenAI Agents format
132
+ *
133
+ * @example
134
+ * ```typescript
135
+ * // Get OpenAI Agents tools from Composio
136
+ * const composio = new Composio({
137
+ * apiKey: 'your-api-key',
138
+ * provider: new OpenAIAgentsProvider()
139
+ * });
140
+ *
141
+ * const tools = await composio.tools.get('default', {
142
+ * toolkits: ['github'],
143
+ * });
144
+ *
145
+ * import { OpenAI } from '@openai/agents';
146
+ *
147
+ * export async function POST(req: Request) {
148
+ * const { messages } = await req.json();
149
+ * const openai = new OpenAI();
150
+ *
151
+ * const response = await openai.chat.completions.create({
152
+ * model: 'gpt-4',
153
+ * messages,
154
+ * tools: openaiAgentsTools
155
+ * });
156
+ *
157
+ * return new StreamingTextResponse(response.choices[0].message);
158
+ * }
159
+ * ```
160
+ */
161
+ wrapTools(tools: ComposioTool[], executeTool: ExecuteToolFn): OpenAIAgentsToolCollection {
162
+ return tools.map(tool => {
163
+ return this.wrapTool(tool, executeTool);
164
+ });
165
+ }
166
+}
packages/providers/openai-agents/test/openai-agents.test.ts
new
+203
@@ -0,0 +1,203 @@
1
+import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+import { OpenAIAgentsProvider } from '../src';
3
+import { Tool } from '@composio/core';
4
+import { tool as createOpenAIAgentTool } from '@openai/agents';
5
+
6
+// Define an interface for our mocked OpenAI Agent tool
7
+interface MockedOpenAIAgentTool {
8
+ name: string;
9
+ description: string;
10
+ parameters: any;
11
+ execute: Function;
12
+ _isMockedOpenAIAgentTool: boolean;
13
+}
14
+
15
+// Mock the @openai/agents module
16
+vi.mock('@openai/agents', () => {
17
+ return {
18
+ tool: vi.fn().mockImplementation(toolConfig => {
19
+ return {
20
+ ...toolConfig,
21
+ _isMockedOpenAIAgentTool: true,
22
+ } as MockedOpenAIAgentTool;
23
+ }),
24
+ };
25
+});
26
+
27
+describe('OpenAIAgentsProvider', () => {
28
+ let provider: OpenAIAgentsProvider;
29
+ let mockTool: Tool;
30
+ let mockExecuteToolFn: any;
31
+
32
+ beforeEach(() => {
33
+ provider = new OpenAIAgentsProvider();
34
+
35
+ // Mock the global execute tool function
36
+ mockExecuteToolFn = vi.fn().mockResolvedValue({
37
+ data: { result: 'success' },
38
+ error: null,
39
+ successful: true,
40
+ });
41
+ provider._setExecuteToolFn(mockExecuteToolFn);
42
+
43
+ // Create a mock Composio tool
44
+ mockTool = {
45
+ slug: 'test-tool',
46
+ name: 'Test Tool',
47
+ description: 'A tool for testing',
48
+ inputParameters: {
49
+ type: 'object',
50
+ properties: {
51
+ input: {
52
+ type: 'string',
53
+ description: 'Test input',
54
+ },
55
+ },
56
+ required: ['input'],
57
+ },
58
+ tags: [],
59
+ };
60
+
61
+ // Reset mocks before each test
62
+ vi.clearAllMocks();
63
+ });
64
+
65
+ describe('name property', () => {
66
+ it('should have the correct name', () => {
67
+ expect(provider.name).toBe('openai-agents');
68
+ });
69
+ });
70
+
71
+ describe('_isAgentic property', () => {
72
+ it('should be agentic', () => {
73
+ expect(provider._isAgentic).toBe(true);
74
+ });
75
+ });
76
+
77
+ describe('wrapTool', () => {
78
+ it('should wrap a tool in OpenAI Agent tool format', () => {
79
+ const wrapped = provider.wrapTool(
80
+ mockTool,
81
+ mockExecuteToolFn
82
+ ) as unknown as MockedOpenAIAgentTool;
83
+
84
+ expect(createOpenAIAgentTool).toHaveBeenCalledWith({
85
+ name: mockTool.slug,
86
+ description: mockTool.description,
87
+ parameters: mockTool.inputParameters,
88
+ execute: expect.any(Function),
89
+ });
90
+
91
+ expect(wrapped._isMockedOpenAIAgentTool).toBe(true);
92
+ });
93
+
94
+ it('should handle tools without input parameters', () => {
95
+ const toolWithoutParams: Tool = {
96
+ ...mockTool,
97
+ inputParameters: undefined,
98
+ };
99
+
100
+ const wrapped = provider.wrapTool(
101
+ toolWithoutParams,
102
+ mockExecuteToolFn
103
+ ) as unknown as MockedOpenAIAgentTool;
104
+
105
+ expect(wrapped._isMockedOpenAIAgentTool).toBe(true);
106
+ });
107
+
108
+ it('should create a function that executes the tool with the right parameters', async () => {
109
+ provider.wrapTool(mockTool, mockExecuteToolFn) as unknown as MockedOpenAIAgentTool;
110
+
111
+ // Extract the execute function from the call to tool()
112
+ const executeFunction = (createOpenAIAgentTool as any).mock.calls[0][0].execute;
113
+
114
+ // Test the execute function with an object parameter
115
+ const params = { input: 'test-value' };
116
+ await executeFunction(params);
117
+
118
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, params);
119
+
120
+ // Reset and test with a JSON string parameter
121
+ vi.clearAllMocks();
122
+ const stringParams = JSON.stringify(params);
123
+ await executeFunction(stringParams);
124
+
125
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, params);
126
+ });
127
+ });
128
+
129
+ describe('wrapTools', () => {
130
+ it('should wrap multiple tools', () => {
131
+ const anotherTool: Tool = {
132
+ ...mockTool,
133
+ slug: 'another-tool',
134
+ name: 'Another Tool',
135
+ };
136
+ const tools = [mockTool, anotherTool];
137
+
138
+ const wrapped = provider.wrapTools(tools, mockExecuteToolFn);
139
+
140
+ expect(Array.isArray(wrapped)).toBe(true);
141
+ expect(wrapped).toHaveLength(2);
142
+ expect(wrapped[0]).toHaveProperty('name', 'test-tool');
143
+ expect(wrapped[1]).toHaveProperty('name', 'another-tool');
144
+
145
+ // Verify tool was called with the right parameters for each tool
146
+ expect(createOpenAIAgentTool).toHaveBeenCalledTimes(2);
147
+ expect(createOpenAIAgentTool).toHaveBeenCalledWith({
148
+ name: mockTool.slug,
149
+ description: mockTool.description,
150
+ parameters: mockTool.inputParameters,
151
+ execute: expect.any(Function),
152
+ });
153
+ expect(createOpenAIAgentTool).toHaveBeenCalledWith({
154
+ name: anotherTool.slug,
155
+ description: anotherTool.description,
156
+ parameters: anotherTool.inputParameters,
157
+ execute: expect.any(Function),
158
+ });
159
+ });
160
+
161
+ it('should return an empty array for empty tools array', () => {
162
+ const wrapped = provider.wrapTools([], mockExecuteToolFn);
163
+ expect(wrapped).toEqual([]);
164
+ expect(createOpenAIAgentTool).not.toHaveBeenCalled();
165
+ });
166
+ });
167
+
168
+ describe('executeTool', () => {
169
+ it('should execute a tool using the global execute function', async () => {
170
+ const toolSlug = 'test-tool';
171
+ const toolParams = {
172
+ userId: 'test-user',
173
+ arguments: { input: 'test-value' },
174
+ };
175
+
176
+ const result = await provider.executeTool(toolSlug, toolParams);
177
+
178
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(toolSlug, toolParams, undefined);
179
+ expect(result).toEqual({
180
+ data: { result: 'success' },
181
+ error: null,
182
+ successful: true,
183
+ });
184
+ });
185
+
186
+ it('should pass modifiers to the global execute function', async () => {
187
+ const toolSlug = 'test-tool';
188
+ const toolParams = {
189
+ userId: 'test-user',
190
+ arguments: { input: 'test-value' },
191
+ };
192
+
193
+ const modifiers = {
194
+ beforeExecute: vi.fn(params => params),
195
+ afterExecute: vi.fn(response => response),
196
+ };
197
+
198
+ await provider.executeTool(toolSlug, toolParams, modifiers);
199
+
200
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(toolSlug, toolParams, modifiers);
201
+ });
202
+ });
203
+});
packages/providers/openai-agents/tsconfig.json
new
+16
@@ -0,0 +1,16 @@
1
+{
2
+ "extends": "../../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "target": "ESNext",
5
+ "module": "ESNext",
6
+ "declaration": true,
7
+ "declarationDir": "./dist",
8
+ "outDir": "./dist",
9
+ "strict": true,
10
+ "esModuleInterop": true,
11
+ "moduleResolution": "node",
12
+ "skipLibCheck": true,
13
+ "resolveJsonModule": true
14
+ },
15
+ "include": ["src"]
16
+}
packages/providers/openai-agents/tsup.config.ts
new
+10
@@ -0,0 +1,10 @@
1
+import { defineConfig } from 'tsup';
2
+
3
+export default defineConfig({
4
+ entry: ['src/index.ts'],
5
+ format: ['esm', 'cjs'],
6
+ dts: true,
7
+ clean: true,
8
+ minify: false,
9
+ outDir: 'dist',
10
+});
packages/providers/openai/src/OpenAIResponsesProvider.ts
new
+314
@@ -0,0 +1,314 @@
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
+import { OpenAI } from 'openai';
8
+import { BaseNonAgenticProvider, removeNonRequiredProperties } from '@composio/core';
9
+import { Tool, ToolExecuteParams } from '@composio/core';
10
+import { ExecuteToolModifiers } from '@composio/core';
11
+import { ExecuteToolFnOptions } from '@composio/core';
12
+import { Stream } from 'openai/streaming';
13
+
14
+export type OpenAiTool = OpenAI.Responses.FunctionTool;
15
+export type OpenAiToolCollection = Array<OpenAiTool>;
16
+export type OpenAIResponsesProviderOptions = {
17
+ /**
18
+ * Whether to enforce strict parameter validation. Default `false`.
19
+ */
20
+ strict?: boolean;
21
+};
22
+export class OpenAIResponsesProvider extends BaseNonAgenticProvider<
23
+ OpenAiToolCollection,
24
+ OpenAiTool
25
+> {
26
+ readonly name = 'openai';
27
+ private strict: boolean | null;
28
+
29
+ /**
30
+ * Creates a new instance of the OpenAIProvider.
31
+ *
32
+ * This is the default provider for the Composio SDK and is automatically
33
+ * available without additional installation.
34
+ *
35
+ * @param {OpenAIResponsesProviderOptions} [options] - Optional provider options
36
+ * @returns {OpenAIResponsesProvider} The OpenAIResponsesProvider instance
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * // The OpenAIProvider is used by default when initializing Composio
41
+ * const composio = new Composio({
42
+ * apiKey: 'your-api-key'
43
+ * });
44
+ *
45
+ * // You can also explicitly specify it
46
+ * const composio = new Composio({
47
+ * apiKey: 'your-api-key',
48
+ * provider: new OpenAIResponsesProvider({
49
+ * strict: true // Optional, default is false
50
+ * })
51
+ * });
52
+ * ```
53
+ */
54
+ constructor(options?: OpenAIResponsesProviderOptions) {
55
+ super();
56
+ this.strict = options?.strict ?? false;
57
+ }
58
+
59
+ /**
60
+ * Wraps a Composio tool in the OpenAI function calling format.
61
+ *
62
+ * This method transforms a Composio tool definition into the format
63
+ * expected by OpenAI's function calling API.
64
+ *
65
+ * @param tool - The Composio tool to wrap
66
+ * @returns The wrapped tool in OpenAI format
67
+ *
68
+ * @example
69
+ * ```typescript
70
+ * // Wrap a single tool for use with OpenAI
71
+ * const composioTool = {
72
+ * slug: 'SEARCH_TOOL',
73
+ * description: 'Search for information',
74
+ * inputParameters: {
75
+ * type: 'object',
76
+ * properties: {
77
+ * query: { type: 'string' }
78
+ * },
79
+ * required: ['query']
80
+ * }
81
+ * };
82
+ *
83
+ * const openAITool = provider.wrapTool(composioTool);
84
+ * ```
85
+ */
86
+ override wrapTool(tool: Tool): OpenAiTool {
87
+ const inputParams = tool.inputParameters;
88
+
89
+ const parameters =
90
+ this.strict && inputParams?.type === 'object'
91
+ ? removeNonRequiredProperties(
92
+ inputParams as {
93
+ type: 'object';
94
+ properties: Record<string, unknown>;
95
+ required?: string[];
96
+ }
97
+ )
98
+ : (inputParams ?? {});
99
+
100
+ return {
101
+ name: tool.slug,
102
+ description: tool.description,
103
+ parameters,
104
+ strict: this.strict,
105
+ type: 'function',
106
+ };
107
+ }
108
+
109
+ /**
110
+ * Wraps multiple Composio tools in the OpenAI function calling format.
111
+ *
112
+ * This method transforms a list of Composio tools into the format
113
+ * expected by OpenAI's function calling API.
114
+ *
115
+ * @param tools - Array of Composio tools to wrap
116
+ * @returns Array of wrapped tools in OpenAI format
117
+ *
118
+ * @example
119
+ * ```typescript
120
+ * // Wrap multiple tools for use with OpenAI
121
+ * const composioTools = [
122
+ * {
123
+ * slug: 'SEARCH_TOOL',
124
+ * description: 'Search for information',
125
+ * inputParameters: {
126
+ * type: 'object',
127
+ * properties: {
128
+ * query: { type: 'string' }
129
+ * }
130
+ * }
131
+ * },
132
+ * {
133
+ * slug: 'WEATHER_TOOL',
134
+ * description: 'Get weather information',
135
+ * inputParameters: {
136
+ * type: 'object',
137
+ * properties: {
138
+ * location: { type: 'string' }
139
+ * }
140
+ * }
141
+ * }
142
+ * ];
143
+ *
144
+ * const openAITools = provider.wrapTools(composioTools);
145
+ * ```
146
+ */
147
+ override wrapTools = (tools: Tool[]): OpenAiToolCollection => {
148
+ return tools.map(tool => this.wrapTool(tool));
149
+ };
150
+
151
+ /**
152
+ * Executes a tool call from OpenAI's chat completion.
153
+ *
154
+ * This method processes a tool call from OpenAI's chat completion API,
155
+ * executes the corresponding Composio tool, and returns the result.
156
+ *
157
+ * @param {string} userId - The user ID for authentication and tracking
158
+ * @param {OpenAI.ChatCompletionMessageToolCall} tool - The tool call from OpenAI
159
+ * @param {ExecuteToolFnOptions} [options] - Optional execution options
160
+ * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
161
+ * @returns {Promise<string>} The result of the tool call as a JSON string
162
+ *
163
+ * @example
164
+ * ```typescript
165
+ * // Execute a tool call from OpenAI
166
+ * const toolCall = {
167
+ * id: 'call_abc123',
168
+ * type: 'function',
169
+ * function: {
170
+ * name: 'SEARCH_TOOL',
171
+ * arguments: '{"query":"composio documentation"}'
172
+ * }
173
+ * };
174
+ *
175
+ * const result = await provider.executeToolCall(
176
+ * 'user123',
177
+ * toolCall,
178
+ * { connectedAccountId: 'conn_xyz456' }
179
+ * );
180
+ * console.log(JSON.parse(result));
181
+ * ```
182
+ */
183
+ async executeToolCall(
184
+ userId: string,
185
+ tool: OpenAI.Responses.ResponseFunctionToolCall,
186
+ options?: ExecuteToolFnOptions,
187
+ modifiers?: ExecuteToolModifiers
188
+ ): Promise<string> {
189
+ const payload: ToolExecuteParams = {
190
+ arguments: JSON.parse(tool.arguments),
191
+ connectedAccountId: options?.connectedAccountId,
192
+ customAuthParams: options?.customAuthParams,
193
+ userId: userId,
194
+ };
195
+ const result = await this.executeTool(tool.name, payload, modifiers);
196
+ return JSON.stringify(result);
197
+ }
198
+
199
+ /**
200
+ * Handles tool calls from OpenAI's response.
201
+ *
202
+ * This method processes tool calls from an OpenAI response,
203
+ * executes each tool call, and returns the results.
204
+ *
205
+ * @param {string} userId - The user ID for authentication and tracking
206
+ * @param {OpenAI.ChatCompletion} chatCompletion - The response from OpenAI
207
+ * @param {ExecuteToolFnOptions} [options] - Optional execution options
208
+ * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
209
+ * @returns {Promise<string[]>} Array of tool execution results as JSON strings
210
+ *
211
+ * @example
212
+ * ```typescript
213
+ * // Handle tool calls from a response
214
+ * const response = await openai.responses.create({
215
+ * model: 'gpt-4o-2024-11-20',
216
+ * input: 'What is the capital of France?',
217
+ * tools: await composio.tools.get(composioTools)
218
+ * });
219
+ *
220
+ * const inputItems = await composio.provider.handleToolCalls(
221
+ * 'user123',
222
+ * response.output
223
+ * );
224
+ * console.log(inputItems); // Array of tool execution results
225
+ *
226
+ * // Submit tool outputs back to OpenAI
227
+ * const response = await openai.responses.create({
228
+ * model: 'gpt-4o-2024-11-20',
229
+ * input: inputItems,
230
+ * tools: await composio.tools.get(composioTools),
231
+ * });
232
+ * ```
233
+ * ```
234
+ */
235
+ async handleToolCalls(
236
+ userId: string,
237
+ toolCalls: OpenAI.Responses.ResponseOutputItem[],
238
+ options?: ExecuteToolFnOptions,
239
+ modifiers?: ExecuteToolModifiers
240
+ ): Promise<OpenAI.Responses.ResponseInputItem.FunctionCallOutput[]> {
241
+ const toolOutputs: OpenAI.Responses.ResponseInputItem.FunctionCallOutput[] = [];
242
+ for (const output of toolCalls) {
243
+ if (output.type === 'function_call') {
244
+ const tool_call = {
245
+ id: output.id,
246
+ name: output.name,
247
+ arguments: output.arguments,
248
+ } as OpenAI.Responses.ResponseFunctionToolCall;
249
+ try {
250
+ const toolOutput = await this.executeToolCall(userId, tool_call, options, modifiers);
251
+ toolOutputs.push({
252
+ call_id: output.call_id ?? '',
253
+ type: 'function_call_output',
254
+ output: toolOutput,
255
+ // id: output.id ?? '',
256
+ status: 'completed',
257
+ });
258
+ } catch (error) {
259
+ toolOutputs.push({
260
+ call_id: output.call_id ?? '',
261
+ type: 'function_call_output',
262
+ output: error instanceof Error ? error.message : 'Unknown error',
263
+ // id: output.id ?? '',
264
+ status: 'incomplete',
265
+ });
266
+ }
267
+ }
268
+ }
269
+ return toolOutputs;
270
+ }
271
+
272
+ /**
273
+ * Handles all the tool calls from the OpenAI Responses API.
274
+ *
275
+ * This method processes tool calls from an OpenAI Responses request,
276
+ * executes each tool call, and returns the tool outputs for submission.
277
+ *
278
+ * @param {string} userId - The user ID for authentication and tracking
279
+ * @param {OpenAI.Responses.Response} response - The Responses request object containing tool calls
280
+ * @param {ExecuteToolFnOptions} [options] - Optional execution options
281
+ * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
282
+ * @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} Array of tool outputs for submission
283
+ *
284
+ * @example
285
+ * ```typescript
286
+ * // Handle tool calls from an OpenAI response
287
+ * const response = await openai.responses.create({
288
+ * model: 'gpt-4o-2024-11-20',
289
+ * input: 'What is the capital of France?',
290
+ * tools: await composio.tools.get(composioTools),
291
+ * tool_choice: 'auto',
292
+ * });
293
+ *
294
+ * const inputItems = await composio.provider.handleResponse('default', response);
295
+ *
296
+ * // Submit tool outputs back to OpenAI
297
+ * const response = await openai.responses.create({
298
+ * model: 'gpt-4o-2024-11-20',
299
+ * input: inputItems,
300
+ * tools: await composio.tools.get(composioTools),
301
+ * });
302
+ * ```
303
+ */
304
+ async handleResponse(
305
+ userId: string,
306
+ response: OpenAI.Responses.Response,
307
+ options?: ExecuteToolFnOptions,
308
+ modifiers?: ExecuteToolModifiers
309
+ ): Promise<OpenAI.Responses.ResponseInputItem.FunctionCallOutput[]> {
310
+ const tool_calls = response.output?.filter(output => output.type === 'function_call') || [];
311
+ const tool_outputs = await this.handleToolCalls(userId, tool_calls, options, modifiers);
312
+ return tool_outputs;
313
+ }
314
+}
packages/providers/openai/src/index.ts
+1
@@ -13,3 +13,4 @@
13
* @module providers/openai
14
*/
15
export { OpenAIProvider } from '@composio/core';
16
+export { OpenAIResponsesProvider } from './OpenAIResponsesProvider';
packages/providers/openai/test/opeanai-responses.test.ts
new
+417
@@ -0,0 +1,417 @@
1
+import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+import { OpenAIResponsesProvider } from '../src';
3
+import { Tool } from '@composio/core';
4
+import { OpenAI } from 'openai';
5
+
6
+// Mock the openai modules
7
+vi.mock('openai', () => {
8
+ return {
9
+ OpenAI: vi.fn().mockImplementation(() => ({
10
+ beta: {
11
+ threads: {
12
+ runs: {
13
+ retrieve: vi.fn().mockImplementation((threadId, runId) => {
14
+ return { id: runId, status: 'completed' };
15
+ }),
16
+ submitToolOutputs: vi.fn().mockImplementation((threadId, runId, options) => {
17
+ return { id: runId, status: 'completed' };
18
+ }),
19
+ },
20
+ },
21
+ },
22
+ })),
23
+ };
24
+});
25
+
26
+// Define interfaces for our OpenAI mocked types
27
+interface MockedOpenAITool {
28
+ type: 'function';
29
+ name: string;
30
+ description?: string;
31
+ parameters?: any;
32
+ strict?: boolean;
33
+}
34
+
35
+describe('OpenAIResponsesProvider', () => {
36
+ let provider: OpenAIResponsesProvider;
37
+ let mockTool: Tool;
38
+ let mockExecuteToolFn: any;
39
+
40
+ beforeEach(() => {
41
+ provider = new OpenAIResponsesProvider();
42
+
43
+ // Mock the global execute tool function
44
+ mockExecuteToolFn = vi.fn().mockResolvedValue({
45
+ data: { result: 'success' },
46
+ error: null,
47
+ successful: true,
48
+ });
49
+ provider._setExecuteToolFn(mockExecuteToolFn);
50
+
51
+ // Create a mock Composio tool
52
+ mockTool = {
53
+ slug: 'test-tool',
54
+ name: 'Test Tool',
55
+ description: 'A tool for testing',
56
+ inputParameters: {
57
+ type: 'object',
58
+ properties: {
59
+ input: {
60
+ type: 'string',
61
+ description: 'Test input',
62
+ },
63
+ },
64
+ required: ['input'],
65
+ },
66
+ tags: [],
67
+ };
68
+
69
+ // Reset mocks before each test
70
+ vi.clearAllMocks();
71
+ });
72
+
73
+ describe('name property', () => {
74
+ it('should have the correct name', () => {
75
+ expect(provider.name).toBe('openai');
76
+ });
77
+ });
78
+
79
+ describe('wrapTool', () => {
80
+ it('should wrap a tool in OpenAI function format', () => {
81
+ const wrapped = provider.wrapTool(mockTool) as MockedOpenAITool;
82
+
83
+ expect(wrapped).toEqual({
84
+ type: 'function',
85
+ name: mockTool.slug,
86
+ description: mockTool.description,
87
+ parameters: mockTool.inputParameters,
88
+ strict: false,
89
+ });
90
+ });
91
+
92
+ it('should handle tools without input parameters', () => {
93
+ const toolWithoutParams: Tool = {
94
+ ...mockTool,
95
+ inputParameters: undefined,
96
+ };
97
+
98
+ const wrapped = provider.wrapTool(toolWithoutParams) as MockedOpenAITool;
99
+
100
+ expect(wrapped).toEqual({
101
+ type: 'function',
102
+ name: toolWithoutParams.slug,
103
+ description: toolWithoutParams.description,
104
+ parameters: {},
105
+ strict: false,
106
+ });
107
+ });
108
+
109
+ it('should respect strict mode when wrapping tools', () => {
110
+ const strictProvider = new OpenAIResponsesProvider({ strict: true });
111
+ const wrapped = strictProvider.wrapTool(mockTool) as MockedOpenAITool;
112
+
113
+ expect(wrapped.strict).toBe(true);
114
+ expect(wrapped.parameters).toEqual(mockTool.inputParameters);
115
+ });
116
+ });
117
+
118
+ describe('wrapTools', () => {
119
+ it('should wrap multiple tools', () => {
120
+ const anotherTool: Tool = {
121
+ ...mockTool,
122
+ slug: 'another-tool',
123
+ name: 'Another Tool',
124
+ };
125
+ const tools = [mockTool, anotherTool];
126
+
127
+ const wrapped = provider.wrapTools(tools);
128
+
129
+ expect(wrapped).toHaveLength(2);
130
+ expect(wrapped[0]).toEqual({
131
+ type: 'function',
132
+ name: mockTool.slug,
133
+ description: mockTool.description,
134
+ parameters: mockTool.inputParameters,
135
+ strict: false,
136
+ });
137
+ expect(wrapped[1]).toEqual({
138
+ type: 'function',
139
+ name: anotherTool.slug,
140
+ description: anotherTool.description,
141
+ parameters: anotherTool.inputParameters,
142
+ strict: false,
143
+ });
144
+ });
145
+
146
+ it('should return an empty array for empty tools array', () => {
147
+ const wrapped = provider.wrapTools([]);
148
+ expect(wrapped).toEqual([]);
149
+ });
150
+ });
151
+
152
+ describe('executeToolCall', () => {
153
+ it('should execute a tool call and return the result as string', async () => {
154
+ const userId = 'test-user';
155
+ const toolCall = {
156
+ id: 'call-123',
157
+ type: 'function',
158
+ name: 'test-tool',
159
+ arguments: JSON.stringify({ input: 'test-value' }),
160
+ call_id: 'call-123',
161
+ } as unknown as OpenAI.Responses.ResponseFunctionToolCall;
162
+
163
+ const result = await provider.executeToolCall(userId, toolCall);
164
+
165
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(
166
+ 'test-tool',
167
+ {
168
+ arguments: { input: 'test-value' },
169
+ userId: 'test-user',
170
+ connectedAccountId: undefined,
171
+ customAuthParams: undefined,
172
+ },
173
+ undefined
174
+ );
175
+ expect(result).toBe(
176
+ JSON.stringify({
177
+ data: { result: 'success' },
178
+ error: null,
179
+ successful: true,
180
+ })
181
+ );
182
+ });
183
+
184
+ it('should pass options to executeTool', async () => {
185
+ const userId = 'test-user';
186
+ const toolCall = {
187
+ id: 'call-123',
188
+ type: 'function',
189
+ name: 'test-tool',
190
+ arguments: JSON.stringify({ input: 'test-value' }),
191
+ call_id: 'call-123',
192
+ } as unknown as OpenAI.Responses.ResponseFunctionToolCall;
193
+
194
+ const options = {
195
+ connectedAccountId: 'conn-123',
196
+ customAuthParams: {
197
+ parameters: [{ name: 'token', value: 'abc123', in: 'header' as const }],
198
+ },
199
+ };
200
+
201
+ const modifiers = {
202
+ beforeExecute: vi.fn(params => params),
203
+ afterExecute: vi.fn(response => response),
204
+ };
205
+
206
+ await provider.executeToolCall(userId, toolCall, options, modifiers);
207
+
208
+ expect(mockExecuteToolFn).toHaveBeenCalledWith(
209
+ 'test-tool',
210
+ {
211
+ arguments: { input: 'test-value' },
212
+ userId: 'test-user',
213
+ connectedAccountId: 'conn-123',
214
+ customAuthParams: options.customAuthParams,
215
+ },
216
+ modifiers
217
+ );
218
+ });
219
+ });
220
+
221
+ describe('handleToolCalls', () => {
222
+ it('should handle tool calls from OpenAI response', async () => {
223
+ const userId = 'test-user';
224
+ const toolCalls = [
225
+ {
226
+ id: 'call-123',
227
+ type: 'function_call',
228
+ name: 'test-tool',
229
+ arguments: JSON.stringify({ input: 'test-value' }),
230
+ call_id: 'call-123',
231
+ },
232
+ ] as OpenAI.Responses.ResponseOutputItem[];
233
+
234
+ const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');
235
+ executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
236
+
237
+ const results = await provider.handleToolCalls(userId, toolCalls);
238
+
239
+ expect(executeToolCallSpy).toHaveBeenCalledWith(
240
+ userId,
241
+ {
242
+ id: 'call-123',
243
+ name: 'test-tool',
244
+ arguments: JSON.stringify({ input: 'test-value' }),
245
+ },
246
+ undefined,
247
+ undefined
248
+ );
249
+ expect(results).toEqual([
250
+ {
251
+ call_id: 'call-123',
252
+ type: 'function_call_output',
253
+ output: JSON.stringify({ result: 'success' }),
254
+ status: 'completed',
255
+ },
256
+ ]);
257
+ });
258
+
259
+ it('should handle errors during tool execution', async () => {
260
+ const userId = 'test-user';
261
+ const toolCalls = [
262
+ {
263
+ id: 'call-123',
264
+ type: 'function_call',
265
+ name: 'test-tool',
266
+ arguments: JSON.stringify({ input: 'test-value' }),
267
+ call_id: 'call-123',
268
+ },
269
+ ] as OpenAI.Responses.ResponseOutputItem[];
270
+
271
+ const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');
272
+ executeToolCallSpy.mockRejectedValue(new Error('Tool execution failed'));
273
+
274
+ const results = await provider.handleToolCalls(userId, toolCalls);
275
+
276
+ expect(results).toEqual([
277
+ {
278
+ call_id: 'call-123',
279
+ type: 'function_call_output',
280
+ output: 'Tool execution failed',
281
+ status: 'incomplete',
282
+ },
283
+ ]);
284
+ });
285
+
286
+ it('should handle multiple tool calls', async () => {
287
+ const userId = 'test-user';
288
+ const toolCalls = [
289
+ {
290
+ id: 'call-123',
291
+ type: 'function_call',
292
+ name: 'test-tool-1',
293
+ arguments: JSON.stringify({ input: 'test-value-1' }),
294
+ call_id: 'call-123',
295
+ },
296
+ {
297
+ id: 'call-456',
298
+ type: 'function_call',
299
+ name: 'test-tool-2',
300
+ arguments: JSON.stringify({ input: 'test-value-2' }),
301
+ call_id: 'call-456',
302
+ },
303
+ ] as OpenAI.Responses.ResponseOutputItem[];
304
+
305
+ const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');
306
+ executeToolCallSpy
307
+ .mockResolvedValueOnce(JSON.stringify({ result: 'success-1' }))
308
+ .mockResolvedValueOnce(JSON.stringify({ result: 'success-2' }));
309
+
310
+ const results = await provider.handleToolCalls(userId, toolCalls);
311
+
312
+ expect(executeToolCallSpy).toHaveBeenCalledTimes(2);
313
+ expect(results).toEqual([
314
+ {
315
+ call_id: 'call-123',
316
+ type: 'function_call_output',
317
+ output: JSON.stringify({ result: 'success-1' }),
318
+ status: 'completed',
319
+ },
320
+ {
321
+ call_id: 'call-456',
322
+ type: 'function_call_output',
323
+ output: JSON.stringify({ result: 'success-2' }),
324
+ status: 'completed',
325
+ },
326
+ ]);
327
+ });
328
+ });
329
+
330
+ describe('handleResponse', () => {
331
+ it('should handle OpenAI response with tool calls', async () => {
332
+ const userId = 'test-user';
333
+ const response = {
334
+ id: 'response-123',
335
+ created_at: new Date().toISOString(),
336
+ output: [
337
+ {
338
+ id: 'call-123',
339
+ type: 'function_call',
340
+ name: 'test-tool',
341
+ arguments: JSON.stringify({ input: 'test-value' }),
342
+ call_id: 'call-123',
343
+ },
344
+ ],
345
+ output_text: 'Test output',
346
+ error: null,
347
+ status: 'completed',
348
+ } as unknown as OpenAI.Responses.Response;
349
+
350
+ const handleToolCallsSpy = vi.spyOn(provider, 'handleToolCalls');
351
+ handleToolCallsSpy.mockResolvedValue([
352
+ {
353
+ call_id: 'call-123',
354
+ type: 'function_call_output',
355
+ output: JSON.stringify({ result: 'success' }),
356
+ status: 'completed',
357
+ },
358
+ ]);
359
+
360
+ const results = await provider.handleResponse(userId, response);
361
+
362
+ expect(handleToolCallsSpy).toHaveBeenCalledWith(
363
+ userId,
364
+ response.output,
365
+ undefined,
366
+ undefined
367
+ );
368
+ expect(results).toEqual([
369
+ {
370
+ call_id: 'call-123',
371
+ type: 'function_call_output',
372
+ output: JSON.stringify({ result: 'success' }),
373
+ status: 'completed',
374
+ },
375
+ ]);
376
+ });
377
+
378
+ it('should handle OpenAI response without tool calls', async () => {
379
+ const userId = 'test-user';
380
+ const response = {
381
+ id: 'response-123',
382
+ created_at: new Date().toISOString(),
383
+ output: [],
384
+ output_text: 'Test output',
385
+ error: null,
386
+ status: 'completed',
387
+ } as unknown as OpenAI.Responses.Response;
388
+
389
+ const handleToolCallsSpy = vi.spyOn(provider, 'handleToolCalls');
390
+ handleToolCallsSpy.mockResolvedValue([]);
391
+
392
+ const results = await provider.handleResponse(userId, response);
393
+
394
+ expect(handleToolCallsSpy).toHaveBeenCalledWith(userId, [], undefined, undefined);
395
+ expect(results).toEqual([]);
396
+ });
397
+
398
+ it('should handle OpenAI response with undefined output', async () => {
399
+ const userId = 'test-user';
400
+ const response = {
401
+ id: 'response-123',
402
+ created_at: new Date().toISOString(),
403
+ output_text: 'Test output',
404
+ error: null,
405
+ status: 'completed',
406
+ } as unknown as OpenAI.Responses.Response;
407
+
408
+ const handleToolCallsSpy = vi.spyOn(provider, 'handleToolCalls');
409
+ handleToolCallsSpy.mockResolvedValue([]);
410
+
411
+ const results = await provider.handleResponse(userId, response);
412
+
413
+ expect(handleToolCallsSpy).toHaveBeenCalledWith(userId, [], undefined, undefined);
414
+ expect(results).toEqual([]);
415
+ });
416
+ });
417
+});
packages/providers/vercel/src/index.ts
+20
-20
@@ -20,21 +20,21 @@ export class VercelProvider extends BaseAgenticProvider<VercelToolCollection, Ve
20
21
/**
22
* Creates a new instance of the VercelProvider.
23
- *
23
+ *
24
* This provider enables integration with the Vercel AI SDK,
25
* allowing Composio tools to be used with Vercel AI applications.
26
- *
26
+ *
27
* @example
28
* ```typescript
29
* // Initialize the Vercel provider
30
* const provider = new VercelProvider();
31
- *
31
+ *
32
* // Use with Composio
33
* const composio = new Composio({
34
* apiKey: 'your-api-key',
35
* provider: new VercelProvider()
36
* });
37
- *
37
+ *
38
* // Use the provider to wrap tools for Vercel AI SDK
39
* const vercelTools = provider.wrapTools(composioTools, composio.tools.execute);
40
* ```
@@ -45,14 +45,14 @@ export class VercelProvider extends BaseAgenticProvider<VercelToolCollection, Ve
45
46
/**
47
* Wraps a Composio tool in a Vercel AI SDK tool format.
48
- *
48
+ *
49
* This method transforms a Composio tool definition into the format
50
* expected by Vercel's AI SDK for function calling.
51
- *
51
+ *
52
* @param {ComposioTool} composioTool - The Composio tool to wrap
53
* @param {ExecuteToolFn} executeTool - Function to execute the tool
54
* @returns {VercelTool} The wrapped Vercel tool
55
- *
55
+ *
56
* @example
57
* ```typescript
58
* // Wrap a single tool for use with Vercel AI SDK
@@ -67,27 +67,27 @@ export class VercelProvider extends BaseAgenticProvider<VercelToolCollection, Ve
67
* required: ['query']
68
* }
69
* };
70
- *
70
+ *
71
* // Create a Vercel tool using the provider
72
* const vercelTool = provider.wrapTool(
73
* composioTool,
74
* composio.tools.execute
75
* );
76
- *
76
+ *
77
* // Use with Vercel AI SDK
78
* import { StreamingTextResponse, Message } from 'ai';
79
* import { OpenAI } from 'openai';
80
- *
80
+ *
81
* export async function POST(req: Request) {
82
* const { messages } = await req.json();
83
* const openai = new OpenAI();
84
- *
84
+ *
85
* const response = await openai.chat.completions.create({
86
* model: 'gpt-4',
87
* messages,
88
* tools: [vercelTool]
89
* });
90
- *
90
+ *
91
* return new StreamingTextResponse(response.choices[0].message);
92
* }
93
* ```
@@ -105,15 +105,15 @@ export class VercelProvider extends BaseAgenticProvider<VercelToolCollection, Ve
105
106
/**
107
* Wraps a list of Composio tools as a Vercel AI SDK tool collection.
108
- *
108
+ *
109
* This method transforms multiple Composio tool definitions into the format
110
* expected by Vercel's AI SDK for function calling, organizing them
111
* into a dictionary keyed by tool slug.
112
- *
112
+ *
113
* @param {ComposioTool[]} tools - Array of Composio tools to wrap
114
* @param {ExecuteToolFn} executeTool - Function to execute the tools
115
* @returns {VercelToolCollection} Dictionary of wrapped tools in Vercel AI SDK format
116
- *
116
+ *
117
* @example
118
* ```typescript
119
* // Wrap multiple tools for use with Vercel AI SDK
@@ -141,27 +141,27 @@ export class VercelProvider extends BaseAgenticProvider<VercelToolCollection, Ve
141
* }
142
* }
143
* ];
144
- *
144
+ *
145
* // Create Vercel tools using the provider
146
* const vercelTools = provider.wrapTools(
147
* composioTools,
148
* composio.tools.execute
149
* );
150
- *
150
+ *
151
* // Use with Vercel AI SDK in a Next.js API route
152
* import { StreamingTextResponse } from 'ai';
153
* import { OpenAI } from 'openai';
154
- *
154
+ *
155
* export async function POST(req: Request) {
156
* const { messages } = await req.json();
157
* const openai = new OpenAI();
158
- *
158
+ *
159
* const response = await openai.chat.completions.create({
160
* model: 'gpt-4',
161
* messages,
162
* tools: Object.values(vercelTools)
163
* });
164
- *
164
+ *
165
* return new StreamingTextResponse(response.choices[0].message);
166
* }
167
* ```
pnpm-lock.yaml
+129
-41
@@ -248,6 +248,15 @@ importers:
248
'@composio/core':
249
specifier: workspace:*
250
version: link:../../packages/core
251
+ '@composio/openai':
252
+ specifier: workspace:^
253
+ version: link:../../packages/providers/openai
254
+ '@composio/openai-agents':
255
+ specifier: workspace:^
256
+ version: link:../../packages/providers/openai-agents
257
+ '@openai/agents':
258
+ specifier: ^0.0.7
259
+ version: 0.0.7(ws@8.18.2)(zod@3.25.62)
260
dotenv:
261
specifier: ^16.4.1
262
version: 16.5.0
@@ -430,8 +439,8 @@ importers:
439
specifier: 0.1.0-alpha.22
440
version: 0.1.0-alpha.22
441
'@composio/json-schema-to-zod':
433
- specifier: 0.1.6
434
- version: 0.1.6
442
+ specifier: 0.1.9
443
+ version: 0.1.9
444
chalk:
445
specifier: ^5.4.1
446
version: 5.4.1
@@ -550,7 +559,7 @@ importers:
559
dependencies:
560
'@langchain/core':
561
specifier: ^0.3.44
553
- version: 0.3.58(openai@4.104.0(zod@3.25.62))
562
+ version: 0.3.58(openai@5.3.0(ws@8.18.2)(zod@3.25.62))
563
devDependencies:
564
'@composio/core':
565
specifier: workspace:*
@@ -603,6 +612,25 @@ importers:
612
specifier: ^3.1.4
613
version: 3.2.3(@types/node@24.0.1)(@vitest/ui@3.2.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
614
615
+ packages/providers/openai-agents:
616
+ dependencies:
617
+ '@openai/agents':
618
+ specifier: ^0.0.7
619
+ version: 0.0.7(ws@8.18.2)(zod@3.25.62)
620
+ devDependencies:
621
+ '@composio/core':
622
+ specifier: workspace:*
623
+ version: link:../../core
624
+ tsup:
625
+ specifier: ^8.4.0
626
+ version: 8.5.0(jiti@1.21.7)(postcss@8.5.5)(tsx@4.20.1)(typescript@5.8.3)(yaml@2.8.0)
627
+ typescript:
628
+ specifier: ^5.8.3
629
+ version: 5.8.3
630
+ vitest:
631
+ specifier: ^3.1.4
632
+ version: 3.2.3(@types/node@24.0.1)(@vitest/ui@3.2.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
633
+
634
packages/providers/vercel:
635
dependencies:
636
ai:
@@ -876,8 +904,8 @@ packages:
904
'@composio/client@0.1.0-alpha.22':
905
resolution: {integrity: sha512-b9KCO5gy0EsCG+nXikOdm17PiZZ85rw3vwu9aNRIse9rEj2FA1SScpP+P9GN4G0lQHl+QPyDuVvGa6U9AATFeg==}
906
879
- '@composio/json-schema-to-zod@0.1.6':
880
- resolution: {integrity: sha512-Eso0rvvdCAxgcjejXXdyJsG4jB3ScUaxkrMaytG4B9Y6uwKJ/uxFrzWqRcwMl5wwQ7nd1vtpJUW/nzr8iRcQMg==}
907
+ '@composio/json-schema-to-zod@0.1.9':
908
+ resolution: {integrity: sha512-uDOAPPkaMWM2DJLCFCW6/rxTgair6EmQ4Ojo6RDayzIl2BRUro0wGkpof4Za8sJPrmdTfSqteRMDy46xPnOYhw==}
909
910
'@esbuild/aix-ppc64@0.25.5':
911
resolution: {integrity: sha512-9o3TMmpmftaCMepOdA5k/yDw8SfInyzWWTjYTFCX3kPSDJMROQTb8jg+h9Cnwnmm1vOzvxN7gIfB5V2ewpjtGA==}
@@ -1208,6 +1236,23 @@ packages:
1236
resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==}
1237
engines: {node: '>= 8'}
1238
1239
+ '@openai/agents-core@0.0.7':
1240
+ resolution: {integrity: sha512-qbJ0w20hTMUJM97q9aGWchr7kyNo35emvjKiVjCW/grR4sMJo1fLia4bE52tjCQGo8EZJBJ9bkjXFSqETjdJYw==}
1241
+ peerDependencies:
1242
+ zod: ^3.25.40
1243
+ peerDependenciesMeta:
1244
+ zod:
1245
+ optional: true
1246
+
1247
+ '@openai/agents-openai@0.0.7':
1248
+ resolution: {integrity: sha512-bWlJUZ6VutBnuESd74i9ttpIsfbw9kuH6mhHhN5bNgUjmbQfxM+2aUBfyxXGzr4mEvBkAuKiyAs3DX1shqOBdQ==}
1249
+
1250
+ '@openai/agents-realtime@0.0.7':
1251
+ resolution: {integrity: sha512-ndPVQpOIX0J+C5wYo+YUb68q4zrXTIbQH/VS24qSIo9fxJokSxwS5P5hNSxDrdQ3+UlYyx/s1Xu6zRCE11H63Q==}
1252
+
1253
+ '@openai/agents@0.0.7':
1254
+ resolution: {integrity: sha512-qDQn7f33fCySEuEVP+PIpBASmD5bjxhzSglzJ3Z21JcRbLq+hxyBz6hpJy6sa0XOSgHh50u2nlsz+rogTizdew==}
1255
+
1256
'@opentelemetry/api-logs@0.201.1':
1257
resolution: {integrity: sha512-IxcFDP1IGMDemVFG2by/AMK+/o6EuBQ8idUq3xZ6MxgQGeumYZuX5OwR0h9HuvcUc/JPjQGfU5OHKIKYDJcXeA==}
1258
engines: {node: '>=8.0.0'}
@@ -2142,6 +2187,9 @@ packages:
2187
'@types/uuid@9.0.8':
2188
resolution: {integrity: sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==}
2189
2190
+ '@types/ws@8.18.1':
2191
+ resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
2192
+
2193
'@types/yaml@1.9.7':
2194
resolution: {integrity: sha512-8WMXRDD1D+wCohjfslHDgICd2JtMATZU8CkhH8LVJqcJs6dyYj5TGptzP8wApbmEullGBSsCEzzap73DQ1HJaA==}
2195
deprecated: This is a stub types definition. yaml provides its own type definitions, so you do not need this installed.
@@ -3585,6 +3633,18 @@ packages:
3633
zod:
3634
optional: true
3635
3636
+ openai@5.3.0:
3637
+ resolution: {integrity: sha512-VIKmoF7y4oJCDOwP/oHXGzM69+x0dpGFmN9QmYO+uPbLFOmmnwO+x1GbsgUtI+6oraxomGZ566Y421oYVu191w==}
3638
+ hasBin: true
3639
+ peerDependencies:
3640
+ ws: ^8.18.0
3641
+ zod: ^3.23.8
3642
+ peerDependenciesMeta:
3643
+ ws:
3644
+ optional: true
3645
+ zod:
3646
+ optional: true
3647
+
3648
openapi-types@12.1.3:
3649
resolution: {integrity: sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==}
3650
@@ -5269,7 +5329,7 @@ snapshots:
5329
5330
'@composio/client@0.1.0-alpha.22': {}
5331
5272
- '@composio/json-schema-to-zod@0.1.6':
5332
+ '@composio/json-schema-to-zod@0.1.9':
5333
dependencies:
5334
'@types/json-schema': 7.0.15
5335
zod: 3.25.62
@@ -5490,14 +5550,14 @@ snapshots:
5550
transitivePeerDependencies:
5551
- openai
5552
5493
- '@langchain/core@0.3.58(openai@4.104.0(zod@3.25.62))':
5553
+ '@langchain/core@0.3.58(openai@5.3.0(ws@8.18.2)(zod@3.25.62))':
5554
dependencies:
5555
'@cfworker/json-schema': 4.1.1
5556
ansi-styles: 5.2.0
5557
camelcase: 6.3.0
5558
decamelize: 1.2.0
5559
js-tiktoken: 1.0.20
5500
- langsmith: 0.3.31(openai@4.104.0(zod@3.25.62))
5560
+ langsmith: 0.3.31(openai@5.3.0(ws@8.18.2)(zod@3.25.62))
5561
mustache: 4.2.0
5562
p-queue: 6.6.2
5563
p-retry: 4.6.2
@@ -5648,6 +5708,56 @@ snapshots:
5708
'@nodelib/fs.scandir': 2.1.5
5709
fastq: 1.19.1
5710
5711
+ '@openai/agents-core@0.0.7(ws@8.18.2)(zod@3.25.62)':
5712
+ dependencies:
5713
+ '@openai/zod': zod@3.25.62
5714
+ debug: 4.4.1
5715
+ openai: 5.3.0(ws@8.18.2)(zod@3.25.62)
5716
+ optionalDependencies:
5717
+ '@modelcontextprotocol/sdk': 1.12.1
5718
+ zod: 3.25.62
5719
+ transitivePeerDependencies:
5720
+ - supports-color
5721
+ - ws
5722
+
5723
+ '@openai/agents-openai@0.0.7(ws@8.18.2)(zod@3.25.62)':
5724
+ dependencies:
5725
+ '@openai/agents-core': 0.0.7(ws@8.18.2)(zod@3.25.62)
5726
+ '@openai/zod': zod@3.25.62
5727
+ debug: 4.4.1
5728
+ openai: 5.3.0(ws@8.18.2)(zod@3.25.62)
5729
+ transitivePeerDependencies:
5730
+ - supports-color
5731
+ - ws
5732
+ - zod
5733
+
5734
+ '@openai/agents-realtime@0.0.7(zod@3.25.62)':
5735
+ dependencies:
5736
+ '@openai/agents-core': 0.0.7(ws@8.18.2)(zod@3.25.62)
5737
+ '@openai/zod': zod@3.25.62
5738
+ '@types/ws': 8.18.1
5739
+ debug: 4.4.1
5740
+ ws: 8.18.2
5741
+ transitivePeerDependencies:
5742
+ - bufferutil
5743
+ - supports-color
5744
+ - utf-8-validate
5745
+ - zod
5746
+
5747
+ '@openai/agents@0.0.7(ws@8.18.2)(zod@3.25.62)':
5748
+ dependencies:
5749
+ '@openai/agents-core': 0.0.7(ws@8.18.2)(zod@3.25.62)
5750
+ '@openai/agents-openai': 0.0.7(ws@8.18.2)(zod@3.25.62)
5751
+ '@openai/agents-realtime': 0.0.7(zod@3.25.62)
5752
+ debug: 4.4.1
5753
+ openai: 5.3.0(ws@8.18.2)(zod@3.25.62)
5754
+ transitivePeerDependencies:
5755
+ - bufferutil
5756
+ - supports-color
5757
+ - utf-8-validate
5758
+ - ws
5759
+ - zod
5760
+
5761
'@opentelemetry/api-logs@0.201.1':
5762
dependencies:
5763
'@opentelemetry/api': 1.9.0
@@ -6890,6 +7000,10 @@ snapshots:
7000
7001
'@types/uuid@9.0.8': {}
7002
7003
+ '@types/ws@8.18.1':
7004
+ dependencies:
7005
+ '@types/node': 24.0.1
7006
+
7007
'@types/yaml@1.9.7':
7008
dependencies:
7009
yaml: 2.8.0
@@ -6994,14 +7108,6 @@ snapshots:
7108
chai: 5.2.0
7109
tinyrainbow: 2.0.0
7110
6997
- '@vitest/mocker@3.2.3(vite@6.3.5(@types/node@20.19.0)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))':
6998
- dependencies:
6999
- '@vitest/spy': 3.2.3
7000
- estree-walker: 3.0.3
7001
- magic-string: 0.30.17
7002
- optionalDependencies:
7003
- vite: 6.3.5(@types/node@20.19.0)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
7004
-
7111
'@vitest/mocker@3.2.3(vite@6.3.5(@types/node@22.15.31)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))':
7112
dependencies:
7113
'@vitest/spy': 3.2.3
@@ -7010,14 +7116,6 @@ snapshots:
7116
optionalDependencies:
7117
vite: 6.3.5(@types/node@22.15.31)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
7118
7013
- '@vitest/mocker@3.2.3(vite@6.3.5(@types/node@24.0.1)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))':
7014
- dependencies:
7015
- '@vitest/spy': 3.2.3
7016
- estree-walker: 3.0.3
7017
- magic-string: 0.30.17
7018
- optionalDependencies:
7019
- vite: 6.3.5(@types/node@24.0.1)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
7020
-
7119
'@vitest/pretty-format@3.2.3':
7120
dependencies:
7121
tinyrainbow: 2.0.0
@@ -7047,7 +7145,7 @@ snapshots:
7145
sirv: 3.0.1
7146
tinyglobby: 0.2.14
7147
tinyrainbow: 2.0.0
7050
- vitest: 3.2.3(@types/node@24.0.1)(@vitest/ui@3.2.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
7148
+ vitest: 3.2.3(@types/node@22.15.31)(@vitest/ui@3.2.3)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0)
7149
7150
'@vitest/utils@3.2.3':
7151
dependencies:
@@ -8161,7 +8259,7 @@ snapshots:
8259
optionalDependencies:
8260
openai: 4.104.0(ws@8.18.2)(zod@3.25.32)
8261
8164
- langsmith@0.3.31(openai@4.104.0(zod@3.25.62)):
8262
+ langsmith@0.3.31(openai@5.3.0(ws@8.18.2)(zod@3.25.62)):
8263
dependencies:
8264
'@types/uuid': 10.0.0
8265
chalk: 4.1.2
@@ -8171,7 +8269,7 @@ snapshots:
8269
semver: 7.7.2
8270
uuid: 10.0.0
8271
optionalDependencies:
8174
- openai: 4.104.0(zod@3.25.62)
8272
+ openai: 5.3.0(ws@8.18.2)(zod@3.25.62)
8273
8274
levn@0.4.1:
8275
dependencies:
@@ -8419,20 +8517,10 @@ snapshots:
8517
transitivePeerDependencies:
8518
- encoding
8519
8422
- openai@4.104.0(zod@3.25.62):
8423
- dependencies:
8424
- '@types/node': 18.19.111
8425
- '@types/node-fetch': 2.6.12
8426
- abort-controller: 3.0.0
8427
- agentkeepalive: 4.6.0
8428
- form-data-encoder: 1.7.2
8429
- formdata-node: 4.4.1
8430
- node-fetch: 2.7.0
8520
+ openai@5.3.0(ws@8.18.2)(zod@3.25.62):
8521
optionalDependencies:
8522
+ ws: 8.18.2
8523
zod: 3.25.62
8433
- transitivePeerDependencies:
8434
- - encoding
8435
- optional: true
8524
8525
openapi-types@12.1.3: {}
8526
@@ -9418,7 +9506,7 @@ snapshots:
9506
dependencies:
9507
'@types/chai': 5.2.2
9508
'@vitest/expect': 3.2.3
9421
- '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@20.19.0)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))
9509
+ '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@22.15.31)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))
9510
'@vitest/pretty-format': 3.2.3
9511
'@vitest/runner': 3.2.3
9512
'@vitest/snapshot': 3.2.3
@@ -9502,7 +9590,7 @@ snapshots:
9590
dependencies:
9591
'@types/chai': 5.2.2
9592
'@vitest/expect': 3.2.3
9505
- '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@24.0.1)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))
9593
+ '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@22.15.31)(jiti@1.21.7)(tsx@4.20.1)(yaml@2.8.0))
9594
'@vitest/pretty-format': 3.2.3
9595
'@vitest/runner': 3.2.3
9596
'@vitest/snapshot': 3.2.3
ts/docs/api/tools.md
-12
@@ -196,7 +196,6 @@ type ToolkitsOnlyParams = {
196
cursor?: string; // Pagination cursor
197
limit?: number; // Limit the number of results
198
search?: never; // Cannot be used with important flag,
199
- strict?: boolean; // Remove non-required properties from input/output parameters
199
};
200
201
type ToolkitSearchOnlyParams = {
@@ -206,7 +205,6 @@ type ToolkitSearchOnlyParams = {
205
cursor?: string; // Pagination cursor
206
limit?: number; // Limit the number of results
207
search: string; // Search term
209
- strict?: boolean; // Remove non-required properties from input/output parameters
208
};
209
210
type ToolListParams = ToolsOnlyParams | ToolkitsOnlyParams | ToolkitSearchOnlyParams;
@@ -218,8 +216,6 @@ Note: The parameters are organized into three mutually exclusive combinations:
216
2. Using `toolkits` with optional `important` flag to fetch tools from specific toolkits
217
3. Using `search` with optional `toolkits` to search for tools by name/description
218
221
-The `strict` parameter is a special flag that can be used with any of the above combinations. When set to `true`, it removes all non-required properties from both input and output parameters of the tools. This is particularly useful when working with providers that have strict parameter requirements, such as VercelAISDK, OpenAI, [where all fields must be marked as required.](https://platform.openai.com/docs/guides/function-calling#strict-mode)
222
-
219
Examples:
220
221
```typescript
@@ -228,14 +224,6 @@ const specificTools = await composio.tools.get('default', {
224
tools: ['GITHUB_GET_REPO', 'GITHUB_LIST_ISSUES'],
225
});
226
231
-// Get all tools from specific toolkits with strict mode enabled
232
-const toolkitTools = await composio.tools.get('default', {
233
- toolkits: ['github', 'gitlab'],
234
- important: true,
235
- limit: 10,
236
- strict: true, // This will remove all non-required properties from tool parameters
237
-});
238
-
227
// Search for tools across all or specific toolkits
228
const searchResults = await composio.tools.get('default', {
229
search: 'repository',