@devries-cameron20 / composio Mirror · read-only / commits / e182bc83c
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, 11:00 UTC

chore(openai): remove the OpenAI Assistants API helpers (#4677)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/4675 - removes `handleAssistantMessage`, `waitAndHandleAssistantToolCalls`, and `waitAndHandleAssistantStreamToolCalls` from the core `OpenAIProvider`, and `handle_assistant_tool_calls` / `wait_and_handle_assistant_tool_calls` from the Python `OpenAIProvider` - OpenAI shut down the Assistants API on August 26, 2026 ([announcement](https://community.openai.com/t/assistants-api-beta-deprecation-august-26-2026-sunset/1354666), [migration guide](https://developers.openai.com/api/docs/assistants/migration)), so these helpers can no longer complete a run - replaces the Assistants section of `ts/docs/api/providers.md` with `OpenAIResponsesProvider`, and moves the Responses example in `ts/docs/providers/openai.md` to `session.tools()` + `handleResponse(session, response)` - fixes the `handleResponse` JSDoc return type, which still named the Assistants `ToolOutput` type - breaking: - the five helpers above are removed; the JSDoc promised removal "in the next major version", but the upstream API no longer exists, so keeping them only preserves calls that fail at runtime - migration: `OpenAIResponsesProvider` (`@composio/openai`, `composio_openai`) with the Responses API; it already accepts a Tool Router session ## Testing - core `vitest run test/provider` (40 pass), `@composio/openai` `vitest run` (37 pass), core `tsc --noEmit` clean, oxlint clean - Python: ruff and mypy clean on `_openai.py`; `pytest tests/test_provider.py -k openai` (7 pass) - `rg` finds no remaining Assistants API references outside generated `docs/content/reference`

Alberto Schiabel committed Sep 28, 2026 at 18:42 UTC e182bc83c32ed46e561ef63a1ee4d3d7a1aed1f9
8 files changed +31 -846
.changeset/remove-openai-assistants-helpers.md new
+5
@@ -0,0 +1,5 @@
1 +---
2 +'@composio/core': minor
3 +---
4 +
5 +Remove the deprecated OpenAI Assistants API helpers from `OpenAIProvider`: `handleAssistantMessage`, `waitAndHandleAssistantToolCalls`, and `waitAndHandleAssistantStreamToolCalls`. OpenAI shut down the Assistants API on August 26, 2026, so these helpers could no longer complete a run. Use `OpenAIResponsesProvider` from `@composio/openai` with the Responses API instead.
python/composio/core/provider/_openai.py
-56
@@ -4,13 +4,8 @@ OpenAI provider implementation.
4
5 from __future__ import annotations
6
7 -import json
8 -import time
7 import typing as t
8
11 -from openai import Client
12 -from openai.types.beta.thread import Thread
13 -from openai.types.beta.threads.run import Run
9 from openai.types.chat.chat_completion import ChatCompletion
10 from openai.types.chat.chat_completion_message_tool_call import (
11 ChatCompletionMessageToolCall,
@@ -157,54 +152,3 @@ class OpenAIProvider(
152 )
153 outputs.append(result)
154 return outputs
160 -
161 - def handle_assistant_tool_calls(
162 - self,
163 - user_id: str,
164 - run: Run,
165 - ) -> t.List:
166 - """Wait and handle assistant function calls"""
167 - tool_outputs: list[dict] = []
168 - if run.required_action is None:
169 - return tool_outputs
170 -
171 - for tool_call in run.required_action.submit_tool_outputs.tool_calls:
172 - tool_outputs.append(
173 - {
174 - "tool_call_id": tool_call.id,
175 - "output": json.dumps(
176 - self.execute_tool_call(
177 - tool_call=t.cast(ChatCompletionMessageToolCall, tool_call),
178 - user_id=user_id,
179 - )
180 - ),
181 - }
182 - )
183 - return tool_outputs
184 -
185 - def wait_and_handle_assistant_tool_calls(
186 - self,
187 - user_id: str,
188 - client: Client,
189 - run: Run,
190 - thread: Thread,
191 - ) -> Run:
192 - """Wait and handle assistant function calls"""
193 - while run.status in ("queued", "in_progress", "requires_action"):
194 - if run.status != "requires_action":
195 - run = client.beta.threads.runs.retrieve(
196 - thread_id=thread.id,
197 - run_id=run.id,
198 - )
199 - time.sleep(0.5)
200 - continue
201 -
202 - run = client.beta.threads.runs.submit_tool_outputs(
203 - thread_id=thread.id,
204 - run_id=run.id,
205 - tool_outputs=self.handle_assistant_tool_calls(
206 - run=run,
207 - user_id=user_id,
208 - ),
209 - )
210 - return run
ts/docs/api/providers.md
+19 -65
@@ -94,7 +94,7 @@ const openaiTools = openaiProvider.wrapTools(composioTools);
94
95 #### executeToolCall(userId, tool, options?, modifiers?)
96
97 -Executes a tool call from an OpenAI assistant.
97 +Executes a tool call from an OpenAI chat completion.
98
99 ```typescript
100 const result = await openaiProvider.executeToolCall(
@@ -134,75 +134,29 @@ const outputs = await openaiProvider.handleToolCalls('user123', chatCompletion);
134
135 **Returns:** Promise<OpenAI.ChatCompletionToolMessageParam[]> - The results of the tool calls
136
137 -> [!WARNING]
138 -> **Deprecated.** OpenAI deprecated the Assistants API, and it shuts down on August 26, 2026. The `handleAssistantMessage`, `waitAndHandleAssistantStreamToolCalls`, and `waitAndHandleAssistantToolCalls` methods below remain in the SDK until then, but new agentic flows should use `OpenAIResponsesProvider` instead — see [the OpenAI provider guide](../providers/openai.md).
137 +### OpenAIResponsesProvider
138
140 -#### handleAssistantMessage(userId, run, options?, modifiers?)
141 -
142 -Handles tool calls from an OpenAI assistant run.
139 +OpenAI shut down the Assistants API on August 26, 2026, and the SDK no longer ships its helpers (`handleAssistantMessage`, `waitAndHandleAssistantToolCalls`, `waitAndHandleAssistantStreamToolCalls`). Use `OpenAIResponsesProvider` from `@composio/openai` with the [Responses API](https://developers.openai.com/api/docs/assistants/migration) instead.
140
141 ```typescript
145 -const toolOutputs = await openaiProvider.handleAssistantMessage('user123', run);
146 -```
147 -
148 -**Parameters:**
149 -
150 -- `userId` (string): The user ID
151 -- `run` (OpenAI.Beta.Threads.Run): The run object containing tool calls
152 -- `options` (ExecuteToolFnOptions): Optional parameters for tool execution
153 -- `modifiers` (ExecuteToolModifiers): Optional modifiers for request/response transformation
154 -
155 -**Returns:** Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]> - The tool outputs
156 -
157 -#### waitAndHandleAssistantStreamToolCalls(userId, client, runStream, thread, options?, modifiers?)
158 -
159 -Waits for and handles tool calls from an OpenAI assistant stream.
160 -
161 -```typescript
162 -for await (const event of openaiProvider.waitAndHandleAssistantStreamToolCalls(
163 - 'user123',
164 - openaiClient,
165 - runStream,
166 - thread
167 -)) {
168 - console.log(event);
169 -}
170 -```
171 -
172 -**Parameters:**
173 -
174 -- `userId` (string): The user ID
175 -- `client` (OpenAI): The OpenAI client
176 -- `runStream` (Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>): The run stream
177 -- `thread` (OpenAI.Beta.Threads.Thread): The thread object
178 -- `options` (ExecuteToolFnOptions): Optional parameters for tool execution
179 -- `modifiers` (ExecuteToolModifiers): Optional modifiers for request/response transformation
180 -
181 -**Returns:** AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown> - Generator of stream events
182 -
183 -#### waitAndHandleAssistantToolCalls(userId, client, run, thread, options?, modifiers?)
184 -
185 -Waits for and handles tool calls from an OpenAI assistant.
186 -
187 -```typescript
188 -const finalRun = await openaiProvider.waitAndHandleAssistantToolCalls(
189 - 'user123',
190 - openaiClient,
191 - run,
192 - thread
193 -);
142 +import { Composio } from '@composio/core';
143 +import { OpenAIResponsesProvider } from '@composio/openai';
144 +import OpenAI from 'openai';
145 +
146 +const openai = new OpenAI();
147 +const composio = new Composio({ provider: new OpenAIResponsesProvider() });
148 +const session = await composio.create('user123');
149 +const tools = await session.tools();
150 +
151 +const response = await openai.responses.create({
152 + model: 'gpt-5',
153 + input: 'Star the composiohq/composio repository on GitHub',
154 + tools,
155 +});
156 +const toolOutputs = await composio.provider.handleResponse(session, response);
157 ```
158
196 -**Parameters:**
197 -
198 -- `userId` (string): The user ID
199 -- `client` (OpenAI): The OpenAI client
200 -- `run` (OpenAI.Beta.Threads.Run): The run object containing tool calls
201 -- `thread` (OpenAI.Beta.Threads.Thread): The thread object
202 -- `options` (ExecuteToolFnOptions): Optional parameters for tool execution
203 -- `modifiers` (ExecuteToolModifiers): Optional modifiers for request/response transformation
204 -
205 -**Returns:** Promise<OpenAI.Beta.Threads.Run> - The final run object
159 +`executeToolCall`, `handleToolCalls`, and `handleResponse` take the session that produced the tools, or a user ID for tools fetched with `tools.get()`. They return `function_call_output` items to send back with `previous_response_id`.
160
161 ## Creating Custom Providers
162
ts/docs/providers/openai.md
+5 -6
@@ -133,7 +133,7 @@ if (completion.choices[0].message.tool_calls) {
133
134 ## Working with OpenAI Responses
135
136 -Use `OpenAIResponsesProvider` for new agentic flows. It formats Composio tools for the Responses API and returns `function_call_output` items that you can pass back with `previous_response_id`.
136 +Use `OpenAIResponsesProvider` for new agentic flows; it replaces the Assistants API, which OpenAI shut down on August 26, 2026. It formats Composio tools for the Responses API and returns `function_call_output` items that you can pass back with `previous_response_id`.
137
138 ```typescript
139 import { Composio } from '@composio/core';
@@ -149,10 +149,9 @@ const openai = new OpenAI({
149 apiKey: 'your-openai-api-key',
150 });
151
152 -// Get GitHub tools
153 -const tools = await composio.tools.get('default', {
154 - toolkits: ['github'],
155 -});
152 +// Create a session for your user
153 +const session = await composio.create('default');
154 +const tools = await session.tools();
155
156 let response = await openai.responses.create({
157 model: 'gpt-5',
@@ -161,7 +160,7 @@ let response = await openai.responses.create({
160 });
161
162 while (response.output.some(item => item.type === 'function_call')) {
164 - const toolOutputs = await composio.provider.handleToolCalls('default', response.output);
163 + const toolOutputs = await composio.provider.handleResponse(session, response);
164 response = await openai.responses.create({
165 model: 'gpt-5',
166 tools,
ts/packages/core/src/provider/OpenAIProvider.ts
-283
@@ -8,10 +8,8 @@
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 { Stream } from 'openai/streaming';
11 import { BaseNonAgenticProvider } from './BaseProvider';
12 import { Tool } from '../types/tool.types';
14 -import logger from '../utils/logger';
13 import { ExecuteToolModifiers } from '../types/modifiers.types';
14 import {
15 ExecuteToolFnOptions,
@@ -296,285 +294,4 @@ export class OpenAIProvider extends BaseNonAgenticProvider<
294 }
295 return outputs;
296 }
299 -
300 - /**
301 - * Handles all the tool calls from the OpenAI Assistant API.
302 - *
303 - * This method processes tool calls from an OpenAI Assistant run,
304 - * executes each tool call, and returns the tool outputs for submission.
305 - *
306 - * @deprecated Assistant API is deprecated, please use responses or chat completions instead. This method will be removed in the next major version.
307 - *
308 - * @param {string} userId - The user ID for authentication and tracking
309 - * @param {OpenAI.Beta.Threads.Run} run - The Assistant run object containing tool calls
310 - * @param {ExecuteToolFnOptions} [options] - Optional execution options
311 - * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
312 - * @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} Array of tool outputs for submission
313 - *
314 - *
315 - * @example
316 - * ```typescript
317 - * // Handle tool calls from an OpenAI Assistant run
318 - * const run = {
319 - * id: 'run_abc123',
320 - * required_action: {
321 - * submit_tool_outputs: {
322 - * tool_calls: [
323 - * {
324 - * id: 'call_xyz789',
325 - * type: 'function',
326 - * function: {
327 - * name: 'SEARCH_TOOL',
328 - * arguments: '{"query":"composio documentation"}'
329 - * }
330 - * }
331 - * ]
332 - * }
333 - * }
334 - * };
335 - *
336 - * const toolOutputs = await provider.handleAssistantMessage(
337 - * 'user123',
338 - * run,
339 - * { connectedAccountId: 'conn_xyz456' }
340 - * );
341 - *
342 - * // Submit tool outputs back to OpenAI
343 - * await openai.beta.threads.runs.submitToolOutputs(
344 - * thread.id,
345 - * run.id,
346 - * { tool_outputs: toolOutputs }
347 - * );
348 - * ```
349 - */
350 - async handleAssistantMessage(
351 - userId: string,
352 - run: OpenAI.Beta.Threads.Run,
353 - options?: ExecuteToolFnOptions,
354 - modifiers?: ExecuteToolModifiers
355 - ) {
356 - const tool_calls = run.required_action?.submit_tool_outputs?.tool_calls || [];
357 - const tool_outputs: Array<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput> =
358 - await Promise.all(
359 - tool_calls.map(async tool_call => {
360 - logger.debug(`Executing tool call: ${tool_call.id}`);
361 -
362 - // Execute each tool call and get the response
363 - const tool_response = await this.executeToolCall(
364 - userId,
365 - tool_call as OpenAI.ChatCompletionMessageFunctionToolCall,
366 - options,
367 - modifiers
368 - );
369 -
370 - logger.debug(`Tool call ${tool_call.id} executed with response: ${tool_response}`);
371 -
372 - return {
373 - tool_call_id: tool_call.id,
374 - output: JSON.stringify(tool_response),
375 - };
376 - })
377 - );
378 - return tool_outputs;
379 - }
380 -
381 - /**
382 - * Waits for the assistant stream and handles the tool calls.
383 - *
384 - * This method processes an OpenAI Assistant stream, handles any tool calls
385 - * that require action, and yields each event from the stream. It's designed
386 - * for streaming Assistant responses while handling tool calls in real-time.
387 - *
388 - * @deprecated Assistant API is deprecated, please use responses or chat completions instead. It will be removed in the next major version.
389 - *
390 - * @param {string} userId - The user ID for authentication and tracking
391 - * @param {OpenAI} client - The OpenAI client instance
392 - * @param {Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>} runStream - The Assistant run stream
393 - * @param {OpenAI.Beta.Threads.Thread} thread - The thread object
394 - * @param {ExecuteToolFnOptions} [options] - Optional execution options
395 - * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
396 - * @returns {AsyncGenerator<OpenAI.Beta.Assistants.AssistantStreamEvent, void, unknown>} Generator yielding stream events
397 - *
398 - *
399 - *
400 - * @example
401 - * ```typescript
402 - * // Process an OpenAI Assistant stream with tool calls
403 - * const thread = await openai.beta.threads.create();
404 - * const runStream = openai.beta.threads.runs.stream(thread.id, {
405 - * assistant_id: 'asst_abc123',
406 - * tools: provider.wrapTools(composioTools)
407 - * });
408 - *
409 - * // Process the stream and handle tool calls
410 - * const streamProcessor = provider.waitAndHandleAssistantStreamToolCalls(
411 - * 'user123',
412 - * openai,
413 - * runStream,
414 - * thread,
415 - * { connectedAccountId: 'conn_xyz456' }
416 - * );
417 - *
418 - * // Consume the stream events
419 - * for await (const event of streamProcessor) {
420 - * if (event.event === 'thread.message.delta') {
421 - * console.log(event.data.delta.content);
422 - * }
423 - * }
424 - * ```
425 - */
426 - async *waitAndHandleAssistantStreamToolCalls(
427 - userId: string,
428 - client: OpenAI,
429 - runStream: Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>,
430 - thread: OpenAI.Beta.Threads.Thread,
431 - options?: ExecuteToolFnOptions,
432 - modifiers?: ExecuteToolModifiers
433 - ) {
434 - // @TODO: Log the run stream
435 - let runId = null;
436 -
437 - // Start processing the runStream events
438 - for await (const event of runStream) {
439 - yield event; // Yield each event from the stream as it arrives
440 -
441 - if (event.event === 'thread.run.created') {
442 - const { id } = event.data;
443 - runId = id;
444 - }
445 -
446 - if (!runId) {
447 - continue;
448 - }
449 -
450 - // Handle the 'requires_action' event
451 - if (event.event === 'thread.run.requires_action') {
452 - const toolOutputs = await this.handleAssistantMessage(
453 - userId,
454 - event.data,
455 - options,
456 - modifiers
457 - );
458 -
459 - // Submit the tool outputs
460 - await client.beta.threads.runs.submitToolOutputs(runId, {
461 - thread_id: thread.id,
462 - tool_outputs: toolOutputs,
463 - });
464 - }
465 -
466 - // Break if the run status becomes inactive
467 - if (
468 - [
469 - 'thread.run.completed',
470 - 'thread.run.failed',
471 - 'thread.run.cancelled',
472 - 'thread.run.expired',
473 - ].includes(event.event)
474 - ) {
475 - break;
476 - }
477 - }
478 -
479 - if (!runId) {
480 - throw new Error('No run ID found');
481 - }
482 -
483 - // Handle any final actions after the stream ends
484 - let finalRun = await client.beta.threads.runs.retrieve(runId, {
485 - thread_id: thread.id,
486 - });
487 -
488 - while (['queued', 'in_progress', 'requires_action'].includes(finalRun.status)) {
489 - if (finalRun.status === 'requires_action') {
490 - const toolOutputs = await this.handleAssistantMessage(userId, finalRun, options, modifiers);
491 -
492 - // Submit tool outputs
493 - finalRun = await client.beta.threads.runs.submitToolOutputs(runId, {
494 - thread_id: thread.id,
495 - tool_outputs: toolOutputs,
496 - });
497 - } else {
498 - // Update the run status
499 - finalRun = await client.beta.threads.runs.retrieve(runId, {
500 - thread_id: thread.id,
501 - });
502 - await new Promise(resolve => setTimeout(resolve, 500)); // Wait before rechecking
503 - }
504 - }
505 - }
506 -
507 - /**
508 - * Waits for the assistant tool calls and handles them.
509 - *
510 - * This method polls an OpenAI Assistant run until it completes or requires action,
511 - * handles any tool calls, and returns the final run object. It's designed for
512 - * non-streaming Assistant interactions.
513 - *
514 - * @deprecated Assistant API is deprecated, please use responses or chat completions instead. It will be removed in the next major version.
515 - *
516 - * @param {string} userId - The user ID for authentication and tracking
517 - * @param {OpenAI} client - The OpenAI client instance
518 - * @param {OpenAI.Beta.Threads.Run} run - The initial run object
519 - * @param {OpenAI.Beta.Threads.Thread} thread - The thread object
520 - * @param {ExecuteToolFnOptions} [options] - Optional execution options
521 - * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
522 - * @returns {Promise<OpenAI.Beta.Threads.Run>} The final run object after completion
523 - *
524 - * @example
525 - * ```typescript
526 - * // Process an OpenAI Assistant run with tool calls
527 - * const thread = await openai.beta.threads.create();
528 - * await openai.beta.threads.messages.create(thread.id, {
529 - * role: 'user',
530 - * content: 'Find information about Composio'
531 - * });
532 - *
533 - * let run = await openai.beta.threads.runs.create(thread.id, {
534 - * assistant_id: 'asst_abc123',
535 - * tools: provider.wrapTools(composioTools)
536 - * });
537 - *
538 - * // Wait for the run to complete, handling any tool calls
539 - * run = await provider.waitAndHandleAssistantToolCalls(
540 - * 'user123',
541 - * openai,
542 - * run,
543 - * thread,
544 - * { connectedAccountId: 'conn_xyz456' }
545 - * );
546 - *
547 - * // Get the final messages after run completion
548 - * const messages = await openai.beta.threads.messages.list(thread.id);
549 - * console.log(messages.data[0].content);
550 - * ```
551 - */
552 - async waitAndHandleAssistantToolCalls(
553 - userId: string,
554 - client: OpenAI,
555 - run: OpenAI.Beta.Threads.Run,
556 - thread: OpenAI.Beta.Threads.Thread,
557 - options?: ExecuteToolFnOptions,
558 - modifiers?: ExecuteToolModifiers
559 - ) {
560 - while (['queued', 'in_progress', 'requires_action'].includes(run.status)) {
561 - // logger.debug(`Current run status: ${run.status}`);
562 - const tool_outputs = await this.handleAssistantMessage(userId, run, options, modifiers);
563 - if (run.status === 'requires_action') {
564 - // logger.debug(
565 - // `Submitting tool outputs for run ID: ${run.id} in thread ID: ${thread.id}`
566 - // );
567 - run = await client.beta.threads.runs.submitToolOutputs(run.id, {
568 - thread_id: thread.id,
569 - tool_outputs: tool_outputs,
570 - });
571 - } else {
572 - run = await client.beta.threads.runs.retrieve(run.id, {
573 - thread_id: thread.id,
574 - });
575 - await new Promise(resolve => setTimeout(resolve, 500));
576 - }
577 - }
578 - return run;
579 - }
297 }
ts/packages/core/test/provider/openai-provider.test.ts
-309
@@ -2,7 +2,6 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
2 import { OpenAIProvider } from '../../src/provider/OpenAIProvider';
3 import { Tool } from '../../src/types/tool.types';
4 import { OpenAI } from 'openai';
5 -import { Stream } from 'openai/streaming';
5 import { toolMocks } from '../utils/mocks/data.mock';
6 import { ExecuteToolModifiers } from '../../src/types/modifiers.types';
7
@@ -13,12 +12,6 @@ vi.mock('openai', () => {
12 };
13 });
14
16 -vi.mock('openai/streaming', () => {
17 - return {
18 - Stream: vi.fn(),
19 - };
20 -});
21 -
15 describe('OpenAIProvider', () => {
16 let provider: OpenAIProvider;
17 let mockTool: Tool;
@@ -427,306 +420,4 @@ describe('OpenAIProvider', () => {
420 ]);
421 });
422 });
430 -
431 - describe('handleAssistantMessage', () => {
432 - it('should handle assistant message with tool calls', async () => {
433 - const userId = 'test-user';
434 - // Cast to OpenAI.Beta.Threads.Run to bypass property requirements
435 - const run = {
436 - id: 'run-123',
437 - object: 'thread.run',
438 - status: 'requires_action',
439 - created_at: 123456789,
440 - thread_id: 'thread-123',
441 - assistant_id: 'asst-123',
442 - required_action: {
443 - type: 'submit_tool_outputs',
444 - submit_tool_outputs: {
445 - tool_calls: [
446 - {
447 - id: 'call-123',
448 - type: 'function',
449 - function: {
450 - name: 'test-tool',
451 - arguments: JSON.stringify({ input: 'test-value' }),
452 - },
453 - },
454 - ],
455 - },
456 - },
457 - } as unknown as OpenAI.Beta.Threads.Run;
458 -
459 - const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');
460 - executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
461 -
462 - const toolOutputs = await provider.handleAssistantMessage(userId, run);
463 -
464 - expect(executeToolCallSpy).toHaveBeenCalledWith(
465 - userId,
466 - run.required_action!.submit_tool_outputs!
467 - .tool_calls[0] as OpenAI.ChatCompletionMessageToolCall,
468 - undefined,
469 - undefined
470 - );
471 - expect(toolOutputs).toEqual([
472 - {
473 - tool_call_id: 'call-123',
474 - output: JSON.stringify(JSON.stringify({ result: 'success' })),
475 - },
476 - ]);
477 - });
478 -
479 - it('should handle run with no tool calls', async () => {
480 - const userId = 'test-user';
481 - const run = {
482 - id: 'run-123',
483 - object: 'thread.run',
484 - status: 'completed',
485 - created_at: 123456789,
486 - thread_id: 'thread-123',
487 - assistant_id: 'asst-123',
488 - } as unknown as OpenAI.Beta.Threads.Run;
489 -
490 - const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');
491 -
492 - const toolOutputs = await provider.handleAssistantMessage(userId, run);
493 -
494 - expect(executeToolCallSpy).not.toHaveBeenCalled();
495 - expect(toolOutputs).toEqual([]);
496 - });
497 - });
498 -
499 - describe('waitAndHandleAssistantToolCalls', () => {
500 - it('should handle assistant tool calls until complete', async () => {
501 - const userId = 'test-user';
502 - // Create a mock OpenAI client with the necessary functions
503 - const client = {
504 - beta: {
505 - threads: {
506 - runs: {
507 - retrieve: vi.fn(),
508 - submitToolOutputs: vi.fn(),
509 - },
510 - },
511 - },
512 - } as unknown as OpenAI;
513 -
514 - // Initial run requiring action
515 - const initialRun = {
516 - id: 'run-123',
517 - object: 'thread.run',
518 - status: 'requires_action',
519 - created_at: 123456789,
520 - thread_id: 'thread-123',
521 - assistant_id: 'asst-123',
522 - required_action: {
523 - type: 'submit_tool_outputs',
524 - submit_tool_outputs: {
525 - tool_calls: [
526 - {
527 - id: 'call-123',
528 - type: 'function',
529 - function: {
530 - name: 'test-tool',
531 - arguments: JSON.stringify({ input: 'test-value' }),
532 - },
533 - },
534 - ],
535 - },
536 - },
537 - } as unknown as OpenAI.Beta.Threads.Run;
538 -
539 - // Run after submitting tool outputs, now in progress
540 - const inProgressRun = {
541 - id: 'run-123',
542 - object: 'thread.run',
543 - status: 'in_progress',
544 - created_at: 123456789,
545 - thread_id: 'thread-123',
546 - assistant_id: 'asst-123',
547 - } as unknown as OpenAI.Beta.Threads.Run;
548 -
549 - // Final completed run
550 - const completedRun = {
551 - id: 'run-123',
552 - object: 'thread.run',
553 - status: 'completed',
554 - created_at: 123456789,
555 - thread_id: 'thread-123',
556 - assistant_id: 'asst-123',
557 - } as unknown as OpenAI.Beta.Threads.Run;
558 -
559 - const thread = {
560 - id: 'thread-123',
561 - object: 'thread',
562 - created_at: 123456789,
563 - metadata: {},
564 - tool_resources: {},
565 - } as unknown as OpenAI.Beta.Threads.Thread;
566 -
567 - // Mock the handleAssistantMessage method
568 - const handleAssistantMessageSpy = vi.spyOn(provider, 'handleAssistantMessage');
569 - handleAssistantMessageSpy.mockResolvedValue([
570 - {
571 - tool_call_id: 'call-123',
572 - output: JSON.stringify({ result: 'success' }),
573 - },
574 - ]);
575 -
576 - // Setup the client mock behavior
577 - client.beta.threads.runs.submitToolOutputs = vi.fn().mockResolvedValue(inProgressRun);
578 - client.beta.threads.runs.retrieve = vi
579 - .fn()
580 - .mockResolvedValueOnce(inProgressRun)
581 - .mockResolvedValue(completedRun);
582 -
583 - // Test the method
584 - const result = await provider.waitAndHandleAssistantToolCalls(
585 - userId,
586 - client,
587 - initialRun,
588 - thread
589 - );
590 -
591 - // Verify the behavior
592 - expect(handleAssistantMessageSpy).toHaveBeenCalledWith(
593 - userId,
594 - initialRun,
595 - undefined,
596 - undefined
597 - );
598 - expect(client.beta.threads.runs.submitToolOutputs).toHaveBeenCalledWith('run-123', {
599 - thread_id: 'thread-123',
600 - tool_outputs: [
601 - {
602 - tool_call_id: 'call-123',
603 - output: JSON.stringify({ result: 'success' }),
604 - },
605 - ],
606 - });
607 - expect(client.beta.threads.runs.retrieve).toHaveBeenCalledWith('run-123', {
608 - thread_id: 'thread-123',
609 - });
610 - expect(result).toEqual(completedRun);
611 - });
612 - });
613 -
614 - describe('waitAndHandleAssistantStreamToolCalls', () => {
615 - it('should handle streamed assistant tool calls', async () => {
616 - const userId = 'test-user';
617 - const client = {
618 - beta: {
619 - threads: {
620 - runs: {
621 - retrieve: vi.fn(),
622 - submitToolOutputs: vi.fn(),
623 - },
624 - },
625 - },
626 - } as unknown as OpenAI;
627 -
628 - const thread = {
629 - id: 'thread-123',
630 - object: 'thread',
631 - created_at: 123456789,
632 - metadata: {},
633 - tool_resources: {},
634 - } as unknown as OpenAI.Beta.Threads.Thread;
635 -
636 - // Mock events in the stream
637 - const mockEvents = [
638 - {
639 - event: 'thread.run.created',
640 - data: { id: 'run-123' },
641 - },
642 - {
643 - event: 'thread.run.requires_action',
644 - data: {
645 - id: 'run-123',
646 - status: 'requires_action',
647 - required_action: {
648 - type: 'submit_tool_outputs',
649 - submit_tool_outputs: {
650 - tool_calls: [
651 - {
652 - id: 'call-123',
653 - type: 'function',
654 - function: {
655 - name: 'test-tool',
656 - arguments: JSON.stringify({ input: 'test-value' }),
657 - },
658 - },
659 - ],
660 - },
661 - },
662 - },
663 - },
664 - {
665 - event: 'thread.run.completed',
666 - data: { id: 'run-123', status: 'completed' },
667 - },
668 - ];
669 -
670 - // Create a mock async iterator for the stream
671 - const mockStream = {
672 - [Symbol.asyncIterator]: async function* () {
673 - for (const event of mockEvents) {
674 - yield event;
675 - }
676 - },
677 - } as unknown as Stream<OpenAI.Beta.Assistants.AssistantStreamEvent>;
678 -
679 - // Mock final run
680 - const finalRun = {
681 - id: 'run-123',
682 - object: 'thread.run',
683 - status: 'completed',
684 - created_at: 123456789,
685 - thread_id: 'thread-123',
686 - assistant_id: 'asst-123',
687 - } as unknown as OpenAI.Beta.Threads.Run;
688 -
689 - // Mock the handleAssistantMessage method
690 - const handleAssistantMessageSpy = vi.spyOn(provider, 'handleAssistantMessage');
691 - handleAssistantMessageSpy.mockResolvedValue([
692 - {
693 - tool_call_id: 'call-123',
694 - output: JSON.stringify({ result: 'success' }),
695 - },
696 - ]);
697 -
698 - // Setup the client mock behavior
699 - client.beta.threads.runs.submitToolOutputs = vi.fn().mockResolvedValue(finalRun);
700 - client.beta.threads.runs.retrieve = vi.fn().mockResolvedValue(finalRun);
701 -
702 - // Collect the yielded events
703 - const collectedEvents: unknown[] = [];
704 - for await (const event of provider.waitAndHandleAssistantStreamToolCalls(
705 - userId,
706 - client,
707 - mockStream,
708 - thread
709 - )) {
710 - collectedEvents.push(event);
711 - }
712 -
713 - // Verify the behavior
714 - expect(collectedEvents).toEqual(mockEvents);
715 - expect(handleAssistantMessageSpy).toHaveBeenCalledWith(
716 - userId,
717 - mockEvents[1].data,
718 - undefined,
719 - undefined
720 - );
721 - expect(client.beta.threads.runs.submitToolOutputs).toHaveBeenCalledWith('run-123', {
722 - thread_id: 'thread-123',
723 - tool_outputs: [
724 - {
725 - tool_call_id: 'call-123',
726 - output: JSON.stringify({ result: 'success' }),
727 - },
728 - ],
729 - });
730 - });
731 - });
423 });
ts/packages/providers/openai/src/OpenAIResponsesProvider.ts
+1 -1
@@ -400,7 +400,7 @@ export class OpenAIResponsesProvider extends BaseNonAgenticProvider<
400 * @param {OpenAI.Responses.Response} response - The Responses request object containing tool calls
401 * @param {ExecuteToolFnOptions} [options] - Optional execution options
402 * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
403 - * @returns {Promise<OpenAI.Beta.Threads.Runs.RunSubmitToolOutputsParams.ToolOutput[]>} Array of tool outputs for submission
403 + * @returns {Promise<OpenAI.Responses.ResponseInputItem.FunctionCallOutput[]>} Tool outputs to send back as Responses input items
404 *
405 * @example
406 * ```typescript
ts/packages/providers/openai/test/openai.test.ts
+1 -126
@@ -6,28 +6,7 @@ import { OpenAI } from 'openai';
6 // Mock the openai modules
7 vi.mock('openai', () => {
8 return {
9 - OpenAI: vi.fn().mockImplementation(function () {
10 - return {
11 - beta: {
12 - threads: {
13 - runs: {
14 - retrieve: vi.fn().mockImplementation((runId, options) => {
15 - return { id: runId, status: 'completed' };
16 - }),
17 - submitToolOutputs: vi.fn().mockImplementation((runId, options) => {
18 - return { id: runId, status: 'completed' };
19 - }),
20 - },
21 - },
22 - },
23 - };
24 - }),
25 - };
26 -});
27 -
28 -vi.mock('openai/streaming', () => {
29 - return {
30 - Stream: vi.fn(),
9 + OpenAI: vi.fn(),
10 };
11 });
12
@@ -433,108 +412,4 @@ describe('OpenAIProvider', () => {
412 ]);
413 });
414 });
436 -
437 - describe('handleAssistantMessage', () => {
438 - it('should process tool calls from an assistant run', async () => {
439 - const userId = 'test-user';
440 - const run = {
441 - id: 'run-123',
442 - required_action: {
443 - submit_tool_outputs: {
444 - tool_calls: [
445 - {
446 - id: 'tool-call-123',
447 - type: 'function',
448 - function: {
449 - name: 'test-tool',
450 - arguments: JSON.stringify({ input: 'test-value' }),
451 - },
452 - },
453 - ],
454 - },
455 - },
456 - } as unknown as OpenAI.Beta.Threads.Run;
457 -
458 - const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');
459 - executeToolCallSpy.mockResolvedValue(JSON.stringify({ result: 'success' }));
460 -
461 - const toolOutputs = await provider.handleAssistantMessage(userId, run);
462 -
463 - expect(executeToolCallSpy).toHaveBeenCalledWith(
464 - userId,
465 - run.required_action?.submit_tool_outputs
466 - ?.tool_calls[0] as OpenAI.ChatCompletionMessageToolCall,
467 - undefined,
468 - undefined
469 - );
470 - expect(toolOutputs).toEqual([
471 - {
472 - tool_call_id: 'tool-call-123',
473 - output: JSON.stringify(JSON.stringify({ result: 'success' })),
474 - },
475 - ]);
476 - });
477 -
478 - it('should handle runs without tool calls', async () => {
479 - const userId = 'test-user';
480 - const run = {
481 - id: 'run-123',
482 - } as OpenAI.Beta.Threads.Run;
483 -
484 - const executeToolCallSpy = vi.spyOn(provider, 'executeToolCall');
485 -
486 - const toolOutputs = await provider.handleAssistantMessage(userId, run);
487 -
488 - expect(executeToolCallSpy).not.toHaveBeenCalled();
489 - expect(toolOutputs).toEqual([]);
490 - });
491 - });
492 -
493 - describe('waitAndHandleAssistantToolCalls', () => {
494 - it('should handle and submit tool outputs for an assistant run', async () => {
495 - const userId = 'test-user';
496 - const client = new OpenAI();
497 - const thread = { id: 'thread-123' } as OpenAI.Beta.Threads.Thread;
498 - const run = {
499 - id: 'run-123',
500 - status: 'requires_action',
501 - required_action: {
502 - submit_tool_outputs: {
503 - tool_calls: [
504 - {
505 - id: 'tool-call-123',
506 - type: 'function',
507 - function: {
508 - name: 'test-tool',
509 - arguments: JSON.stringify({ input: 'test-value' }),
510 - },
511 - },
512 - ],
513 - },
514 - },
515 - } as OpenAI.Beta.Threads.Run;
516 -
517 - const handleAssistantMessageSpy = vi.spyOn(provider, 'handleAssistantMessage');
518 - handleAssistantMessageSpy.mockResolvedValue([
519 - {
520 - tool_call_id: 'tool-call-123',
521 - output: JSON.stringify({ result: 'success' }),
522 - },
523 - ]);
524 -
525 - const result = await provider.waitAndHandleAssistantToolCalls(userId, client, run, thread);
526 -
527 - expect(handleAssistantMessageSpy).toHaveBeenCalledWith(userId, run, undefined, undefined);
528 - expect(client.beta.threads.runs.submitToolOutputs).toHaveBeenCalledWith(run.id, {
529 - thread_id: thread.id,
530 - tool_outputs: [
531 - {
532 - tool_call_id: 'tool-call-123',
533 - output: JSON.stringify({ result: 'success' }),
534 - },
535 - ],
536 - });
537 - expect(result).toEqual({ id: 'run-123', status: 'completed' });
538 - });
539 - });
415 });