Open History to see the last commit
1import { useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { useSummarize } from '@tanstack/ai-react'
4import type { UseSummarizeReturn } from '@tanstack/ai-react'
5import { fetchServerSentEvents } from '@tanstack/ai-client'
6import { summarizeFn, summarizeStreamFn } from '../lib/server-fns'
7import type { StreamChunk } from '@tanstack/ai'
8
9// Persist each variant's lightweight resume snapshot across reloads.
10
11const SAMPLE_TEXT = `Artificial intelligence (AI) has rapidly transformed from a niche academic pursuit into one of the most influential technologies of the 21st century. The development of large language models, in particular, has demonstrated capabilities that were previously thought to be decades away. These models can generate human-like text, translate languages, write code, and even engage in complex reasoning tasks.
12
13The implications of this technology are far-reaching. In healthcare, AI systems are being used to analyze medical images, predict patient outcomes, and accelerate drug discovery. In education, personalized learning systems adapt to individual student needs. In creative fields, AI tools are being used to generate art, music, and literature, raising profound questions about authorship and creativity.
14
15However, the rapid advancement of AI also raises significant concerns. Issues of bias in training data, the environmental cost of training large models, the potential for misuse in generating disinformation, and the impact on employment are all active areas of debate. Researchers and policymakers are working to develop frameworks for responsible AI development that balance innovation with safety and ethical considerations.`
16
17const MODELS: Array<{ value: string; label: string }> = [
18 { value: 'gpt-4o-mini', label: 'GPT-4o Mini (fast, cheap)' },
19 { value: 'gpt-4o', label: 'GPT-4o' },
20 { value: 'gpt-5-mini', label: 'GPT-5 Mini' },
21 { value: 'gpt-5', label: 'GPT-5' },
22 { value: 'gpt-5.1', label: 'GPT-5.1' },
23 { value: 'gpt-5.2', label: 'GPT-5.2 (frontier)' },
24]
25
26// Accumulate TEXT_MESSAGE_CONTENT deltas (or the absolute `content`) from a
27// streaming chunk so we can render the summary token-by-token instead of
28// waiting for the terminal `generation:result` event.
29function consumeStreamingChunk(
30 chunk: StreamChunk,
31 prev: string,
32): string | undefined {
33 if (chunk.type !== 'TEXT_MESSAGE_CONTENT') return undefined
34 const c = chunk as StreamChunk & { content?: string; delta?: string }
35 if (typeof c.content === 'string' && c.content.length > 0) return c.content
36 if (typeof c.delta === 'string' && c.delta.length > 0) return prev + c.delta
37 return undefined
38}
39
40function StreamingSummarize() {
41 const [text, setText] = useState('')
42 const [style, setStyle] = useState<'concise' | 'bullet-points' | 'paragraph'>(
43 'concise',
44 )
45 const [model, setModel] = useState<string>(MODELS[0].value)
46 const [streamingText, setStreamingText] = useState('')
47
48 // The connect adapter merges `body` into every request payload; the API
49 // route reads `model` from `body.data` to pick the openaiSummarize variant.
50 const hookReturn = useSummarize({
51 threadId: 'summarize:streaming',
52 connection: fetchServerSentEvents('/api/summarize'),
53 body: { model },
54 persistence: true,
55 onChunk: (chunk) =>
56 setStreamingText((prev) => consumeStreamingChunk(chunk, prev) ?? prev),
57 })
58
59 return (
60 <SummarizeUI
61 {...hookReturn}
62 text={text}
63 setText={setText}
64 style={style}
65 setStyle={setStyle}
66 model={model}
67 setModel={setModel}
68 streamingText={streamingText}
69 onBeforeGenerate={() => setStreamingText('')}
70 />
71 )
72}
73
74function DirectSummarize() {
75 const [text, setText] = useState('')
76 const [style, setStyle] = useState<'concise' | 'bullet-points' | 'paragraph'>(
77 'concise',
78 )
79 const [model, setModel] = useState<string>(MODELS[0].value)
80
81 // Fetcher path: GenerationClient passes `input` straight to the fetcher
82 // (no `body` merge), so we inject `model` into the payload here. Direct
83 // mode is non-streaming — the result appears all at once when the
84 // server-fn resolves.
85 const hookReturn = useSummarize({
86 threadId: 'summarize:direct',
87 fetcher: (input) => summarizeFn({ data: { ...input, model } }),
88 persistence: true,
89 })
90
91 return (
92 <SummarizeUI
93 {...hookReturn}
94 text={text}
95 setText={setText}
96 style={style}
97 setStyle={setStyle}
98 model={model}
99 setModel={setModel}
100 />
101 )
102}
103
104function ServerFnSummarize() {
105 const [text, setText] = useState('')
106 const [style, setStyle] = useState<'concise' | 'bullet-points' | 'paragraph'>(
107 'concise',
108 )
109 const [model, setModel] = useState<string>(MODELS[0].value)
110 const [streamingText, setStreamingText] = useState('')
111
112 // The server-fn returns an SSE Response; GenerationClient parses it and
113 // routes chunks through `onChunk` exactly like the connect-adapter path.
114 const hookReturn = useSummarize({
115 threadId: 'summarize:server-fn',
116 fetcher: (input) => summarizeStreamFn({ data: { ...input, model } }),
117 persistence: true,
118 onChunk: (chunk) =>
119 setStreamingText((prev) => consumeStreamingChunk(chunk, prev) ?? prev),
120 })
121
122 return (
123 <SummarizeUI
124 {...hookReturn}
125 text={text}
126 setText={setText}
127 style={style}
128 setStyle={setStyle}
129 model={model}
130 setModel={setModel}
131 streamingText={streamingText}
132 onBeforeGenerate={() => setStreamingText('')}
133 />
134 )
135}
136
137function SummarizeUI({
138 text,
139 setText,
140 style,
141 setStyle,
142 model,
143 setModel,
144 streamingText,
145 onBeforeGenerate,
146 generate,
147 result,
148 isLoading,
149 error,
150 reset,
151}: UseSummarizeReturn & {
152 text: string
153 setText: (v: string) => void
154 style: 'concise' | 'bullet-points' | 'paragraph'
155 setStyle: (v: 'concise' | 'bullet-points' | 'paragraph') => void
156 model: string
157 setModel: (v: string) => void
158 /** Token-by-token accumulated text from streaming chunks (undefined in
159 * direct/non-streaming mode). */
160 streamingText?: string
161 /** Called just before `generate()` so streaming variants can clear local
162 * accumulator state. */
163 onBeforeGenerate?: () => void
164}) {
165 const handleSummarize = () => {
166 if (!text.trim()) return
167 onBeforeGenerate?.()
168 // Intentionally no `maxLength` — for the OpenAI Responses API,
169 // `maxLength` is mapped to `max_output_tokens`, which on GPT-5.x
170 // reasoning models is the budget for BOTH hidden reasoning AND visible
171 // output. A tight cap (e.g. 200) gets the whole budget consumed by
172 // reasoning, leaving the response truncated with `finishReason: 'length'`
173 // and no visible summary. The selected `style` already drives length.
174 generate({ text: text.trim(), style })
175 }
176
177 // Prefer the live streaming text while generating, fall back to the final
178 // result once the run completes. Direct mode never has streamingText so it
179 // jumps straight to result.
180 const displaySummary = streamingText || result?.summary || ''
181
182 return (
183 <div className="space-y-6">
184 <div className="space-y-3">
185 <div className="flex items-center justify-between">
186 <label className="text-sm text-gray-400">Text to Summarize</label>
187 <button
188 onClick={() => setText(SAMPLE_TEXT)}
189 className="text-xs text-orange-400 hover:text-orange-300 transition-colors"
190 >
191 Use sample text
192 </button>
193 </div>
194 <textarea
195 value={text}
196 onChange={(e) => setText(e.target.value)}
197 placeholder="Paste or type text to summarize..."
198 className="w-full rounded-lg border border-orange-500/20 bg-gray-800/50 px-4 py-3 text-sm text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-orange-500/50 resize-none"
199 rows={8}
200 disabled={isLoading}
201 />
202 </div>
203
204 <div className="space-y-3">
205 <label className="text-sm text-gray-400">Model</label>
206 <select
207 value={model}
208 onChange={(e) => setModel(e.target.value)}
209 disabled={isLoading}
210 className="w-full rounded-lg border border-orange-500/20 bg-gray-800/50 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-orange-500/50 disabled:opacity-50"
211 >
212 {MODELS.map((opt) => (
213 <option key={opt.value} value={opt.value}>
214 {opt.label}
215 </option>
216 ))}
217 </select>
218 </div>
219
220 <div className="space-y-3">
221 <label className="text-sm text-gray-400">Style</label>
222 <div className="flex flex-wrap gap-2">
223 {(['concise', 'bullet-points', 'paragraph'] as const).map((s) => (
224 <button
225 key={s}
226 onClick={() => setStyle(s)}
227 className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
228 style === s
229 ? 'bg-orange-600 text-white'
230 : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
231 }`}
232 >
233 {s}
234 </button>
235 ))}
236 </div>
237 </div>
238
239 <div className="flex gap-3">
240 <button
241 onClick={handleSummarize}
242 disabled={!text.trim() || isLoading}
243 className="px-6 py-2 bg-orange-600 hover:bg-orange-700 disabled:bg-gray-700 disabled:text-gray-500 text-white rounded-lg text-sm font-medium transition-colors"
244 >
245 {isLoading ? 'Summarizing...' : 'Summarize'}
246 </button>
247 {result && (
248 <button
249 onClick={reset}
250 className="px-6 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg text-sm font-medium transition-colors"
251 >
252 Clear
253 </button>
254 )}
255 </div>
256
257 {error && (
258 <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
259 <p className="text-red-400 text-sm">{error.message}</p>
260 </div>
261 )}
262
263 {displaySummary && (
264 <div className="p-4 bg-gray-800/50 border border-gray-700 rounded-lg">
265 <p className="text-sm text-gray-400 mb-3">
266 Summary
267 {isLoading && streamingText && (
268 <span className="ml-2 text-orange-400 animate-pulse">
269 streaming…
270 </span>
271 )}
272 </p>
273 <p className="text-white whitespace-pre-wrap">{displaySummary}</p>
274 </div>
275 )}
276 </div>
277 )
278}
279
280function SummarizePage() {
281 const [mode, setMode] = useState<'streaming' | 'direct' | 'server-fn'>(
282 'streaming',
283 )
284
285 return (
286 <div className="flex flex-col h-[calc(100vh-72px)] bg-gray-900 text-white">
287 <div className="border-b border-orange-500/20 bg-gray-800 px-6 py-4">
288 <div className="flex items-center justify-between">
289 <div>
290 <h2 className="text-xl font-semibold">Text Summarization</h2>
291 <p className="text-sm text-gray-400 mt-1">
292 Summarize text using OpenAI models
293 </p>
294 </div>
295 <div className="flex gap-1 bg-gray-900/50 rounded-lg p-1">
296 <button
297 onClick={() => setMode('streaming')}
298 className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
299 mode === 'streaming'
300 ? 'bg-orange-600 text-white'
301 : 'text-gray-400 hover:text-white'
302 }`}
303 >
304 Streaming
305 </button>
306 <button
307 onClick={() => setMode('direct')}
308 className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
309 mode === 'direct'
310 ? 'bg-orange-600 text-white'
311 : 'text-gray-400 hover:text-white'
312 }`}
313 >
314 Direct
315 </button>
316 <button
317 onClick={() => setMode('server-fn')}
318 className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
319 mode === 'server-fn'
320 ? 'bg-orange-600 text-white'
321 : 'text-gray-400 hover:text-white'
322 }`}
323 >
324 Server Fn
325 </button>
326 </div>
327 </div>
328 </div>
329
330 <div className="flex-1 overflow-y-auto p-6">
331 <div className="max-w-2xl mx-auto">
332 {mode === 'streaming' ? (
333 <StreamingSummarize key="streaming" />
334 ) : mode === 'direct' ? (
335 <DirectSummarize key="direct" />
336 ) : (
337 <ServerFnSummarize key="server-fn" />
338 )}
339 </div>
340 </div>
341 </div>
342 )
343}
344
345export const Route = createFileRoute('/generations/summarize')({
346 component: SummarizePage,
347})