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

stream-processor.ts

374 lines11.5 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/** Map Converse blocks to run, text, reasoning, and tool events.
33 * Keep signatures and encrypted bytes separate for each contentBlockIndex.
34 * Finish after trailing usage events. The adapter handles thrown errors.
35 */
36export async function* processConverseStream(
37 stream: AsyncIterable<ConverseStreamOutput>,
38 newMessageId: () => string,
39 lifecycle: { threadId?: string; parentRunId?: string; model?: string } = {},
40): AsyncIterable<AdapterYieldChunk> {
41 const runId = newMessageId()
42 const threadId = lifecycle.threadId ?? newMessageId()
43 const { parentRunId, model } = lifecycle
44 const messageId = newMessageId()
45​
46 let hasEmittedRunStarted = false
47​
48 // Text lifecycle
49 let accumulatedContent = ''
50 let hasEmittedTextMessageStart = false
51​
52 // Reasoning lifecycle
53 const reasoningByIndex = new Map<
54 number,
55 {
56 id: string
57 text: string
58 signature: string
59 bytes: Array<Uint8Array>
60 redacted: boolean
61 closed: boolean
62 encrypted?: string
63 }
64 >()
65​
66 // Tool-call lifecycle, keyed by Converse contentBlockIndex. Converse opens a
67 // tool-use block with `contentBlockStart`, streams arg fragments via
68 // `contentBlockDelta`, and closes it with `contentBlockStop`.
69 const toolCallsByIndex = new Map<
70 number,
71 {
72 id: string
73 name: string
74 started: boolean
75 arguments: string
76 }
77 >()
78​
79 // Usage + finish-reason are captured during iteration and folded into the
80 // single terminal RUN_FINISHED, matching openai-base's deferred-finish
81 // contract (usage may arrive after the finish signal).
82 let usage: TokenUsage | undefined
83 let finishReason: NonNullable<AdapterYieldChunk['finishReason']> | undefined
84​
85 // Lazily emit RUN_STARTED exactly once, before the first content event.
86 function* ensureRunStarted(): Generator<AdapterYieldChunk> {
87 if (hasEmittedRunStarted) return
88 hasEmittedRunStarted = true
89 yield {
90 type: EventType.RUN_STARTED,
91 runId,
92 threadId,
93 parentRunId,
94 ...(model && { model }),
95 timestamp: Date.now(),
96 }
97 }
98​
99 // Close an open reasoning message before text/tool content begins, mirroring
100 // openai-base which always emits REASONING_MESSAGE_END before TEXT_MESSAGE_START.
101 function* encryptedReasoning(index: number): Generator<AdapterYieldChunk> {
102 const reasoning = reasoningByIndex.get(index)
103 if (!reasoning) return
104 const encrypted = reasoning.redacted
105 ? Buffer.concat(reasoning.bytes).toString('base64')
106 : reasoning.signature
107 if (!encrypted || encrypted === reasoning.encrypted) return
108 reasoning.encrypted = encrypted
109 yield {
110 type: EventType.REASONING_ENCRYPTED_VALUE,
111 entityId: reasoning.id,
112 subtype: 'message',
113 encryptedValue: encrypted,
114 ...(reasoning.redacted && {
115 stepId: reasoning.id.startsWith('redacted_thinking-')
116 ? reasoning.id
117 : 'redacted_thinking-' + reasoning.id,
118 }),
119 timestamp: Date.now(),
120 }
121 }
122​
123 function* closeReasoning(index?: number): Generator<AdapterYieldChunk> {
124 for (const [blockIndex, reasoning] of reasoningByIndex) {
125 if (index !== undefined && index !== blockIndex) continue
126 yield* encryptedReasoning(blockIndex)
127 if (reasoning.closed) continue
128 reasoning.closed = true
129 yield {
130 type: EventType.STEP_FINISHED,
131 stepId: reasoning.id,
132 stepName: reasoning.id,
133 delta: '',
134 content: reasoning.text,
135 timestamp: Date.now(),
136 }
137 yield {
138 type: EventType.REASONING_MESSAGE_END,
139 messageId: reasoning.id,
140 timestamp: Date.now(),
141 }
142 yield {
143 type: EventType.REASONING_END,
144 messageId: reasoning.id,
145 timestamp: Date.now(),
146 }
147 }
148 }
149​
150 for await (const ev of stream) {
151 yield* ensureRunStarted()
152​
153 // Surface in-band server/throttle/validation errors instead of dropping them.
154 throwIfConverseStreamError(ev)
155​
156 // messageStart carries only the role; no AG-UI event maps to it.
157 if ('messageStart' in ev) continue
158​
159 if ('contentBlockStart' in ev) {
160 const start = ev.contentBlockStart
161 const toolUse = start?.start?.toolUse
162 if (start && toolUse) {
163 yield* closeReasoning()
164 const id = toolUse.toolUseId ?? newMessageId()
165 const name = toolUse.name ?? ''
166 const index = start.contentBlockIndex ?? 0
167 toolCallsByIndex.set(index, {
168 id,
169 name,
170 started: true,
171 arguments: '',
172 })
173 yield {
174 type: EventType.TOOL_CALL_START,
175 toolCallId: id,
176 toolCallName: name,
177 toolName: name,
178 timestamp: Date.now(),
179 index,
180 }
181 }
182 continue
183 }
184​
185 if ('contentBlockDelta' in ev) {
186 const block = ev.contentBlockDelta
187 const delta = block?.delta
188 const index = block?.contentBlockIndex ?? 0
189​
190 // Tool-call argument fragments (partial JSON).
191 if (delta && 'toolUse' in delta && delta.toolUse?.input !== undefined) {
192 const toolCall = toolCallsByIndex.get(index)
193 if (toolCall?.started) {
194 toolCall.arguments += delta.toolUse.input
195 yield {
196 type: EventType.TOOL_CALL_ARGS,
197 toolCallId: toolCall.id,
198 timestamp: Date.now(),
199 delta: delta.toolUse.input,
200 }
201 }
202 continue
203 }
204​
205 if (delta && 'reasoningContent' in delta && delta.reasoningContent) {
206 const fragment = delta.reasoningContent
207 let reasoning = reasoningByIndex.get(index)
208 if (!reasoning) {
209 const redacted =
210 'redactedContent' in fragment &&
211 (fragment.redactedContent?.length ?? 0) > 0
212 reasoning = {
213 id: (redacted ? 'redacted_thinking-' : '') + newMessageId(),
214 text: '',
215 signature: '',
216 bytes: [],
217 redacted,
218 closed: false,
219 }
220 reasoningByIndex.set(index, reasoning)
221 yield {
222 type: EventType.STEP_STARTED,
223 stepId: reasoning.id,
224 stepName: reasoning.id,
225 stepType: 'thinking',
226 timestamp: Date.now(),
227 }
228 yield {
229 type: EventType.REASONING_MESSAGE_START,
230 messageId: reasoning.id,
231 role: 'reasoning',
232 timestamp: Date.now(),
233 }
234 }
235 if (
236 !reasoning.redacted &&
237 'text' in fragment &&
238 fragment.text !== undefined
239 ) {
240 reasoning.text += fragment.text
241 yield {
242 type: EventType.REASONING_MESSAGE_CONTENT,
243 messageId: reasoning.id,
244 delta: fragment.text,
245 timestamp: Date.now(),
246 }
247 }
248 if (
249 !reasoning.redacted &&
250 'signature' in fragment &&
251 fragment.signature !== undefined
252 )
253 reasoning.signature += fragment.signature
254 if (
255 'redactedContent' in fragment &&
256 fragment.redactedContent &&
257 fragment.redactedContent.length > 0
258 ) {
259 if (!reasoning.redacted) reasoning.encrypted = undefined
260 reasoning.redacted = true
261 reasoning.text = ''
262 reasoning.signature = ''
263 reasoning.bytes.push(fragment.redactedContent)
264 yield* encryptedReasoning(index)
265 }
266 continue
267 }
268​
269 // Text content.
270 if (delta && 'text' in delta && delta.text !== undefined) {
271 yield* closeReasoning()
272 if (!hasEmittedTextMessageStart) {
273 hasEmittedTextMessageStart = true
274 yield {
275 type: EventType.TEXT_MESSAGE_START,
276 messageId,
277 role: 'assistant',
278 timestamp: Date.now(),
279 }
280 }
281 accumulatedContent += delta.text
282 yield {
283 type: EventType.TEXT_MESSAGE_CONTENT,
284 messageId,
285 delta: delta.text,
286 content: accumulatedContent,
287 timestamp: Date.now(),
288 }
289 }
290 continue
291 }
292​
293 if ('contentBlockStop' in ev) {
294 const stopIndex = ev.contentBlockStop?.contentBlockIndex ?? 0
295 yield* closeReasoning(stopIndex)
296 const toolCall = toolCallsByIndex.get(stopIndex)
297 if (toolCall?.started) {
298 yield {
299 type: EventType.TOOL_CALL_END,
300 toolCallId: toolCall.id,
301 args: toolCall.arguments,
302 toolCallName: toolCall.name,
303 toolName: toolCall.name,
304 timestamp: Date.now(),
305 }
306 toolCallsByIndex.delete(stopIndex)
307 }
308 continue
309 }
310​
311 if ('messageStop' in ev) {
312 const stopReason = ev.messageStop?.stopReason
313 // Map Converse stopReason to AG-UI's narrower finishReason vocabulary.
314 finishReason =
315 stopReason === 'tool_use'
316 ? 'tool_calls'
317 : stopReason === 'max_tokens'
318 ? 'length'
319 : stopReason === 'content_filtered'
320 ? 'content_filter'
321 : 'stop'
322 continue
323 }
324​
325 if ('metadata' in ev) {
326 const u = ev.metadata?.usage
327 if (u) {
328 usage = buildConverseUsage(u)
329 }
330 continue
331 }
332 }
333​
334 // Stream ended (possibly without any content) — still emit RUN_STARTED so
335 // consumers always see a run lifecycle.
336 yield* ensureRunStarted()
337​
338 // Drain any tool call that opened but never received contentBlockStop.
339 for (const [index, toolCall] of toolCallsByIndex) {
340 if (!toolCall.started) continue
341 yield {
342 type: EventType.TOOL_CALL_END,
343 toolCallId: toolCall.id,
344 args: toolCall.arguments,
345 toolCallName: toolCall.name,
346 toolName: toolCall.name,
347 timestamp: Date.now(),
348 }
349 toolCallsByIndex.delete(index)
350 }
351​
352 // Close the text message lifecycle if it was opened.
353 if (hasEmittedTextMessageStart) {
354 yield {
355 type: EventType.TEXT_MESSAGE_END,
356 messageId,
357 timestamp: Date.now(),
358 }
359 }
360​
361 // Close any reasoning lifecycle that text never closed.
362 yield* closeReasoning()
363​
364 // Single terminal RUN_FINISHED. Conditional `usage` spread keeps the wire
365 // shape spec-compliant (AG-UI's `usage` is optional with no `| undefined`).
366 yield {
367 type: EventType.RUN_FINISHED,
368 runId,
369 threadId,
370 timestamp: Date.now(),
371 finishReason: finishReason ?? 'stop',
372 ...(usage && { usage }),
373 }