|
| 1 | +/** Buffered consumption of the knowledge chat SSE stream: deltas concatenate into one complete answer. */ |
| 2 | + |
| 3 | +import type { ChatStreamChunk } from './api-types.js' |
| 4 | +import { KbApiError } from './client.js' |
| 5 | +import { parseSseStream } from './sse.js' |
| 6 | + |
| 7 | +export interface ChatResult { |
| 8 | + answer: string |
| 9 | + requestId?: string |
| 10 | +} |
| 11 | + |
| 12 | +/** |
| 13 | + * Consume one chat SSE response to completion. |
| 14 | + * @param res - the SSE response from KbClient.postSse. |
| 15 | + * @returns the concatenated answer and the last seen request id. |
| 16 | + */ |
| 17 | +export async function consumeChatStream(res: Response): Promise<ChatResult> { |
| 18 | + if (!res.body) throw new KbApiError('knowledge chat returned no response body') |
| 19 | + let answer = '' |
| 20 | + let requestId: string | undefined |
| 21 | + for await (const event of parseSseStream(res.body)) { |
| 22 | + if (event.data === '[DONE]') break |
| 23 | + if (event.event === 'error') { |
| 24 | + let message = `knowledge chat stream error: ${event.data}` |
| 25 | + try { |
| 26 | + const err = JSON.parse(event.data) as { code?: string; message?: string } |
| 27 | + if (err.message) message = `knowledge chat stream error${err.code ? ` (${err.code})` : ''}: ${err.message}` |
| 28 | + } catch { /* non-JSON error payload: keep the raw data in the message */ } |
| 29 | + throw new KbApiError(message) |
| 30 | + } |
| 31 | + let parsed: ChatStreamChunk |
| 32 | + try { |
| 33 | + parsed = JSON.parse(event.data) as ChatStreamChunk |
| 34 | + } catch { continue } // unparseable keep-alive/comment payloads carry no answer content |
| 35 | + if (parsed.request_id) requestId = parsed.request_id |
| 36 | + for (const choice of parsed.output?.choices ?? []) { |
| 37 | + if (choice.message?.content) answer += choice.message.content |
| 38 | + } |
| 39 | + } |
| 40 | + return { answer, requestId } |
| 41 | +} |
0 commit comments