From d75200b7d31c87694588427d895e4cf8a8c295c7 Mon Sep 17 00:00:00 2001 From: ggbond Date: Fri, 4 Dec 2026 10:04:12 +0800 Subject: [PATCH 1/2] fix(ai-bedrock): report incomplete-stream when Converse stream ends without messageStop --- docs/chat/streaming.md | 1 + .../ai-bedrock/src/adapters/converse-text.ts | 22 ++ .../src/converse/stream-processor.ts | 53 +++-- .../tests/converse/incomplete-stream.test.ts | 202 ++++++++++++++++++ .../tests/converse/stream-processor.test.ts | 9 +- 5 files changed, 271 insertions(+), 16 deletions(-) create mode 100644 packages/ai-bedrock/tests/converse/incomplete-stream.test.ts diff --git a/docs/chat/streaming.md b/docs/chat/streaming.md index 3e2544ad4f..da1927e9c6 100644 --- a/docs/chat/streaming.md +++ b/docs/chat/streaming.md @@ -199,6 +199,7 @@ The shared `ChatClient` processes the chunks that are ready in order. It does no - **An OpenAI or OpenRouter Responses stream ends without `response.completed`.** The adapter emits `RUN_ERROR` with code `incomplete-stream`. This applies to chat and to structured output. The text that arrived stays available. The run does not call `onFinish`. - **A Chat Completions stream ends without a finish.** See below. - **An Anthropic stream ends before a stop reason.** No `message_delta` with `stop_reason` and no `message_stop` arrived. The adapter emits `RUN_ERROR` with code `incomplete-stream`. The text that arrived stays available. The run does not call `onFinish`. +- **A Bedrock Converse stream ends without `messageStop`.** The adapter closes any open text or reasoning blocks, skips unclosed tool calls, and emits `RUN_ERROR` with code `incomplete-stream`. This applies to chat and to structured output. The text that arrived stays available. The run does not call `onFinish`. - **A Gemini chat stream ends without a `finishReason`.** The adapter closes the open tool calls, reasoning, and text, then emits `RUN_ERROR` with code `truncated-stream`. Gemini structured output already uses this code. The text that arrived stays available. The run does not call `onFinish`. Chat Completions adapters built on `@tanstack/openai-base` also make sure that the stream finished. A started stream needs one of these: diff --git a/packages/ai-bedrock/src/adapters/converse-text.ts b/packages/ai-bedrock/src/adapters/converse-text.ts index f095c281c8..8c66fdecf1 100644 --- a/packages/ai-bedrock/src/adapters/converse-text.ts +++ b/packages/ai-bedrock/src/adapters/converse-text.ts @@ -299,6 +299,7 @@ export class BedrockConverseTextAdapter< threadId: options.threadId, parentRunId: options.parentRunId, model: options.model, + signal: options.request?.signal, }, )) { yield chunk.type === EventType.RUN_STARTED || @@ -408,6 +409,7 @@ export class BedrockConverseTextAdapter< let hasEmittedTextMessageStart = false let accumulatedRaw = '' let finishReason: 'stop' | 'length' | 'content_filter' = 'stop' + let sawMessageStop = false // Usage arrives on the trailing `metadata` event, after the finish signal, // so it is captured during iteration and folded into RUN_FINISHED below. let usage: TokenUsage | undefined @@ -477,6 +479,7 @@ export class BedrockConverseTextAdapter< } if ('messageStop' in ev) { + sawMessageStop = true const stopReason = ev.messageStop?.stopReason // The forced structured-output tool produces stopReason 'tool_use' on // success, but that's an implementation detail — a cleanly-completed @@ -522,6 +525,25 @@ export class BedrockConverseTextAdapter< } } + if (!sawMessageStop) { + if (chatOptions.request?.signal?.aborted) { + return + } + const message = `${this.name}.structuredOutputStream: Converse stream ended without messageStop` + yield { + type: EventType.RUN_ERROR, + metadata: this.sourceMetadata(chatOptions.model), + runId, + model: chatOptions.model, + timestamp: Date.now(), + message, + code: 'incomplete-stream', + error: { message, code: 'incomplete-stream' }, + ...(usage && { usage }), + } + return + } + // Same truncation check as `structuredOutput()`: report the token limit // before the empty-content and parse errors (issue #1426). if (finishReason === 'length') { diff --git a/packages/ai-bedrock/src/converse/stream-processor.ts b/packages/ai-bedrock/src/converse/stream-processor.ts index 84732b0f28..0895247076 100644 --- a/packages/ai-bedrock/src/converse/stream-processor.ts +++ b/packages/ai-bedrock/src/converse/stream-processor.ts @@ -36,10 +36,15 @@ export function throwIfConverseStreamError(ev: ConverseStreamOutput): void { export async function* processConverseStream( stream: AsyncIterable, newMessageId: () => string, - lifecycle: { threadId: string; parentRunId?: string; model?: string }, + lifecycle: { + threadId: string + parentRunId?: string + model?: string + signal?: AbortSignal | null + }, ): AsyncIterable { const runId = newMessageId() - const { threadId, parentRunId, model } = lifecycle + const { threadId, parentRunId, model, signal } = lifecycle const messageId = newMessageId() let hasEmittedRunStarted = false @@ -79,6 +84,7 @@ export async function* processConverseStream( // contract (usage may arrive after the finish signal). let usage: TokenUsage | undefined let finishReason: NonNullable | undefined + let sawMessageStop = false // The model filled its context window before it finished (stopReason // `model_context_window_exceeded`). The answer is cut off, so the run ends // with a RUN_ERROR instead of a clean RUN_FINISHED. @@ -286,6 +292,7 @@ export async function* processConverseStream( } if ('messageStop' in ev) { + sawMessageStop = true const stopReason: string | undefined = ev.messageStop?.stopReason contextWindowExceeded = stopReason === 'model_context_window_exceeded' // Map Converse stopReason to AG-UI's narrower finishReason vocabulary. @@ -314,17 +321,22 @@ export async function* processConverseStream( // consumers always see a run lifecycle. yield* ensureRunStarted() - // Drain any tool call that opened but never received contentBlockStop. - for (const [index, toolCall] of toolCallsByIndex) { - if (!toolCall.started) continue - yield { - type: EventType.TOOL_CALL_END, - toolCallId: toolCall.id, - args: toolCall.arguments, - toolCallName: toolCall.name, - timestamp: Date.now(), + // Drain any tool call that opened but never received contentBlockStop when + // the turn actually reached messageStop. If the stream was cut off before + // messageStop, leave unclosed tool calls unfinished so partial JSON is not + // emitted as a completed call. + if (sawMessageStop) { + for (const [index, toolCall] of toolCallsByIndex) { + if (!toolCall.started) continue + yield { + type: EventType.TOOL_CALL_END, + toolCallId: toolCall.id, + args: toolCall.arguments, + toolCallName: toolCall.name, + timestamp: Date.now(), + } + toolCallsByIndex.delete(index) } - toolCallsByIndex.delete(index) } // Close the text message lifecycle if it was opened. @@ -354,6 +366,23 @@ export async function* processConverseStream( return } + if (!sawMessageStop) { + if (signal?.aborted) { + return + } + const message = 'Bedrock Converse stream ended without messageStop' + yield { + type: EventType.RUN_ERROR, + ...(model && { model }), + timestamp: Date.now(), + message, + code: 'incomplete-stream', + error: { message, code: 'incomplete-stream' }, + ...(usage && { usage }), + } + return + } + // Single terminal RUN_FINISHED. Conditional `usage` spread keeps the wire // shape spec-compliant (AG-UI's `usage` is optional with no `| undefined`). yield { diff --git a/packages/ai-bedrock/tests/converse/incomplete-stream.test.ts b/packages/ai-bedrock/tests/converse/incomplete-stream.test.ts new file mode 100644 index 0000000000..21a7dd3ee8 --- /dev/null +++ b/packages/ai-bedrock/tests/converse/incomplete-stream.test.ts @@ -0,0 +1,202 @@ +import { describe, expect, it } from 'vitest' +import { EventType, chat } from '@tanstack/ai' +import { resolveDebugOption } from '@tanstack/ai/adapter-internals' +import { BedrockConverseTextAdapter } from '../../src/adapters/converse-text' +import type { + ConverseStreamCommandInput, + ConverseStreamOutput, +} from '@aws-sdk/client-bedrock-runtime' +import type { StreamChunk } from '@tanstack/ai' + +const model = 'us.amazon.nova-pro-v1:0' + +type Fixture = { [K in keyof ConverseStreamOutput]?: unknown } + +/** A ConverseStream cut off mid tool call: no contentBlockStop, no messageStop. */ +const cutEvents: Array = [ + { messageStart: { role: 'assistant' } }, + { + contentBlockDelta: { + contentBlockIndex: 0, + delta: { text: 'Let me clean that up.' }, + }, + }, + { contentBlockStop: { contentBlockIndex: 0 } }, + { + contentBlockStart: { + contentBlockIndex: 1, + start: { toolUse: { toolUseId: 'tooluse_1', name: 'delete_files' } }, + }, + }, + { + contentBlockDelta: { + contentBlockIndex: 1, + delta: { toolUse: { input: '{"path": "/data/repo' } }, + }, + }, +] + +const completeEvents: Array = [ + ...cutEvents, + { contentBlockStop: { contentBlockIndex: 1 } }, + { messageStop: { stopReason: 'tool_use' } }, + { metadata: { usage: { inputTokens: 5, outputTokens: 6, totalTokens: 11 } } }, +] + +class StubAdapter extends BedrockConverseTextAdapter { + events: Array = [] + + protected override async sendStream( + _input: ConverseStreamCommandInput, + ): Promise> { + const events = this.events + return (async function* () { + for (const event of events) yield event as ConverseStreamOutput + })() + } +} + +async function runChat(events: Array) { + const adapter = new StubAdapter({ apiKey: 'k' }, model) + adapter.events = events + const chunks: Array = [] + const calls = { finish: 0, error: 0 } + for await (const chunk of chat({ + adapter, + threadId: 'repro', + messages: [{ role: 'user', content: 'Clean up /data/repo' }], + middleware: [ + { + name: 'observe', + onFinish: () => { + calls.finish++ + }, + onError: () => { + calls.error++ + }, + }, + ], + })) { + chunks.push(chunk) + } + return { chunks, calls } +} + +describe('Bedrock Converse stream that ends without messageStop', () => { + it('ends the run with an incomplete-stream RUN_ERROR and skips onFinish', async () => { + const { chunks, calls } = await runChat(cutEvents) + expect(chunks.at(-1)).toMatchObject({ + type: 'RUN_ERROR', + code: 'incomplete-stream', + }) + expect(chunks.some((chunk) => chunk.type === 'RUN_FINISHED')).toBe(false) + expect(calls).toEqual({ finish: 0, error: 1 }) + }) + + it('does not close a tool call whose input never finished', async () => { + const { chunks } = await runChat(cutEvents) + expect(chunks.some((chunk) => chunk.type === 'TOOL_CALL_END')).toBe(false) + }) + + it('keeps the partial text and closes TEXT_MESSAGE_END', async () => { + const { chunks } = await runChat(cutEvents) + expect( + chunks.some( + (chunk) => + chunk.type === 'TEXT_MESSAGE_CONTENT' && + chunk.delta === 'Let me clean that up.', + ), + ).toBe(true) + expect(chunks.some((chunk) => chunk.type === 'TEXT_MESSAGE_END')).toBe(true) + }) + + it('still finishes a stream that sent messageStop', async () => { + const { chunks, calls } = await runChat(completeEvents) + const last = chunks.at(-1) + expect(last?.type).toBe('RUN_FINISHED') + expect( + (last?.metadata as { tanstack?: { finishReason?: string } } | undefined) + ?.tanstack?.finishReason, + ).toBe('tool_calls') + expect(chunks.some((chunk) => chunk.type === 'TOOL_CALL_END')).toBe(true) + expect(calls).toEqual({ finish: 1, error: 0 }) + }) + + it('does not report an abort as an incomplete stream', async () => { + const controller = new AbortController() + class AbortableStubAdapter extends BedrockConverseTextAdapter { + protected override async sendStream(): Promise< + AsyncIterable + > { + return (async function* () { + yield cutEvents[0] as ConverseStreamOutput + yield cutEvents[1] as ConverseStreamOutput + })() + } + } + + const adapter = new AbortableStubAdapter({ apiKey: 'k' }, model) + const chunks: Array = [] + for await (const chunk of adapter.chatStream({ + threadId: 'thread-1', + logger: resolveDebugOption(false), + model, + messages: [{ role: 'user', content: 'Hi' }], + request: { signal: controller.signal }, + })) { + chunks.push(chunk) + if (chunk.type === EventType.TEXT_MESSAGE_CONTENT) controller.abort() + } + + expect( + chunks.some( + (chunk) => + chunk.type === EventType.RUN_ERROR && + chunk.code === 'incomplete-stream', + ), + ).toBe(false) + expect(chunks.some((chunk) => chunk.type === EventType.RUN_FINISHED)).toBe( + false, + ) + }) + + it('reports incomplete-stream on structuredOutputStream when messageStop is missing', async () => { + const adapter = new StubAdapter({ apiKey: 'k' }, model) + adapter.events = [ + { messageStart: { role: 'assistant' } }, + { + contentBlockStart: { + contentBlockIndex: 0, + start: { toolUse: { toolUseId: 's', name: 'structured_output' } }, + }, + }, + { + contentBlockDelta: { + contentBlockIndex: 0, + delta: { toolUse: { input: '{"n":' } }, + }, + }, + ] + + const chunks: Array<{ type: string; code?: string }> = [] + for await (const chunk of adapter.structuredOutputStream({ + chatOptions: { + threadId: 'thread-1', + logger: resolveDebugOption(false), + model, + messages: [{ role: 'user', content: 'go' }], + }, + outputSchema: { type: 'object', properties: { n: { type: 'number' } } }, + })) { + chunks.push(chunk as { type: string; code?: string }) + } + + expect(chunks.at(-1)).toMatchObject({ + type: EventType.RUN_ERROR, + code: 'incomplete-stream', + }) + expect(chunks.some((chunk) => chunk.type === EventType.RUN_FINISHED)).toBe( + false, + ) + }) +}) diff --git a/packages/ai-bedrock/tests/converse/stream-processor.test.ts b/packages/ai-bedrock/tests/converse/stream-processor.test.ts index d6eaa14bff..2e75f7abf1 100644 --- a/packages/ai-bedrock/tests/converse/stream-processor.test.ts +++ b/packages/ai-bedrock/tests/converse/stream-processor.test.ts @@ -276,7 +276,7 @@ describe('processConverseStream', () => { }) }) - it('drains a tool call that never received contentBlockStop (truncated stream)', async () => { + it('drains a tool call that never received contentBlockStop when messageStop arrived', async () => { const events = await collect( { contentBlockStart: { @@ -290,7 +290,7 @@ describe('processConverseStream', () => { contentBlockIndex: 0, }, }, - // No contentBlockStop, no messageStop — stream just ends. + { messageStop: { stopReason: 'tool_use' } }, ) const ends = events.filter((e) => e.type === EventType.TOOL_CALL_END) expect(ends).toHaveLength(1) @@ -456,7 +456,7 @@ describe('processConverseStream', () => { expect(end).toMatchObject({ toolCallId: 't1', args: '{"n": 1.50}' }) }) - it('puts malformed raw arguments on TOOL_CALL_END without an input', async () => { + it('puts malformed raw arguments on TOOL_CALL_END without an input when messageStop arrived', async () => { const events = await collect( { contentBlockStart: { @@ -470,7 +470,7 @@ describe('processConverseStream', () => { contentBlockIndex: 0, }, }, - // Truncated: the drained END still carries the raw string. + { messageStop: { stopReason: 'tool_use' } }, ) const end = events.find((e) => e.type === EventType.TOOL_CALL_END) expect(end).toMatchObject({ toolCallId: 't1', args: '{"a":' }) @@ -486,6 +486,7 @@ describe('processConverseStream', () => { }, }, { contentBlockStop: { contentBlockIndex: 0 } }, + { messageStop: { stopReason: 'tool_use' } }, ) const end = events.find((e) => e.type === EventType.TOOL_CALL_END) expect(end).toMatchObject({ toolCallId: 't1', args: '' }) From f677fc02471445cf77daa159a74dae5048048e8d Mon Sep 17 00:00:00 2001 From: Tom Beckenham <34339192+tombeckenham@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:56:17 +1100 Subject: [PATCH 2/2] fix(ai-bedrock): add changeset, runId, and E2E for incomplete Converse streams - Add a patch changeset for @tanstack/ai-bedrock. - Put runId on the incomplete-stream RUN_ERROR of processConverseStream. - Drop the sawMessageStop flags: finishReason is set only by messageStop. - Cover the structured-output abort branch and the processor-level error shape; trim incomplete-stream.test.ts to one stub adapter. - Add an E2E spec with a Converse mock that ends before messageStop. - Docs: an aborted request is not reported; refresh updatedAt. Refs https://github.com/TanStack/ai/issues/2306 --- .../bedrock-converse-incomplete-stream.md | 5 + docs/chat/streaming.md | 2 +- docs/config.json | 2 +- .../ai-bedrock/src/adapters/converse-text.ts | 8 +- .../src/converse/stream-processor.ts | 15 +- .../tests/converse/incomplete-stream.test.ts | 225 +++++++----------- .../tests/converse/stream-processor.test.ts | 59 +++++ testing/e2e/global-setup.ts | 99 ++++++-- testing/e2e/src/routeTree.gen.ts | 23 ++ .../api.bedrock-converse-incomplete-stream.ts | 86 +++++++ ...bedrock-converse-incomplete-stream.spec.ts | 38 +++ 11 files changed, 387 insertions(+), 175 deletions(-) create mode 100644 .changeset/bedrock-converse-incomplete-stream.md create mode 100644 testing/e2e/src/routes/api.bedrock-converse-incomplete-stream.ts create mode 100644 testing/e2e/tests/bedrock-converse-incomplete-stream.spec.ts diff --git a/.changeset/bedrock-converse-incomplete-stream.md b/.changeset/bedrock-converse-incomplete-stream.md new file mode 100644 index 0000000000..ee6a52a750 --- /dev/null +++ b/.changeset/bedrock-converse-incomplete-stream.md @@ -0,0 +1,5 @@ +--- +'@tanstack/ai-bedrock': patch +--- + +A Bedrock Converse stream that ends without `messageStop` now ends the run with `RUN_ERROR` and code `incomplete-stream`. Before, the run finished with `stop`, and a tool call whose input was cut off was closed with the partial input. This applies to chat and to structured output. The text that arrived stays available. An aborted request is not reported. diff --git a/docs/chat/streaming.md b/docs/chat/streaming.md index da1927e9c6..e8b9e11103 100644 --- a/docs/chat/streaming.md +++ b/docs/chat/streaming.md @@ -199,7 +199,7 @@ The shared `ChatClient` processes the chunks that are ready in order. It does no - **An OpenAI or OpenRouter Responses stream ends without `response.completed`.** The adapter emits `RUN_ERROR` with code `incomplete-stream`. This applies to chat and to structured output. The text that arrived stays available. The run does not call `onFinish`. - **A Chat Completions stream ends without a finish.** See below. - **An Anthropic stream ends before a stop reason.** No `message_delta` with `stop_reason` and no `message_stop` arrived. The adapter emits `RUN_ERROR` with code `incomplete-stream`. The text that arrived stays available. The run does not call `onFinish`. -- **A Bedrock Converse stream ends without `messageStop`.** The adapter closes any open text or reasoning blocks, skips unclosed tool calls, and emits `RUN_ERROR` with code `incomplete-stream`. This applies to chat and to structured output. The text that arrived stays available. The run does not call `onFinish`. +- **A Bedrock Converse stream ends without `messageStop`.** The adapter closes any open text or reasoning blocks, skips unclosed tool calls, and emits `RUN_ERROR` with code `incomplete-stream`. This applies to chat and to structured output. The text that arrived stays available. The run does not call `onFinish`. An aborted request is not reported. - **A Gemini chat stream ends without a `finishReason`.** The adapter closes the open tool calls, reasoning, and text, then emits `RUN_ERROR` with code `truncated-stream`. Gemini structured output already uses this code. The text that arrived stays available. The run does not call `onFinish`. Chat Completions adapters built on `@tanstack/openai-base` also make sure that the stream finished. A started stream needs one of these: diff --git a/docs/config.json b/docs/config.json index 2efce6249d..50936e64af 100644 --- a/docs/config.json +++ b/docs/config.json @@ -243,7 +243,7 @@ "label": "Streaming", "to": "chat/streaming", "addedAt": "2026-04-15", - "updatedAt": "2026-11-09" + "updatedAt": "2026-12-04" }, { "label": "Stream Events", diff --git a/packages/ai-bedrock/src/adapters/converse-text.ts b/packages/ai-bedrock/src/adapters/converse-text.ts index 8c66fdecf1..d83d9729a4 100644 --- a/packages/ai-bedrock/src/adapters/converse-text.ts +++ b/packages/ai-bedrock/src/adapters/converse-text.ts @@ -408,8 +408,8 @@ export class BedrockConverseTextAdapter< let hasEmittedRunStarted = false let hasEmittedTextMessageStart = false let accumulatedRaw = '' - let finishReason: 'stop' | 'length' | 'content_filter' = 'stop' - let sawMessageStop = false + // Set only by `messageStop`, so `undefined` means the stream was cut off. + let finishReason: 'stop' | 'length' | 'content_filter' | undefined // Usage arrives on the trailing `metadata` event, after the finish signal, // so it is captured during iteration and folded into RUN_FINISHED below. let usage: TokenUsage | undefined @@ -479,7 +479,6 @@ export class BedrockConverseTextAdapter< } if ('messageStop' in ev) { - sawMessageStop = true const stopReason = ev.messageStop?.stopReason // The forced structured-output tool produces stopReason 'tool_use' on // success, but that's an implementation detail — a cleanly-completed @@ -525,7 +524,8 @@ export class BedrockConverseTextAdapter< } } - if (!sawMessageStop) { + if (finishReason === undefined) { + // An abort also ends the stream early, but that is not an error. if (chatOptions.request?.signal?.aborted) { return } diff --git a/packages/ai-bedrock/src/converse/stream-processor.ts b/packages/ai-bedrock/src/converse/stream-processor.ts index 0895247076..4a6b858e97 100644 --- a/packages/ai-bedrock/src/converse/stream-processor.ts +++ b/packages/ai-bedrock/src/converse/stream-processor.ts @@ -31,7 +31,9 @@ export function throwIfConverseStreamError(ev: ConverseStreamOutput): void { /** Map Converse blocks to run, text, reasoning, and tool events. * Keep signatures and encrypted bytes separate for each contentBlockIndex. - * Finish after trailing usage events. The adapter handles thrown errors. + * End with RUN_FINISHED after trailing usage events, or with RUN_ERROR + * `incomplete-stream` when the stream ends without `messageStop`. An aborted + * request gets no terminal event. The adapter handles thrown errors. */ export async function* processConverseStream( stream: AsyncIterable, @@ -83,8 +85,8 @@ export async function* processConverseStream( // single terminal RUN_FINISHED, matching openai-base's deferred-finish // contract (usage may arrive after the finish signal). let usage: TokenUsage | undefined + // Set only by `messageStop`, so `undefined` means the stream was cut off. let finishReason: NonNullable | undefined - let sawMessageStop = false // The model filled its context window before it finished (stopReason // `model_context_window_exceeded`). The answer is cut off, so the run ends // with a RUN_ERROR instead of a clean RUN_FINISHED. @@ -292,7 +294,6 @@ export async function* processConverseStream( } if ('messageStop' in ev) { - sawMessageStop = true const stopReason: string | undefined = ev.messageStop?.stopReason contextWindowExceeded = stopReason === 'model_context_window_exceeded' // Map Converse stopReason to AG-UI's narrower finishReason vocabulary. @@ -325,7 +326,7 @@ export async function* processConverseStream( // the turn actually reached messageStop. If the stream was cut off before // messageStop, leave unclosed tool calls unfinished so partial JSON is not // emitted as a completed call. - if (sawMessageStop) { + if (finishReason !== undefined) { for (const [index, toolCall] of toolCallsByIndex) { if (!toolCall.started) continue yield { @@ -366,13 +367,15 @@ export async function* processConverseStream( return } - if (!sawMessageStop) { + if (finishReason === undefined) { + // An abort also ends the stream early, but that is not an error. if (signal?.aborted) { return } const message = 'Bedrock Converse stream ended without messageStop' yield { type: EventType.RUN_ERROR, + runId, ...(model && { model }), timestamp: Date.now(), message, @@ -390,7 +393,7 @@ export async function* processConverseStream( runId, threadId, timestamp: Date.now(), - finishReason: finishReason ?? 'stop', + finishReason, ...(usage && { usage }), } } diff --git a/packages/ai-bedrock/tests/converse/incomplete-stream.test.ts b/packages/ai-bedrock/tests/converse/incomplete-stream.test.ts index 21a7dd3ee8..31d520b39a 100644 --- a/packages/ai-bedrock/tests/converse/incomplete-stream.test.ts +++ b/packages/ai-bedrock/tests/converse/incomplete-stream.test.ts @@ -2,10 +2,7 @@ import { describe, expect, it } from 'vitest' import { EventType, chat } from '@tanstack/ai' import { resolveDebugOption } from '@tanstack/ai/adapter-internals' import { BedrockConverseTextAdapter } from '../../src/adapters/converse-text' -import type { - ConverseStreamCommandInput, - ConverseStreamOutput, -} from '@aws-sdk/client-bedrock-runtime' +import type { ConverseStreamOutput } from '@aws-sdk/client-bedrock-runtime' import type { StreamChunk } from '@tanstack/ai' const model = 'us.amazon.nova-pro-v1:0' @@ -36,167 +33,111 @@ const cutEvents: Array = [ }, ] -const completeEvents: Array = [ - ...cutEvents, - { contentBlockStop: { contentBlockIndex: 1 } }, - { messageStop: { stopReason: 'tool_use' } }, - { metadata: { usage: { inputTokens: 5, outputTokens: 6, totalTokens: 11 } } }, -] - class StubAdapter extends BedrockConverseTextAdapter { - events: Array = [] - - protected override async sendStream( - _input: ConverseStreamCommandInput, - ): Promise> { - const events = this.events + protected override async sendStream(): Promise< + AsyncIterable + > { return (async function* () { - for (const event of events) yield event as ConverseStreamOutput + for (const event of cutEvents) yield event as ConverseStreamOutput })() } } -async function runChat(events: Array) { - const adapter = new StubAdapter({ apiKey: 'k' }, model) - adapter.events = events +const adapter = new StubAdapter({ apiKey: 'k' }, model) + +const chatOptions = (signal?: AbortSignal) => ({ + threadId: 'thread-1', + logger: resolveDebugOption(false), + model, + messages: [{ role: 'user' as const, content: 'Clean up /data/repo' }], + ...(signal && { request: { signal } }), +}) + +const outputSchema = { type: 'object', properties: { n: { type: 'number' } } } + +/** Collect a stream. With a controller, abort as soon as the first chunk arrives. */ +async function collect( + stream: AsyncIterable, + controller?: AbortController, +) { const chunks: Array = [] - const calls = { finish: 0, error: 0 } - for await (const chunk of chat({ - adapter, - threadId: 'repro', - messages: [{ role: 'user', content: 'Clean up /data/repo' }], - middleware: [ - { - name: 'observe', - onFinish: () => { - calls.finish++ - }, - onError: () => { - calls.error++ - }, - }, - ], - })) { + for await (const chunk of stream) { chunks.push(chunk) + controller?.abort() } - return { chunks, calls } + return chunks } +const isIncomplete = (chunk: StreamChunk | undefined) => + chunk?.type === EventType.RUN_ERROR && chunk.code === 'incomplete-stream' + describe('Bedrock Converse stream that ends without messageStop', () => { - it('ends the run with an incomplete-stream RUN_ERROR and skips onFinish', async () => { - const { chunks, calls } = await runChat(cutEvents) - expect(chunks.at(-1)).toMatchObject({ - type: 'RUN_ERROR', - code: 'incomplete-stream', - }) - expect(chunks.some((chunk) => chunk.type === 'RUN_FINISHED')).toBe(false) + it('ends chat() with incomplete-stream, keeps the text, and skips onFinish', async () => { + const calls = { finish: 0, error: 0 } + const chunks = await collect( + chat({ + adapter, + threadId: 'repro', + messages: [{ role: 'user', content: 'Clean up /data/repo' }], + middleware: [ + { + name: 'observe', + onFinish: () => { + calls.finish++ + }, + onError: () => { + calls.error++ + }, + }, + ], + }), + ) + const types = chunks.map((chunk) => chunk.type) + expect(isIncomplete(chunks.at(-1))).toBe(true) + expect(types).not.toContain(EventType.RUN_FINISHED) + expect(types).not.toContain(EventType.TOOL_CALL_END) + expect(types).toContain(EventType.TEXT_MESSAGE_END) expect(calls).toEqual({ finish: 0, error: 1 }) }) - it('does not close a tool call whose input never finished', async () => { - const { chunks } = await runChat(cutEvents) - expect(chunks.some((chunk) => chunk.type === 'TOOL_CALL_END')).toBe(false) - }) - - it('keeps the partial text and closes TEXT_MESSAGE_END', async () => { - const { chunks } = await runChat(cutEvents) - expect( - chunks.some( - (chunk) => - chunk.type === 'TEXT_MESSAGE_CONTENT' && - chunk.delta === 'Let me clean that up.', - ), - ).toBe(true) - expect(chunks.some((chunk) => chunk.type === 'TEXT_MESSAGE_END')).toBe(true) - }) - - it('still finishes a stream that sent messageStop', async () => { - const { chunks, calls } = await runChat(completeEvents) - const last = chunks.at(-1) - expect(last?.type).toBe('RUN_FINISHED') - expect( - (last?.metadata as { tanstack?: { finishReason?: string } } | undefined) - ?.tanstack?.finishReason, - ).toBe('tool_calls') - expect(chunks.some((chunk) => chunk.type === 'TOOL_CALL_END')).toBe(true) - expect(calls).toEqual({ finish: 1, error: 0 }) - }) - - it('does not report an abort as an incomplete stream', async () => { + it('does not report an aborted chatStream', async () => { const controller = new AbortController() - class AbortableStubAdapter extends BedrockConverseTextAdapter { - protected override async sendStream(): Promise< - AsyncIterable - > { - return (async function* () { - yield cutEvents[0] as ConverseStreamOutput - yield cutEvents[1] as ConverseStreamOutput - })() - } - } - - const adapter = new AbortableStubAdapter({ apiKey: 'k' }, model) - const chunks: Array = [] - for await (const chunk of adapter.chatStream({ - threadId: 'thread-1', - logger: resolveDebugOption(false), - model, - messages: [{ role: 'user', content: 'Hi' }], - request: { signal: controller.signal }, - })) { - chunks.push(chunk) - if (chunk.type === EventType.TEXT_MESSAGE_CONTENT) controller.abort() - } - - expect( - chunks.some( - (chunk) => - chunk.type === EventType.RUN_ERROR && - chunk.code === 'incomplete-stream', - ), - ).toBe(false) + const chunks = await collect( + adapter.chatStream(chatOptions(controller.signal)), + controller, + ) + expect(chunks.some((chunk) => chunk.type === EventType.RUN_ERROR)).toBe( + false, + ) expect(chunks.some((chunk) => chunk.type === EventType.RUN_FINISHED)).toBe( false, ) }) - it('reports incomplete-stream on structuredOutputStream when messageStop is missing', async () => { - const adapter = new StubAdapter({ apiKey: 'k' }, model) - adapter.events = [ - { messageStart: { role: 'assistant' } }, - { - contentBlockStart: { - contentBlockIndex: 0, - start: { toolUse: { toolUseId: 's', name: 'structured_output' } }, - }, - }, - { - contentBlockDelta: { - contentBlockIndex: 0, - delta: { toolUse: { input: '{"n":' } }, - }, - }, - ] - - const chunks: Array<{ type: string; code?: string }> = [] - for await (const chunk of adapter.structuredOutputStream({ - chatOptions: { - threadId: 'thread-1', - logger: resolveDebugOption(false), - model, - messages: [{ role: 'user', content: 'go' }], - }, - outputSchema: { type: 'object', properties: { n: { type: 'number' } } }, - })) { - chunks.push(chunk as { type: string; code?: string }) - } - - expect(chunks.at(-1)).toMatchObject({ - type: EventType.RUN_ERROR, - code: 'incomplete-stream', - }) + it('ends structuredOutputStream with incomplete-stream', async () => { + const chunks = await collect( + adapter.structuredOutputStream({ + chatOptions: chatOptions(), + outputSchema, + }), + ) + expect(isIncomplete(chunks.at(-1))).toBe(true) expect(chunks.some((chunk) => chunk.type === EventType.RUN_FINISHED)).toBe( false, ) }) + + it('does not report an aborted structuredOutputStream', async () => { + const controller = new AbortController() + const chunks = await collect( + adapter.structuredOutputStream({ + chatOptions: chatOptions(controller.signal), + outputSchema, + }), + controller, + ) + expect(chunks.some((chunk) => chunk.type === EventType.RUN_ERROR)).toBe( + false, + ) + }) }) diff --git a/packages/ai-bedrock/tests/converse/stream-processor.test.ts b/packages/ai-bedrock/tests/converse/stream-processor.test.ts index 2e75f7abf1..be463c46e1 100644 --- a/packages/ai-bedrock/tests/converse/stream-processor.test.ts +++ b/packages/ai-bedrock/tests/converse/stream-processor.test.ts @@ -276,6 +276,65 @@ describe('processConverseStream', () => { }) }) + it('ends a stream that has no messageStop with incomplete-stream', async () => { + const events = await collect( + { messageStart: { role: 'assistant' } }, + { + contentBlockDelta: { delta: { text: 'partial' }, contentBlockIndex: 0 }, + }, + { + contentBlockStart: { + start: { toolUse: { toolUseId: 't1', name: 'rm' } }, + contentBlockIndex: 1, + }, + }, + { + contentBlockDelta: { + delta: { toolUse: { input: '{"a":' } }, + contentBlockIndex: 1, + }, + }, + { + contentBlockDelta: { + delta: { reasoningContent: { text: 'think' } }, + contentBlockIndex: 2, + }, + }, + { + metadata: { + usage: { inputTokens: 3, outputTokens: 2, totalTokens: 5 }, + }, + }, + // No contentBlockStop, no messageStop: the stream just ends. + ) + const types = events.map((e) => e.type) + expect(types).not.toContain(EventType.TOOL_CALL_END) + expect(types).not.toContain(EventType.RUN_FINISHED) + expect(types).toContain(EventType.TEXT_MESSAGE_END) + expect(types).toContain(EventType.REASONING_END) + expect(events.at(-1)).toMatchObject({ + type: EventType.RUN_ERROR, + runId: 'id-0', + code: 'incomplete-stream', + error: { code: 'incomplete-stream' }, + usage: { totalTokens: 5 }, + }) + }) + + it('ends an aborted stream with no terminal event', async () => { + const controller = new AbortController() + controller.abort() + const types: Array = [] + for await (const c of processConverseStream( + gen({ messageStart: { role: 'assistant' } }), + counter(), + { threadId: 'thread-1', signal: controller.signal }, + )) { + types.push(c.type) + } + expect(types).toEqual([EventType.RUN_STARTED]) + }) + it('drains a tool call that never received contentBlockStop when messageStop arrived', async () => { const events = await collect( { diff --git a/testing/e2e/global-setup.ts b/testing/e2e/global-setup.ts index 4bbd3208e1..1a32fe9570 100644 --- a/testing/e2e/global-setup.ts +++ b/testing/e2e/global-setup.ts @@ -183,6 +183,10 @@ export default async function globalSetup() { // which request sections ended with a `cachePoint` block and answers with // Bedrock's cache usage counters; the companion spec asserts both. mock.mount('/bedrock-converse-cache', bedrockConverseCacheMount()) + mock.mount( + '/bedrock-converse-incomplete-stream', + bedrockConverseIncompleteStreamMount(), + ) mock.mount('/bedrock-rerank', bedrockRerankMount()) // decide() usage on a failed answer mapping. aimock has no OpenAI Decisions @@ -2880,6 +2884,75 @@ function readBody(req: http.IncomingMessage): Promise { }) } +const utf8 = new TextEncoder() +const converseCodec = new EventStreamCodec( + (bytes) => new TextDecoder().decode(bytes), + (text) => utf8.encode(text), +) +/** One `vnd.amazon.eventstream` frame of a Converse stream. */ +const converseFrame = (eventType: string, payload: unknown): Buffer => + Buffer.from( + converseCodec.encode({ + headers: { + ':event-type': { type: 'string', value: eventType }, + ':message-type': { type: 'string', value: 'event' }, + ':content-type': { type: 'string', value: 'application/json' }, + }, + body: utf8.encode(JSON.stringify(payload)), + }), + ) + +/** + * Answers `POST /cut/model/{modelId}/converse-stream` with text and a tool call + * whose input is not finished, then ends the body with no `messageStop`, as + * when a proxy drops the stream. `/complete/...` closes the call and sends + * `messageStop` too. + */ +function bedrockConverseIncompleteStreamMount(): Mountable { + return { + async handleRequest(req, res, pathname) { + const scenario = /^\/(cut|complete)\/model\/[^/]+\/converse-stream$/.exec( + pathname, + )?.[1] + if (req.method !== 'POST' || !scenario) return false + res.statusCode = 200 + res.setHeader('Content-Type', 'application/vnd.amazon.eventstream') + res.write(converseFrame('messageStart', { role: 'assistant' })) + res.write( + converseFrame('contentBlockDelta', { + contentBlockIndex: 0, + delta: { text: 'partial' }, + }), + ) + res.write(converseFrame('contentBlockStop', { contentBlockIndex: 0 })) + res.write( + converseFrame('contentBlockStart', { + contentBlockIndex: 1, + start: { toolUse: { toolUseId: 'tooluse_1', name: 'lookup' } }, + }), + ) + res.write( + converseFrame('contentBlockDelta', { + contentBlockIndex: 1, + delta: { toolUse: { input: '{"query": "par' } }, + }), + ) + if (scenario === 'complete') { + res.write( + converseFrame('contentBlockDelta', { + contentBlockIndex: 1, + delta: { toolUse: { input: 'is"}' } }, + }), + ) + res.write(converseFrame('contentBlockStop', { contentBlockIndex: 1 })) + res.write(converseFrame('messageStop', { stopReason: 'tool_use' })) + } + res.end() + return true + }, + } +} + /** * Answers `POST /model/{modelId}/converse-stream` with a fixed Converse event * stream. The text block carries a JSON report of where the request placed @@ -2888,22 +2961,6 @@ function readBody(req: http.IncomingMessage): Promise { * on a cache hit. */ function bedrockConverseCacheMount(): Mountable { - const utf8 = new TextEncoder() - const codec = new EventStreamCodec( - (bytes) => new TextDecoder().decode(bytes), - (text) => utf8.encode(text), - ) - const frame = (eventType: string, payload: unknown): Buffer => - Buffer.from( - codec.encode({ - headers: { - ':event-type': { type: 'string', value: eventType }, - ':message-type': { type: 'string', value: 'event' }, - ':content-type': { type: 'string', value: 'application/json' }, - }, - body: utf8.encode(JSON.stringify(payload)), - }), - ) const endsWithCachePoint = (blocks: unknown): boolean => { if (!Array.isArray(blocks) || blocks.length === 0) return false const last: unknown = blocks[blocks.length - 1] @@ -2938,18 +2995,18 @@ function bedrockConverseCacheMount(): Mountable { res.statusCode = 200 res.setHeader('Content-Type', 'application/vnd.amazon.eventstream') - res.write(frame('messageStart', { role: 'assistant' })) + res.write(converseFrame('messageStart', { role: 'assistant' })) res.write( - frame('contentBlockDelta', { + converseFrame('contentBlockDelta', { contentBlockIndex: 0, delta: { text: JSON.stringify(observed) }, }), ) - res.write(frame('contentBlockStop', { contentBlockIndex: 0 })) - res.write(frame('messageStop', { stopReason: 'end_turn' })) + res.write(converseFrame('contentBlockStop', { contentBlockIndex: 0 })) + res.write(converseFrame('messageStop', { stopReason: 'end_turn' })) // Values from a real cache hit: inputTokens is the uncached remainder. res.write( - frame('metadata', { + converseFrame('metadata', { usage: { inputTokens: 3, outputTokens: 4, diff --git a/testing/e2e/src/routeTree.gen.ts b/testing/e2e/src/routeTree.gen.ts index 88329adf2d..386fe19b4a 100644 --- a/testing/e2e/src/routeTree.gen.ts +++ b/testing/e2e/src/routeTree.gen.ts @@ -84,6 +84,7 @@ import { Route as ApiArktypeToolWireRouteImport } from './routes/api.arktype-too import { Route as ApiAudioRouteImport } from './routes/api.audio' import { Route as ApiAzureOpenaiWireRouteImport } from './routes/api.azure-openai-wire' import { Route as ApiBedrockConverseCacheRouteImport } from './routes/api.bedrock-converse-cache' +import { Route as ApiBedrockConverseIncompleteStreamRouteImport } from './routes/api.bedrock-converse-incomplete-stream' import { Route as ApiBedrockConverseTruncatedToolCallRouteImport } from './routes/api.bedrock-converse-truncated-tool-call' import { Route as ApiBedrockRerankRouteImport } from './routes/api.bedrock-rerank' import { Route as ApiByokChatRouteImport } from './routes/api.byok-chat' @@ -650,6 +651,12 @@ const ApiBedrockConverseCacheRoute = ApiBedrockConverseCacheRouteImport.update({ path: '/api/bedrock-converse-cache', getParentRoute: () => rootRouteImport, } as any) +const ApiBedrockConverseIncompleteStreamRoute = + ApiBedrockConverseIncompleteStreamRouteImport.update({ + id: '/api/bedrock-converse-incomplete-stream', + path: '/api/bedrock-converse-incomplete-stream', + getParentRoute: () => rootRouteImport, + } as any) const ApiBedrockConverseTruncatedToolCallRoute = ApiBedrockConverseTruncatedToolCallRouteImport.update({ id: '/api/bedrock-converse-truncated-tool-call', @@ -1656,6 +1663,7 @@ export interface FileRoutesByFullPath { '/api/audio': typeof ApiAudioRouteWithChildren '/api/azure-openai-wire': typeof ApiAzureOpenaiWireRoute '/api/bedrock-converse-cache': typeof ApiBedrockConverseCacheRoute + '/api/bedrock-converse-incomplete-stream': typeof ApiBedrockConverseIncompleteStreamRoute '/api/bedrock-converse-truncated-tool-call': typeof ApiBedrockConverseTruncatedToolCallRoute '/api/bedrock-rerank': typeof ApiBedrockRerankRoute '/api/byok-chat': typeof ApiByokChatRoute @@ -1909,6 +1917,7 @@ export interface FileRoutesByTo { '/api/audio': typeof ApiAudioRouteWithChildren '/api/azure-openai-wire': typeof ApiAzureOpenaiWireRoute '/api/bedrock-converse-cache': typeof ApiBedrockConverseCacheRoute + '/api/bedrock-converse-incomplete-stream': typeof ApiBedrockConverseIncompleteStreamRoute '/api/bedrock-converse-truncated-tool-call': typeof ApiBedrockConverseTruncatedToolCallRoute '/api/bedrock-rerank': typeof ApiBedrockRerankRoute '/api/byok-chat': typeof ApiByokChatRoute @@ -2163,6 +2172,7 @@ export interface FileRoutesById { '/api/audio': typeof ApiAudioRouteWithChildren '/api/azure-openai-wire': typeof ApiAzureOpenaiWireRoute '/api/bedrock-converse-cache': typeof ApiBedrockConverseCacheRoute + '/api/bedrock-converse-incomplete-stream': typeof ApiBedrockConverseIncompleteStreamRoute '/api/bedrock-converse-truncated-tool-call': typeof ApiBedrockConverseTruncatedToolCallRoute '/api/bedrock-rerank': typeof ApiBedrockRerankRoute '/api/byok-chat': typeof ApiByokChatRoute @@ -2418,6 +2428,7 @@ export interface FileRouteTypes { | '/api/audio' | '/api/azure-openai-wire' | '/api/bedrock-converse-cache' + | '/api/bedrock-converse-incomplete-stream' | '/api/bedrock-converse-truncated-tool-call' | '/api/bedrock-rerank' | '/api/byok-chat' @@ -2671,6 +2682,7 @@ export interface FileRouteTypes { | '/api/audio' | '/api/azure-openai-wire' | '/api/bedrock-converse-cache' + | '/api/bedrock-converse-incomplete-stream' | '/api/bedrock-converse-truncated-tool-call' | '/api/bedrock-rerank' | '/api/byok-chat' @@ -2924,6 +2936,7 @@ export interface FileRouteTypes { | '/api/audio' | '/api/azure-openai-wire' | '/api/bedrock-converse-cache' + | '/api/bedrock-converse-incomplete-stream' | '/api/bedrock-converse-truncated-tool-call' | '/api/bedrock-rerank' | '/api/byok-chat' @@ -3178,6 +3191,7 @@ export interface RootRouteChildren { ApiAudioRoute: typeof ApiAudioRouteWithChildren ApiAzureOpenaiWireRoute: typeof ApiAzureOpenaiWireRoute ApiBedrockConverseCacheRoute: typeof ApiBedrockConverseCacheRoute + ApiBedrockConverseIncompleteStreamRoute: typeof ApiBedrockConverseIncompleteStreamRoute ApiBedrockConverseTruncatedToolCallRoute: typeof ApiBedrockConverseTruncatedToolCallRoute ApiBedrockRerankRoute: typeof ApiBedrockRerankRoute ApiByokChatRoute: typeof ApiByokChatRoute @@ -3879,6 +3893,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ApiBedrockConverseCacheRouteImport parentRoute: typeof rootRouteImport } + '/api/bedrock-converse-incomplete-stream': { + id: '/api/bedrock-converse-incomplete-stream' + path: '/api/bedrock-converse-incomplete-stream' + fullPath: '/api/bedrock-converse-incomplete-stream' + preLoaderRoute: typeof ApiBedrockConverseIncompleteStreamRouteImport + parentRoute: typeof rootRouteImport + } '/api/bedrock-converse-truncated-tool-call': { id: '/api/bedrock-converse-truncated-tool-call' path: '/api/bedrock-converse-truncated-tool-call' @@ -5249,6 +5270,8 @@ const rootRouteChildren: RootRouteChildren = { ApiAudioRoute: ApiAudioRouteWithChildren, ApiAzureOpenaiWireRoute: ApiAzureOpenaiWireRoute, ApiBedrockConverseCacheRoute: ApiBedrockConverseCacheRoute, + ApiBedrockConverseIncompleteStreamRoute: + ApiBedrockConverseIncompleteStreamRoute, ApiBedrockConverseTruncatedToolCallRoute: ApiBedrockConverseTruncatedToolCallRoute, ApiBedrockRerankRoute: ApiBedrockRerankRoute, diff --git a/testing/e2e/src/routes/api.bedrock-converse-incomplete-stream.ts b/testing/e2e/src/routes/api.bedrock-converse-incomplete-stream.ts new file mode 100644 index 0000000000..0f54bcd402 --- /dev/null +++ b/testing/e2e/src/routes/api.bedrock-converse-incomplete-stream.ts @@ -0,0 +1,86 @@ +import { createFileRoute } from '@tanstack/react-router' +import { chat, toolDefinition } from '@tanstack/ai' +import { BedrockConverseTextAdapter } from '@tanstack/ai-bedrock' +import { NodeHttpHandler } from '@smithy/node-http-handler' +import { z } from 'zod' +import type { ResolvedBedrockAuth } from '@tanstack/ai-bedrock' + +const LLMOCK_DEFAULT_BASE = process.env.LLMOCK_URL || 'http://127.0.0.1:4010' +const MODEL = 'us.anthropic.claude-haiku-4-5-20251001-v1:0' + +/** HTTP/1.1, because aimock does not speak HTTP/2 (see the cache route). */ +class Http1ConverseAdapter extends BedrockConverseTextAdapter { + protected override buildClientConfig( + resolved: ResolvedBedrockAuth, + region: string, + endpoint: string | undefined, + ) { + return { + ...super.buildClientConfig(resolved, region, endpoint), + requestHandler: new NodeHttpHandler(), + } + } +} + +/** + * POST ?scenario=cut runs chat() against a Converse stream that ends in the + * middle of a tool call, with no `messageStop`. `?scenario=complete` gets the + * whole stream. The mock is `bedrockConverseIncompleteStreamMount` in + * global-setup.ts. + */ +export const Route = createFileRoute('/api/bedrock-converse-incomplete-stream')( + { + server: { + handlers: { + POST: async ({ request }) => { + const scenario = new URL(request.url).searchParams.get('scenario') + const adapter = new Http1ConverseAdapter( + { + apiKey: 'sk-e2e-test-dummy-key', + baseURL: `${LLMOCK_DEFAULT_BASE}/bedrock-converse-incomplete-stream/${scenario}`, + region: 'us-east-1', + }, + MODEL, + ) + // No server implementation: a complete call stops the run for the client. + const lookup = toolDefinition({ + name: 'lookup', + description: 'Looks something up.', + inputSchema: z.object({ query: z.string() }), + }) + const result = { + events: new Array(), + text: '', + finishCount: 0, + errorCount: 0, + errorCode: '', + } + for await (const event of chat({ + threadId: 'bedrock-converse-incomplete-stream', + adapter, + tools: [lookup], + messages: [{ role: 'user', content: 'Reply' }], + debug: false, + middleware: [ + { + name: 'observe', + onFinish: () => { + result.finishCount++ + }, + onError: () => { + result.errorCount++ + }, + }, + ], + })) { + result.events.push(event.type) + if (event.type === 'TEXT_MESSAGE_CONTENT') + result.text += event.delta + if (event.type === 'RUN_ERROR') result.errorCode = event.code ?? '' + } + return Response.json(result) + }, + }, + }, + }, +) diff --git a/testing/e2e/tests/bedrock-converse-incomplete-stream.spec.ts b/testing/e2e/tests/bedrock-converse-incomplete-stream.spec.ts new file mode 100644 index 0000000000..b06e2f3768 --- /dev/null +++ b/testing/e2e/tests/bedrock-converse-incomplete-stream.spec.ts @@ -0,0 +1,38 @@ +import { test, expect } from './fixtures' + +// The mock is `bedrockConverseIncompleteStreamMount` in global-setup.ts. +test('Bedrock Converse reports a stream that ends without messageStop', async ({ + request, +}) => { + const response = await request.post( + '/api/bedrock-converse-incomplete-stream?scenario=cut', + ) + expect(response.ok()).toBe(true) + const result = await response.json() + expect(result).toMatchObject({ + text: 'partial', + finishCount: 0, + errorCount: 1, + errorCode: 'incomplete-stream', + }) + expect(result.events.at(-1)).toBe('RUN_ERROR') + expect(result.events).not.toContain('RUN_FINISHED') + expect(result.events).not.toContain('TOOL_CALL_END') +}) + +test('Bedrock Converse still finishes a complete stream', async ({ + request, +}) => { + const response = await request.post( + '/api/bedrock-converse-incomplete-stream?scenario=complete', + ) + expect(response.ok()).toBe(true) + const result = await response.json() + expect(result).toMatchObject({ + text: 'partial', + finishCount: 1, + errorCount: 0, + }) + expect(result.events).toContain('TOOL_CALL_END') + expect(result.events.at(-1)).toBe('RUN_FINISHED') +})