import type * as plugins from './plugins.js'; /** An event's data as a JSON object, or `undefined`. */ const eventRecord = (data: string): Record | undefined => { try { const value: unknown = JSON.parse(data); return typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record : undefined; } catch { return undefined; } }; /** The Responses events that end a stream: a finished answer, a failed one, and an error event. */ const responsesTerminalTypes = new Set(['response.completed', 'response.incomplete', 'response.failed', 'error']); /** * Where a Responses stream ends: `response.completed` or `response.incomplete` ends the answer, * `response.failed` and an `error` event end a failed one (AGL-1130). */ export const openAiResponsesTerminal: plugins.IModelStreamTerminal = { event: 'response.completed', ends: (data) => (data.includes('"response.completed"') || data.includes('"response.incomplete"') || data.includes('"response.failed"') || data.includes('"error"')) && responsesTerminalTypes.has(eventRecord(data)?.type as string), }; /** * Where a Chat Completions stream ends: `[DONE]` ends the answer, and an error chunk, which a * server sends in place of the rest of a failed answer and without `[DONE]`, ends it too: a chunk * with an `error` object and no `choices`, as the AI SDK reads one (AGL-1130). */ export const openAiChatTerminal: plugins.IModelStreamTerminal = { event: '[DONE]', ends: (data) => { if (data === '[DONE]') return true; if (!data.includes('"error"')) return false; const chunk = eventRecord(data); return typeof chunk?.error === 'object' && chunk.error !== null && !Array.isArray(chunk.choices); }, };