Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/lib/responses/ResponseAccumulator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,22 @@ import {
import { OpenAIError } from '../../error';
import { addOutputText } from '../ResponsesParser';

type ResponseKeepAliveEvent = {
type: 'keepalive';
sequence_number: number;
};

/**
* Applies a streaming event to a response snapshot.
*
* Always use the returned snapshot. Incremental events update the supplied snapshot
* in place, while response lifecycle events return a detached replacement. Event
* payloads are cloned, so retaining or replaying the raw events is safe.
*/
export function accumulateResponse(event: ResponseStreamEvent, snapshot?: Response): Response {
export function accumulateResponse(
event: ResponseStreamEvent | ResponseKeepAliveEvent,
snapshot?: Response,
): Response {
if (!snapshot) {
if (event.type !== 'response.created') {
throw new OpenAIError(
Expand Down Expand Up @@ -371,6 +379,7 @@ export function accumulateResponse(event: ResponseStreamEvent, snapshot?: Respon
case 'response.mcp_list_tools.in_progress':
case 'response.mcp_list_tools.completed':
case 'response.mcp_list_tools.failed':
case 'keepalive':
case 'error': {
// These events do not contain state represented by the Response object.
break;
Expand Down
13 changes: 13 additions & 0 deletions tests/lib/ResponseAccumulator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,19 @@ describe('ResponseAccumulator', () => {
expect(first.output_text).toBe('Hello world');
});

it('ignores keepalive events', () => {
const initial = accumulateResponse({
type: 'response.created',
sequence_number: 0,
response: makeResponse(),
});

const snapshot = accumulateResponse({ type: 'keepalive', sequence_number: 1 }, initial);

expect(snapshot).toBe(initial);
expect(snapshot).toEqual(makeResponse());
});

it.each([
['response.completed', 'completed'],
['response.failed', 'failed'],
Expand Down