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

toServerSentEventsResponse.md

59 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:1059
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), and
24`batchWaitMs` how long a buffered chunk waits for more (default 50).
25​
26## Type Parameters
27​
28### TOffset
29​
30`TOffset` *extends* `string` = `string`
31​
32## Parameters
33​
34### stream
35​
36`AsyncIterable`\<[`AGUIEvent`](../type-aliases/AGUIEvent.md)\>
37​
38AsyncIterable of StreamChunks from chat()
39​
40### init?
41​
42`ResponseInit` & `object`
43​
44Optional Response initialization options (including `abortController`, `durability` with its optional `batch` and `batchWaitMs`, and `debug`)
45​
46## Returns
47​
48`Response`
49​
50Response in Server-Sent Events format
51​
52## Example
53​
54```typescript
55export async function POST(request: Request) {
56 const stream = chat({ adapter: openaiText('gpt-5.5'), messages: [...] });
57 return toServerSentEventsResponse(stream, { durability: { adapter: memoryStream(request) } });
59```