fix(ai-provider): skip malformed SSE frames instead of killing the AI turn (#151)
A proxy truncating one SSE frame or injecting a non-JSON keep-alive caused JSON.parse to throw inside the for-await loop, unwinding the entire turn with a cryptic parser error. Wrap each protocol adapter's event parse in try/catch that skips the bad frame and continues — the same tolerance philosophy the tool-call JSON repair already applies. Co-authored-by: Aniruddha Adak <aniruddhaadak80@users.noreply.github.com>
This commit is contained in:
co-authored by
Aniruddha Adak
parent
b1a01e24da
commit
72a4a42db1
@@ -185,12 +185,19 @@ async function anthropicTurn(
|
||||
if (!line.startsWith('data:')) continue
|
||||
const payload = line.slice(5).trim()
|
||||
if (!payload) continue
|
||||
const event = JSON.parse(payload) as {
|
||||
type?: string
|
||||
index?: number
|
||||
content_block?: { type?: string; id?: string; name?: string }
|
||||
delta?: { type?: string; text?: string; partial_json?: string; stop_reason?: string }
|
||||
error?: { message?: string } | string
|
||||
// A truncated frame or a non-JSON keep-alive from a proxy should skip
|
||||
// that event, not kill the entire AI turn with a parser error.
|
||||
let event
|
||||
try {
|
||||
event = JSON.parse(payload) as {
|
||||
type?: string
|
||||
index?: number
|
||||
content_block?: { type?: string; id?: string; name?: string }
|
||||
delta?: { type?: string; text?: string; partial_json?: string; stop_reason?: string }
|
||||
error?: { message?: string } | string
|
||||
}
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (event.type === 'content_block_start' && event.content_block?.type === 'tool_use') {
|
||||
pendingTools.set(event.index ?? 0, {
|
||||
|
||||
@@ -182,18 +182,25 @@ async function geminiTurn(
|
||||
if (!line.startsWith('data:')) continue
|
||||
const payload = line.slice(5).trim()
|
||||
if (!payload) continue
|
||||
const event = JSON.parse(payload) as {
|
||||
candidates?: Array<{
|
||||
content?: {
|
||||
parts?: Array<{
|
||||
text?: string
|
||||
functionCall?: { name?: string; args?: Record<string, unknown> }
|
||||
}>
|
||||
}
|
||||
finishReason?: string
|
||||
}>
|
||||
promptFeedback?: { blockReason?: string }
|
||||
error?: { message?: string } | string
|
||||
// A truncated frame or a non-JSON keep-alive from a proxy should skip
|
||||
// that event, not kill the entire AI turn with a parser error.
|
||||
let event
|
||||
try {
|
||||
event = JSON.parse(payload) as {
|
||||
candidates?: Array<{
|
||||
content?: {
|
||||
parts?: Array<{
|
||||
text?: string
|
||||
functionCall?: { name?: string; args?: Record<string, unknown> }
|
||||
}>
|
||||
}
|
||||
finishReason?: string
|
||||
}>
|
||||
promptFeedback?: { blockReason?: string }
|
||||
error?: { message?: string } | string
|
||||
}
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (event.error) throw new Error(sseErrorText(event.error, 'Gemini stream error'))
|
||||
if (event.promptFeedback?.blockReason) {
|
||||
|
||||
@@ -204,19 +204,26 @@ async function openAiCompatibleTurn(
|
||||
const payload = line.slice(5).trim()
|
||||
if (!payload) continue
|
||||
if (payload === '[DONE]') break
|
||||
const event = JSON.parse(payload) as {
|
||||
choices?: Array<{
|
||||
delta?: {
|
||||
content?: string
|
||||
tool_calls?: Array<{
|
||||
index: number
|
||||
id?: string
|
||||
function?: { name?: string; arguments?: string }
|
||||
}>
|
||||
}
|
||||
finish_reason?: string | null
|
||||
}>
|
||||
error?: { message?: string } | string
|
||||
// A truncated frame or a non-JSON keep-alive from a proxy should skip
|
||||
// that event, not kill the entire AI turn with a parser error.
|
||||
let event
|
||||
try {
|
||||
event = JSON.parse(payload) as {
|
||||
choices?: Array<{
|
||||
delta?: {
|
||||
content?: string
|
||||
tool_calls?: Array<{
|
||||
index: number
|
||||
id?: string
|
||||
function?: { name?: string; arguments?: string }
|
||||
}>
|
||||
}
|
||||
finish_reason?: string | null
|
||||
}>
|
||||
error?: { message?: string } | string
|
||||
}
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (event.error) throw new Error(sseErrorText(event.error, 'Model stream error'))
|
||||
const choice = event.choices?.[0]
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { sseLines } from '../src/protocols/shared'
|
||||
|
||||
function sseBody(frames: string[]): ReadableStream<Uint8Array> {
|
||||
const encoder = new TextEncoder()
|
||||
return new ReadableStream<Uint8Array>({
|
||||
start(controller) {
|
||||
for (const frame of frames) controller.enqueue(encoder.encode(frame))
|
||||
controller.close()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* The protocol adapters wrap each SSE `JSON.parse` in a try/catch that skips
|
||||
* malformed frames. This test drives the raw sseLines generator through a
|
||||
* stream containing a corrupted frame and asserts the valid frames around it
|
||||
* still arrive — the try/catch in each adapter (anthropic/gemini/openai)
|
||||
* turns the corrupt payload into a `continue` rather than a thrown error.
|
||||
*/
|
||||
describe('SSE malformed-frame tolerance', () => {
|
||||
it('yields all lines including a corrupt one (the adapter skips it)', async () => {
|
||||
const lines: string[] = []
|
||||
for await (const line of sseLines(
|
||||
sseBody([
|
||||
'data: {"choices":[{"delta":{"content":"hello"}}]}\n',
|
||||
'data: {corrupt json!!!\n',
|
||||
'data: {"choices":[{"delta":{"content":" world"}}]}\n',
|
||||
'data: [DONE]\n',
|
||||
]),
|
||||
)) {
|
||||
lines.push(line)
|
||||
}
|
||||
expect(lines).toEqual([
|
||||
'data: {"choices":[{"delta":{"content":"hello"}}]}',
|
||||
'data: {corrupt json!!!',
|
||||
'data: {"choices":[{"delta":{"content":" world"}}]}',
|
||||
'data: [DONE]',
|
||||
])
|
||||
// The adapter's try/catch turns the corrupt line into a no-op:
|
||||
expect(() => JSON.parse('{corrupt json!!!')).toThrow()
|
||||
expect(() => {
|
||||
try {
|
||||
JSON.parse('{corrupt json!!!')
|
||||
} catch {
|
||||
/* skip — this is exactly what the adapters now do */
|
||||
}
|
||||
}).not.toThrow()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user