MCPcopy Create free account
hub / github.com/TanStack/ai / toHttpStream

Function toHttpStream

packages/ai/src/stream-to-response.ts:171–219  ·  view source on GitHub ↗
(
  stream: AsyncIterable<StreamChunk>,
  abortController?: AbortController,
)

Source from the content-addressed store, hash-verified

169 * ```
170 */
171export function toHttpStream(
172 stream: AsyncIterable<StreamChunk>,
173 abortController?: AbortController,
174): ReadableStream<Uint8Array> {
175 const encoder = new TextEncoder()
176
177 return new ReadableStream({
178 async start(controller) {
179 try {
180 for await (const chunk of stream) {
181 // Check if stream was cancelled/aborted
182 if (abortController?.signal.aborted) {
183 break
184 }
185
186 // Send each chunk as newline-delimited JSON
187 controller.enqueue(encoder.encode(`${JSON.stringify(chunk)}\n`))
188 }
189
190 controller.close()
191 } catch (error: unknown) {
192 // Don't send error if aborted
193 if (abortController?.signal.aborted) {
194 controller.close()
195 return
196 }
197
198 // Send error event (AG-UI RUN_ERROR)
199 controller.enqueue(
200 encoder.encode(
201 `${JSON.stringify({
202 type: 'RUN_ERROR',
203 timestamp: Date.now(),
204 error: toRunErrorPayload(error),
205 })}\n`,
206 ),
207 )
208 controller.close()
209 }
210 },
211 cancel() {
212 // When the ReadableStream is cancelled (e.g., client disconnects),
213 // abort the underlying stream
214 if (abortController) {
215 abortController.abort()
216 }
217 },
218 })
219}
220
221/**
222 * Convert a StreamChunk async iterable to a Response in HTTP stream format (newline-delimited JSON)

Callers 1

toHttpResponseFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected