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

generations.summarize.tsx

350 lines12.6 KB

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)' },
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
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.forwardedProps` to pick the openaiSummarize
50 // variant.
51 const hookReturn = useSummarize({
52 threadId: 'summarize:streaming',
53 connection: fetchServerSentEvents('/api/summarize'),
54 body: { model },
55 persistence: true,
56 onChunk: (chunk) =>
57 setStreamingText((prev) => consumeStreamingChunk(chunk, prev) ?? prev),
58 })
59​
60 return (
61 <SummarizeUI
62 {...hookReturn}
63 text={text}
64 setText={setText}
65 style={style}
66 setStyle={setStyle}
67 model={model}
68 setModel={setModel}
69 streamingText={streamingText}
70 onBeforeGenerate={() => setStreamingText('')}
71 />
72 )
74​
75function DirectSummarize() {
76 const [text, setText] = useState('')
77 const [style, setStyle] = useState<'concise' | 'bullet-points' | 'paragraph'>(
78 'concise',
79 )
80 const [model, setModel] = useState<string>(MODELS[0].value)
81​
82 // Fetcher path: GenerationClient passes `input` straight to the fetcher
83 // (no `body` merge), so we inject `model` into the payload here. Direct
84 // mode is non-streaming — the result appears all at once when the
85 // server-fn resolves.
86 const hookReturn = useSummarize({
87 threadId: 'summarize:direct',
88 fetcher: (input, { threadId }) =>
89 summarizeFn({ data: { ...input, model, threadId } }),
90 persistence: true,
91 })
92​
93 return (
94 <SummarizeUI
95 {...hookReturn}
96 text={text}
97 setText={setText}
98 style={style}
99 setStyle={setStyle}
100 model={model}
101 setModel={setModel}
102 />
103 )
105​
106function ServerFnSummarize() {
107 const [text, setText] = useState('')
108 const [style, setStyle] = useState<'concise' | 'bullet-points' | 'paragraph'>(
109 'concise',
110 )
111 const [model, setModel] = useState<string>(MODELS[0].value)
112 const [streamingText, setStreamingText] = useState('')
113​
114 // The server-fn returns an SSE Response; GenerationClient parses it and
115 // routes chunks through `onChunk` exactly like the connect-adapter path.
116 const hookReturn = useSummarize({
117 threadId: 'summarize:server-fn',
118 fetcher: (input, { threadId }) =>
119 summarizeStreamFn({ data: { ...input, model, threadId } }),
120 persistence: true,
121 onChunk: (chunk) =>
122 setStreamingText((prev) => consumeStreamingChunk(chunk, prev) ?? prev),
123 })
124​
125 return (
126 <SummarizeUI
127 {...hookReturn}
128 text={text}
129 setText={setText}
130 style={style}
131 setStyle={setStyle}
132 model={model}
133 setModel={setModel}
134 streamingText={streamingText}
135 onBeforeGenerate={() => setStreamingText('')}
136 />
137 )
139​
140function SummarizeUI({
141 text,
142 setText,
143 style,
144 setStyle,
145 model,
146 setModel,
147 streamingText,
148 onBeforeGenerate,
149 generate,
150 result,
151 isLoading,
152 error,
153 reset,
154}: UseSummarizeReturn & {
155 text: string
156 setText: (v: string) => void
157 style: 'concise' | 'bullet-points' | 'paragraph'
158 setStyle: (v: 'concise' | 'bullet-points' | 'paragraph') => void
159 model: string
160 setModel: (v: string) => void
161 /** Token-by-token accumulated text from streaming chunks (undefined in
162 * direct/non-streaming mode). */
163 streamingText?: string
164 /** Called just before `generate()` so streaming variants can clear local
165 * accumulator state. */
166 onBeforeGenerate?: () => void
167}) {
168 const handleSummarize = () => {
169 if (!text.trim()) return
170 onBeforeGenerate?.()
171 // Intentionally no `maxLength` — for the OpenAI Responses API,
172 // `maxLength` is mapped to `max_output_tokens`, which on GPT-5.x
173 // reasoning models is the budget for BOTH hidden reasoning AND visible
174 // output. A tight cap (e.g. 200) gets the whole budget consumed by
175 // reasoning, leaving the response truncated with `finishReason: 'length'`
176 // and no visible summary. The selected `style` already drives length.
177 generate({ text: text.trim(), style })
178 }
179​
180 // Prefer the live streaming text while generating, fall back to the final
181 // result once the run completes. Direct mode never has streamingText so it
182 // jumps straight to result.
183 const displaySummary = streamingText || result?.summary || ''
184​
185 return (
186 <div className="space-y-6">
187 <div className="space-y-3">
188 <div className="flex items-center justify-between">
189 <label className="text-sm text-gray-400">Text to Summarize</label>
190 <button
191 onClick={() => setText(SAMPLE_TEXT)}
192 className="text-xs text-orange-400 hover:text-orange-300 transition-colors"
193 >
194 Use sample text
195 </button>
196 </div>
197 <textarea
198 value={text}
199 onChange={(e) => setText(e.target.value)}
200 placeholder="Paste or type text to summarize..."
201 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"
202 rows={8}
203 disabled={isLoading}
204 />
205 </div>
206​
207 <div className="space-y-3">
208 <label className="text-sm text-gray-400">Model</label>
209 <select
210 value={model}
211 onChange={(e) => setModel(e.target.value)}
212 disabled={isLoading}
213 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"
214 >
215 {MODELS.map((opt) => (
216 <option key={opt.value} value={opt.value}>
217 {opt.label}
218 </option>
219 ))}
220 </select>
221 </div>
222​
223 <div className="space-y-3">
224 <label className="text-sm text-gray-400">Style</label>
225 <div className="flex flex-wrap gap-2">
226 {(['concise', 'bullet-points', 'paragraph'] as const).map((s) => (
227 <button
228 key={s}
229 onClick={() => setStyle(s)}
230 className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
231 style === s
232 ? 'bg-orange-600 text-white'
233 : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
234 }`}
235 >
236 {s}
237 </button>
238 ))}
239 </div>
240 </div>
241​
242 <div className="flex gap-3">
243 <button
244 onClick={handleSummarize}
245 disabled={!text.trim() || isLoading}
246 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"
247 >
248 {isLoading ? 'Summarizing...' : 'Summarize'}
249 </button>
250 {result && (
251 <button
252 onClick={reset}
253 className="px-6 py-2 bg-gray-700 hover:bg-gray-600 text-white rounded-lg text-sm font-medium transition-colors"
254 >
255 Clear
256 </button>
257 )}
258 </div>
259​
260 {error && (
261 <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
262 <p className="text-red-400 text-sm">{error.message}</p>
263 </div>
264 )}
265​
266 {displaySummary && (
267 <div className="p-4 bg-gray-800/50 border border-gray-700 rounded-lg">
268 <p className="text-sm text-gray-400 mb-3">
269 Summary
270 {isLoading && streamingText && (
271 <span className="ml-2 text-orange-400 animate-pulse">
272 streaming…
273 </span>
274 )}
275 </p>
276 <p className="text-white whitespace-pre-wrap">{displaySummary}</p>
277 </div>
278 )}
279 </div>
280 )
282​
283function SummarizePage() {
284 const [mode, setMode] = useState<'streaming' | 'direct' | 'server-fn'>(
285 'streaming',
286 )
287​
288 return (
289 <div className="flex flex-col h-[calc(100vh-72px)] bg-gray-900 text-white">
290 <div className="border-b border-orange-500/20 bg-gray-800 px-6 py-4">
291 <div className="flex items-center justify-between">
292 <div>
293 <h2 className="text-xl font-semibold">Text Summarization</h2>
294 <p className="text-sm text-gray-400 mt-1">
295 Summarize text using OpenAI models
296 </p>
297 </div>
298 <div className="flex gap-1 bg-gray-900/50 rounded-lg p-1">
299 <button
300 onClick={() => setMode('streaming')}
301 className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
302 mode === 'streaming'
303 ? 'bg-orange-600 text-white'
304 : 'text-gray-400 hover:text-white'
305 }`}
306 >
307 Streaming
308 </button>
309 <button
310 onClick={() => setMode('direct')}
311 className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
312 mode === 'direct'
313 ? 'bg-orange-600 text-white'
314 : 'text-gray-400 hover:text-white'
315 }`}
316 >
317 Direct
318 </button>
319 <button
320 onClick={() => setMode('server-fn')}
321 className={`px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${
322 mode === 'server-fn'
323 ? 'bg-orange-600 text-white'
324 : 'text-gray-400 hover:text-white'
325 }`}
326 >
327 Server Fn
328 </button>
329 </div>
330 </div>
331 </div>
332​
333 <div className="flex-1 overflow-y-auto p-6">
334 <div className="max-w-2xl mx-auto">
335 {mode === 'streaming' ? (
336 <StreamingSummarize key="streaming" />
337 ) : mode === 'direct' ? (
338 <DirectSummarize key="direct" />
339 ) : (
340 <ServerFnSummarize key="server-fn" />
341 )}
342 </div>
343 </div>
344 </div>
345 )
347​
348export const Route = createFileRoute('/generations/summarize')({
349 component: SummarizePage,
350})