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

toServerSentEventsResponse.md

58 lines1.6 KB

1---
2id: toServerSentEventsResponse
3title: toServerSentEventsResponse
4---
5​
6```ts
7function toServerSentEventsResponse<TOffset>(stream, init?): Response;
8```
9​
10Defined in: [packages/ai/src/stream-to-response.ts:712](https://github.com/TanStack/ai/blob/main/packages/ai/src/stream-to-response.ts#L712)
11​
12Convert a StreamChunk async iterable to a Response in Server-Sent Events format
13​
14This creates a Response that emits chunks in SSE format:
15- Each chunk is prefixed with "data: "
16- Each chunk is followed by "\n\n"
17- Stream ends when the underlying iterable is exhausted (RUN_FINISHED is the terminal event)
18​
19Pass a `durability` sink (`memoryStream(request)` / `durableStream(request)`)
20to make the stream resumable: fresh runs are appended to the log and each SSE
21event is tagged with an `id:` offset; a reconnect (native `Last-Event-ID`) or
22a `?offset` join replays from the log without re-running the producer. `batch`
23controls how many chunks are buffered per `append` (default 32).
24​
25## Type Parameters
26​
27### TOffset
28​
29`TOffset` *extends* `string` = `string`
30​
31## Parameters
32​
33### stream
34​
35`AsyncIterable`\<[`AGUIEvent`](../type-aliases/AGUIEvent.md)\>
36​
37AsyncIterable of StreamChunks from chat()
38​
39### init?
40​
41`ResponseInit` & `object`
42​
43Optional Response initialization options (including `abortController`, `durability` with its optional `batch`, and `debug`)
44​
45## Returns
46​
47`Response`
48​
49Response in Server-Sent Events format
50​
51## Example
52​
53```typescript
54export async function POST(request: Request) {
55 const stream = chat({ adapter: openaiText('gpt-5.5'), messages: [...] });
56 return toServerSentEventsResponse(stream, { durability: { adapter: memoryStream(request) } });
58```