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

api.resumable.ts

63 lines2.3 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 memoryStream,
6 resumeServerSentEventsResponse,
7 toServerSentEventsResponse,
8} from '@tanstack/ai'
9import { openaiText } from '@tanstack/ai-openai'
10​
11/**
12 * Resumable-streams demo endpoint.
13 *
14 * The `memoryStream(request)` durability sink records every chunk to an ordered
15 * log before delivery and tags each SSE event with an opaque `id:` offset, so a
16 * dropped connection reconnects (`Last-Event-ID`) and resumes from the log
17 * without re-running the model. The `useChat` client on /resumable needs no
18 * extra code for this; it just uses this route's connection.
19 *
20 * `memoryStream` is process-local, which is fine for a single-process demo. In
21 * production, swap it for `durableStream(request, { server })` from
22 * `@tanstack/ai-durable-stream` backed by Cloudflare Durable Streams, Electric,
23 * or any Durable Streams protocol server.
24 */
25​
26export const Route = createFileRoute('/api/resumable')({
27 server: {
28 handlers: {
29 // Fresh run (no `Last-Event-ID`) → produce with the model and append to
30 // the log. Reconnect (client re-sends with `Last-Event-ID`) → the sink
31 // replays strictly after that offset and the lazy `chat()` stream below
32 // is never iterated.
33 POST: async ({ request }) => {
34 const abortController = new AbortController()
35 const params = await chatParamsFromRequestBody(await request.json())
36​
37 const stream = chat({
38 adapter: openaiText('gpt-5.5'),
39 messages: params.messages,
40 threadId: params.threadId,
41 runId: params.runId,
42 abortController,
43 })
44​
45 return toServerSentEventsResponse(stream, {
46 durability: { adapter: memoryStream(request) },
47 abortController,
48 })
49 },
50​
51 // Replay a run from the start (`?offset=-1&runId=…`) for an explicit
52 // `joinRun` (a second tab or a full reload). Read-only: no messages are
53 // sent and no model is called. This demo relies on automatic POST
54 // reconnect and does not call joinRun, but a durable route should expose
55 // this so an attach-by-id resume is possible.
56 GET: ({ request }) => {
57 return resumeServerSentEventsResponse({
58 adapter: memoryStream(request),
59 })
60 },
61 },
62 },
63})