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

api.summarize.ts

87 lines3.6 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 memoryStream,
4 summarize,
5 toServerSentEventsResponse,
6} from '@tanstack/ai'
7import {
8 reconstructGeneration,
9 withGenerationPersistence,
10} from '@tanstack/ai-persistence'
11import { openaiSummarize } from '@tanstack/ai-openai'
12import { replayGenerationIfResuming } from '../lib/generation-durability'
13import { generationServerPersistence } from '../lib/generation-server-store'
14​
15/**
16 * Text summarization with DELIVERY durability, so a mid-run reload rejoins and
17 * tails the stream to completion — the same resumability the media routes get.
18 *
19 * Summarize produces text, not media, so there are no artifacts to store: the
20 * run record alone is enough for `persistence: true` to repaint the last summary
21 * after a reload, and `reconstructGeneration` serves it from the GET below.
22 *
23 * A *mid-run* reload additionally needs the delivery log:
24 * `memoryStream` records the chunks, and the run's `runId` is threaded into
25 * `summarize()` so the emitted `RUN_STARTED` is keyed by the same id the client
26 * rejoins with. Without that alignment the client's `joinRun` GET would tail a
27 * different (empty) log and fast-fail.
28 */
29export const Route = createFileRoute('/api/summarize')({
30 server: {
31 handlers: {
32 POST: async ({ request }) => {
33 const body = await request.json()
34 const { text, maxLength, style, model } = body.forwardedProps
35 // The AG-UI envelope carries the run identity alongside
36 // `forwardedProps`. It also rides the `X-Run-Id` header (which
37 // `memoryStream` keys the log by), so threading `runId` into
38 // `summarize()` keeps RUN_STARTED and the log in sync.
39 const threadId =
40 typeof body.threadId === 'string' ? body.threadId : undefined
41 const runId = typeof body.runId === 'string' ? body.runId : undefined
42​
43 // Persistence needs the scope named. Reject a request without one
44 // rather than filing the run somewhere no client could hydrate by.
45 if (!threadId) {
46 return new Response(
47 '`threadId` is required — it is the scope this summary is filed under.',
48 { status: 400 },
49 )
50 }
51​
52 const stream = summarize({
53 adapter: openaiSummarize(model ?? 'gpt-5.5'),
54 text,
55 maxLength,
56 style,
57 stream: true,
58 ...(runId ? { runId } : {}),
59 threadId,
60 // Writes the run record. Summarize has no media, so no artifact
61 // stores are needed — the record alone is what mount hydration
62 // repaints the last summary from.
63 middleware: [
64 withGenerationPersistence(generationServerPersistence()),
65 ],
66 })
67​
68 // Delivery durability: chunks are logged and id-tagged, so a mount-time
69 // `joinRun` replays/tails instead of failing. The producer is decoupled
70 // from this response by the library, so a reload keeps it draining to
71 // the log until the summary finishes.
72 return toServerSentEventsResponse(stream, {
73 durability: { adapter: memoryStream(request) },
74 })
75 },
76​
77 // Two jobs, resolved in order:
78 // 1. `joinRun` delivery replay, when the request carries a resume offset.
79 // 2. Mount hydration for `persistence: true`: the latest run for
80 // `?threadId=`, so a finished summary restores after a reload even
81 // once its delivery log has aged out.
82 GET: async ({ request }) =>
83 replayGenerationIfResuming(request) ??
84 (await reconstructGeneration(generationServerPersistence(), request)),
85 },
86 },
87})