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
5 changes: 5 additions & 0 deletions .changeset/bedrock-converse-incomplete-stream.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions docs/chat/streaming.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`. 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:
Expand Down
2 changes: 1 addition & 1 deletion docs/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@
"label": "Streaming",
"to": "chat/streaming",
"addedAt": "2026-04-15",
"updatedAt": "2026-11-09"
"updatedAt": "2026-12-04"
},
{
"label": "Stream Events",
Expand Down
24 changes: 23 additions & 1 deletion packages/ai-bedrock/src/adapters/converse-text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ||
Expand Down Expand Up @@ -407,7 +408,8 @@ export class BedrockConverseTextAdapter<
let hasEmittedRunStarted = false
let hasEmittedTextMessageStart = false
let accumulatedRaw = ''
let finishReason: 'stop' | 'length' | 'content_filter' = 'stop'
// 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
Expand Down Expand Up @@ -522,6 +524,26 @@ export class BedrockConverseTextAdapter<
}
}

if (finishReason === undefined) {
// An abort also ends the stream early, but that is not an error.
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') {
Expand Down
60 changes: 46 additions & 14 deletions packages/ai-bedrock/src/converse/stream-processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,22 @@ 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<ConverseStreamOutput>,
newMessageId: () => string,
lifecycle: { threadId: string; parentRunId?: string; model?: string },
lifecycle: {
threadId: string
parentRunId?: string
model?: string
signal?: AbortSignal | null
},
): AsyncIterable<AdapterYieldChunk> {
const runId = newMessageId()
const { threadId, parentRunId, model } = lifecycle
const { threadId, parentRunId, model, signal } = lifecycle
const messageId = newMessageId()

let hasEmittedRunStarted = false
Expand Down Expand Up @@ -78,6 +85,7 @@ 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<AdapterYieldChunk['finishReason']> | undefined
// The model filled its context window before it finished (stopReason
// `model_context_window_exceeded`). The answer is cut off, so the run ends
Expand Down Expand Up @@ -314,17 +322,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 (finishReason !== undefined) {
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.
Expand Down Expand Up @@ -354,14 +367,33 @@ export async function* processConverseStream(
return
}

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,
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 {
type: EventType.RUN_FINISHED,
runId,
threadId,
timestamp: Date.now(),
finishReason: finishReason ?? 'stop',
finishReason,
...(usage && { usage }),
}
}
143 changes: 143 additions & 0 deletions packages/ai-bedrock/tests/converse/incomplete-stream.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
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 { 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<Fixture> = [
{ 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' } },
},
},
]

class StubAdapter extends BedrockConverseTextAdapter<typeof model> {
protected override async sendStream(): Promise<
AsyncIterable<ConverseStreamOutput>
> {
return (async function* () {
for (const event of cutEvents) yield event as ConverseStreamOutput
})()
}
}

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<StreamChunk>,
controller?: AbortController,
) {
const chunks: Array<StreamChunk> = []
for await (const chunk of stream) {
chunks.push(chunk)
controller?.abort()
}
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 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 report an aborted chatStream', async () => {
const controller = new AbortController()
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('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,
)
})
})
Loading