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

toHttpResponse.md

62 lines1.8 KB

1---
2id: toHttpResponse
3title: toHttpResponse
4---
5​
6```ts
7function toHttpResponse<TOffset>(stream, init?): Response;
8```
9​
10Defined in: [packages/ai/src/stream-to-response.ts:1128](https://github.com/TanStack/ai/blob/main/packages/ai/src/stream-to-response.ts#L1128)
11​
12Convert a StreamChunk async iterable to a Response in HTTP stream format (newline-delimited JSON)
13​
14This creates a Response that emits chunks in HTTP stream format:
15- Each chunk is JSON.stringify'd and followed by "\n"
16- No SSE formatting (no "data: " prefix)
17​
18This format is compatible with `fetchHttpStream` connection adapter.
19​
20Pass a `durability` sink (`memoryStream(request)` / `durableStream(request)`)
21to make the stream resumable: fresh runs are appended to the log and each
22NDJSON line is emitted as an `{ id, chunk }` envelope carrying an opaque
23offset; a reconnect (native `Last-Event-ID` header) or a `?offset` join
24replays from the log without re-running the producer. `batch` controls how
25many chunks are buffered per `append` (default 32). This shares the exact
26`durableStreamSource` used by `toServerSentEventsResponse` — only the wire
27encoding differs.
28​
29## Type Parameters
30​
31### TOffset
32​
33`TOffset` *extends* `string` = `string`
34​
35## Parameters
36​
37### stream
38​
39`AsyncIterable`\<[`AGUIEvent`](../type-aliases/AGUIEvent.md)\>
40​
41AsyncIterable of StreamChunks from chat()
42​
43### init?
44​
45`ResponseInit` & `object`
46​
47Optional Response initialization options (including `abortController`, `durability` with its optional `batch`, and `debug`)
48​
49## Returns
50​
51`Response`
52​
53Response in HTTP stream format (newline-delimited JSON)
54​
55## Example
56​
57```typescript
58export async function POST(request: Request) {
59 const stream = chat({ adapter: openaiText('gpt-5.5'), messages: [...] });
60 return toHttpResponse(stream, { durability: { adapter: memoryStream(request) } });
62```