Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

stream-processor.ts

304 lines10.3 KB

1import { EventType } from '@tanstack/ai'
2import { buildConverseUsage } from './usage'
3import type { AdapterYieldChunk, TokenUsage } from '@tanstack/ai'
4import type { ConverseStreamOutput } from '@aws-sdk/client-bedrock-runtime'
5​
6/**
7 * Converse delivers server-side failures — throttling, request validation,
8 * mid-stream model faults, and service-unavailable — as in-band stream events
9 * rather than thrown exceptions. If they were ignored the iterator would simply
10 * end and the run would look like a clean, truncated success. Throw the
11 * underlying exception (these SDK members extend `Error`) so the adapter's
12 * `chatStream` / `structuredOutputStream` catch converts it into a `RUN_ERROR`.
13 */
14export function throwIfConverseStreamError(ev: ConverseStreamOutput): void {
15 if ('internalServerException' in ev && ev.internalServerException) {
16 throw ev.internalServerException
17 }
18 if ('modelStreamErrorException' in ev && ev.modelStreamErrorException) {
19 throw ev.modelStreamErrorException
20 }
21 if ('validationException' in ev && ev.validationException) {
22 throw ev.validationException
23 }
24 if ('throttlingException' in ev && ev.throttlingException) {
25 throw ev.throttlingException
26 }
27 if ('serviceUnavailableException' in ev && ev.serviceUnavailableException) {
28 throw ev.serviceUnavailableException
29 }
31​
32/**
33 * Maps a Bedrock Converse `ConverseStreamOutput` event stream to the TanStack
34 * AG-UI `StreamChunk` lifecycle, following `openai-base`'s `processStreamChunks`
35 * lifecycle shape so the activity layer / agent loop behave identically across
36 * providers. (Reasoning surfaces only the message-level events —
37 * `REASONING_MESSAGE_START/CONTENT/END` — which is all the core accumulator
38 * consumes; the `REASONING_START`/`REASONING_END`/`STEP_*` boundary events
39 * openai-base also emits are no-ops in the engine and are not reproduced here.)
40 *
41 * Lifecycle ownership matches openai-base: this processor emits the full
42 * success-path lifecycle itself — `RUN_STARTED` lazily before the first event,
43 * `TEXT_MESSAGE_*` / `TOOL_CALL_*` / `REASONING_MESSAGE_*` for content, and a
44 * single terminal `RUN_FINISHED` once the iterator is exhausted (so the trailing
45 * `metadata` usage event is folded into the finish event regardless of arrival
46 * order). The calling adapter only owns the catch/`RUN_ERROR` path — so any
47 * in-band Converse error event (see `throwIfConverseStreamError`) is thrown to
48 * surface there rather than ending the stream as a clean truncated success.
49 *
50 * Converse streams tool-call arguments as partial-JSON string fragments inside
51 * `contentBlockDelta.delta.toolUse.input`; each fragment is emitted as a
52 * `TOOL_CALL_ARGS` `delta`, mirroring OpenAI's `function.arguments` deltas.
53 *
54 * @param stream - The Converse event stream from `ConverseStreamCommand`.
55 * @param newMessageId - Factory for fresh ids — run, thread, message, and
56 * tool-call ids (the adapter passes `() => this.generateId()`).
57 * @param lifecycle - Incoming run lifecycle ids, threaded onto the emitted
58 * `RUN_STARTED`/`RUN_FINISHED` so the chat path matches every sibling adapter
59 * (openai-base reuses `options.threadId`/`parentRunId`). Defaults preserve the
60 * previous behaviour (fresh `threadId`, no `parentRunId`).
61 */
62export async function* processConverseStream(
63 stream: AsyncIterable<ConverseStreamOutput>,
64 newMessageId: () => string,
65 lifecycle: { threadId?: string; parentRunId?: string; model?: string } = {},
66): AsyncIterable<AdapterYieldChunk> {
67 const runId = newMessageId()
68 const threadId = lifecycle.threadId ?? newMessageId()
69 const { parentRunId, model } = lifecycle
70 const messageId = newMessageId()
71​
72 let hasEmittedRunStarted = false
73​
74 // Text lifecycle
75 let accumulatedContent = ''
76 let hasEmittedTextMessageStart = false
77​
78 // Reasoning lifecycle
79 let reasoningMessageId: string | undefined
80 let hasClosedReasoning = false
81​
82 // Tool-call lifecycle, keyed by Converse contentBlockIndex. Converse opens a
83 // tool-use block with `contentBlockStart`, streams arg fragments via
84 // `contentBlockDelta`, and closes it with `contentBlockStop`.
85 const toolCallsByIndex = new Map<
86 number,
87 { id: string; name: string; started: boolean }
88 >()
89​
90 // Usage + finish-reason are captured during iteration and folded into the
91 // single terminal RUN_FINISHED, matching openai-base's deferred-finish
92 // contract (usage may arrive after the finish signal).
93 let usage: TokenUsage | undefined
94 let finishReason: NonNullable<AdapterYieldChunk['finishReason']> | undefined
95​
96 // Lazily emit RUN_STARTED exactly once, before the first content event.
97 function* ensureRunStarted(): Generator<AdapterYieldChunk> {
98 if (hasEmittedRunStarted) return
99 hasEmittedRunStarted = true
100 yield {
101 type: EventType.RUN_STARTED,
102 runId,
103 threadId,
104 parentRunId,
105 ...(model && { model }),
106 timestamp: Date.now(),
107 }
108 }
109​
110 // Close an open reasoning message before text/tool content begins, mirroring
111 // openai-base which always emits REASONING_MESSAGE_END before TEXT_MESSAGE_START.
112 function* closeReasoning(): Generator<AdapterYieldChunk> {
113 if (reasoningMessageId && !hasClosedReasoning) {
114 hasClosedReasoning = true
115 yield {
116 type: EventType.REASONING_MESSAGE_END,
117 messageId: reasoningMessageId,
118 timestamp: Date.now(),
119 }
120 }
121 }
122​
123 for await (const ev of stream) {
124 yield* ensureRunStarted()
125​
126 // Surface in-band server/throttle/validation errors instead of dropping them.
127 throwIfConverseStreamError(ev)
128​
129 // messageStart carries only the role; no AG-UI event maps to it.
130 if ('messageStart' in ev) continue
131​
132 if ('contentBlockStart' in ev) {
133 const start = ev.contentBlockStart
134 const toolUse = start?.start?.toolUse
135 if (start && toolUse) {
136 yield* closeReasoning()
137 const id = toolUse.toolUseId ?? newMessageId()
138 const name = toolUse.name ?? ''
139 const index = start.contentBlockIndex ?? 0
140 toolCallsByIndex.set(index, {
141 id,
142 name,
143 started: true,
144 })
145 yield {
146 type: EventType.TOOL_CALL_START,
147 toolCallId: id,
148 toolCallName: name,
149 toolName: name,
150 timestamp: Date.now(),
151 index,
152 }
153 }
154 continue
155 }
156​
157 if ('contentBlockDelta' in ev) {
158 const block = ev.contentBlockDelta
159 const delta = block?.delta
160 const index = block?.contentBlockIndex ?? 0
161​
162 // Tool-call argument fragments (partial JSON).
163 if (delta && 'toolUse' in delta && delta.toolUse?.input !== undefined) {
164 const toolCall = toolCallsByIndex.get(index)
165 if (toolCall?.started) {
166 yield {
167 type: EventType.TOOL_CALL_ARGS,
168 toolCallId: toolCall.id,
169 timestamp: Date.now(),
170 delta: delta.toolUse.input,
171 }
172 }
173 continue
174 }
175​
176 // Reasoning content.
177 if (
178 delta &&
179 'reasoningContent' in delta &&
180 delta.reasoningContent &&
181 'text' in delta.reasoningContent &&
182 delta.reasoningContent.text !== undefined
183 ) {
184 if (!reasoningMessageId) {
185 reasoningMessageId = newMessageId()
186 yield {
187 type: EventType.REASONING_MESSAGE_START,
188 messageId: reasoningMessageId,
189 role: 'reasoning',
190 timestamp: Date.now(),
191 }
192 }
193 yield {
194 type: EventType.REASONING_MESSAGE_CONTENT,
195 messageId: reasoningMessageId,
196 delta: delta.reasoningContent.text,
197 timestamp: Date.now(),
198 }
199 continue
200 }
201​
202 // Text content.
203 if (delta && 'text' in delta && delta.text !== undefined) {
204 yield* closeReasoning()
205 if (!hasEmittedTextMessageStart) {
206 hasEmittedTextMessageStart = true
207 yield {
208 type: EventType.TEXT_MESSAGE_START,
209 messageId,
210 role: 'assistant',
211 timestamp: Date.now(),
212 }
213 }
214 accumulatedContent += delta.text
215 yield {
216 type: EventType.TEXT_MESSAGE_CONTENT,
217 messageId,
218 delta: delta.text,
219 content: accumulatedContent,
220 timestamp: Date.now(),
221 }
222 }
223 continue
224 }
225​
226 if ('contentBlockStop' in ev) {
227 const stopIndex = ev.contentBlockStop?.contentBlockIndex ?? 0
228 const toolCall = toolCallsByIndex.get(stopIndex)
229 if (toolCall?.started) {
230 yield {
231 type: EventType.TOOL_CALL_END,
232 toolCallId: toolCall.id,
233 toolCallName: toolCall.name,
234 toolName: toolCall.name,
235 timestamp: Date.now(),
236 }
237 toolCallsByIndex.delete(stopIndex)
238 }
239 continue
240 }
241​
242 if ('messageStop' in ev) {
243 const stopReason = ev.messageStop?.stopReason
244 // Map Converse stopReason to AG-UI's narrower finishReason vocabulary.
245 finishReason =
246 stopReason === 'tool_use'
247 ? 'tool_calls'
248 : stopReason === 'max_tokens'
249 ? 'length'
250 : stopReason === 'content_filtered'
251 ? 'content_filter'
252 : 'stop'
253 continue
254 }
255​
256 if ('metadata' in ev) {
257 const u = ev.metadata?.usage
258 if (u) {
259 usage = buildConverseUsage(u)
260 }
261 continue
262 }
263 }
264​
265 // Stream ended (possibly without any content) — still emit RUN_STARTED so
266 // consumers always see a run lifecycle.
267 yield* ensureRunStarted()
268​
269 // Drain any tool call that opened but never received contentBlockStop.
270 for (const [index, toolCall] of toolCallsByIndex) {
271 if (!toolCall.started) continue
272 yield {
273 type: EventType.TOOL_CALL_END,
274 toolCallId: toolCall.id,
275 toolCallName: toolCall.name,
276 toolName: toolCall.name,
277 timestamp: Date.now(),
278 }
279 toolCallsByIndex.delete(index)
280 }
281​
282 // Close the text message lifecycle if it was opened.
283 if (hasEmittedTextMessageStart) {
284 yield {
285 type: EventType.TEXT_MESSAGE_END,
286 messageId,
287 timestamp: Date.now(),
288 }
289 }
290​
291 // Close any reasoning lifecycle that text never closed.
292 yield* closeReasoning()
293​
294 // Single terminal RUN_FINISHED. Conditional `usage` spread keeps the wire
295 // shape spec-compliant (AG-UI's `usage` is optional with no `| undefined`).
296 yield {
297 type: EventType.RUN_FINISHED,
298 runId,
299 threadId,
300 timestamp: Date.now(),
301 finishReason: finishReason ?? 'stop',
302 ...(usage && { usage }),
303 }