Open History to see the last commit
1import { useState } from 'react'
2import { createFileRoute } from '@tanstack/react-router'
3import { FileText, Loader2, Zap } from 'lucide-react'
4
5type Provider =
6 | 'openai'
7 | 'anthropic'
8 | 'gemini'
9 | 'ollama'
10 | 'grok'
11 | 'openrouter'
12
13interface SummarizeProvider {
14 id: Provider
15 name: string
16}
17
18const PROVIDERS: Array<SummarizeProvider> = [
19 { id: 'openai', name: 'OpenAI (GPT-4o Mini)' },
20 { id: 'anthropic', name: 'Anthropic (Claude Sonnet)' },
21 { id: 'gemini', name: 'Gemini (2.5 Flash)' },
22 { id: 'grok', name: 'Grok (Grok 3 Mini)' },
23 { id: 'ollama', name: 'Ollama (Mistral 7B)' },
24 { id: 'openrouter', name: 'OpenRouter (GPT-4o Mini)' },
25]
26
27const SAMPLE_TEXT = `Artificial intelligence (AI) is intelligence demonstrated by machines, as opposed to natural intelligence displayed by animals including humans. AI research has been defined as the field of study of intelligent agents, which refers to any system that perceives its environment and takes actions that maximize its chance of achieving its goals.
28
29The term "artificial intelligence" had previously been used to describe machines that mimic and display "human" cognitive skills that are associated with the human mind, such as "learning" and "problem-solving". This definition has since been rejected by major AI researchers who now describe AI in terms of rationality and acting rationally, which does not limit how intelligence can be articulated.
30
31AI applications include advanced web search engines, recommendation systems, understanding human speech, self-driving cars, automated decision-making and competing at the highest level in strategic game systems. As machines become increasingly capable, tasks considered to require "intelligence" are often removed from the definition of AI, a phenomenon known as the AI effect.`
32
33function SummarizePage() {
34 const [text, setText] = useState(SAMPLE_TEXT)
35 const [provider, setProvider] = useState<Provider>('openai')
36 const [maxLength, setMaxLength] = useState(100)
37 const [style, setStyle] = useState<'concise' | 'detailed' | 'bullet-points'>(
38 'concise',
39 )
40 const [useStreaming, setUseStreaming] = useState(false)
41 const [summary, setSummary] = useState<string | null>(null)
42 const [isLoading, setIsLoading] = useState(false)
43 const [error, setError] = useState<string | null>(null)
44 const [usedProvider, setUsedProvider] = useState<string | null>(null)
45 const [usedModel, setUsedModel] = useState<string | null>(null)
46 const [chunkCount, setChunkCount] = useState<number>(0)
47
48 const handleSummarize = async () => {
49 setIsLoading(true)
50 setError(null)
51 setSummary(null)
52 setChunkCount(0)
53
54 try {
55 const response = await fetch('/api/summarize', {
56 method: 'POST',
57 headers: { 'Content-Type': 'application/json' },
58 body: JSON.stringify({
59 text,
60 provider,
61 maxLength,
62 style,
63 stream: useStreaming,
64 }),
65 })
66
67 if (useStreaming) {
68 // Handle streaming response
69 const reader = response.body?.getReader()
70 const decoder = new TextDecoder()
71 let chunks = 0
72 let accumulatedSummary = ''
73
74 if (!reader) {
75 throw new Error('No response body')
76 }
77
78 while (true) {
79 const { done, value } = await reader.read()
80 if (done) break
81
82 const text = decoder.decode(value)
83 const lines = text.split('\n')
84
85 for (const line of lines) {
86 if (line.startsWith('data: ')) {
87 const data = line.slice(6)
88 if (data === '[DONE]') continue
89
90 try {
91 const parsed = JSON.parse(data)
92 if (parsed.type === 'error') {
93 throw new Error(parsed.error)
94 }
95 // Handle TEXT_MESSAGE_CONTENT chunks from the summarize stream
96 if (parsed.type === 'TEXT_MESSAGE_CONTENT') {
97 chunks++
98 setChunkCount(chunks)
99 // Accumulate delta or use content if provided
100 if (parsed.delta) {
101 accumulatedSummary += parsed.delta
102 } else if (parsed.content) {
103 accumulatedSummary = parsed.content
104 }
105 setSummary(accumulatedSummary)
106 setUsedProvider(parsed.provider)
107 setUsedModel(parsed.model)
108 }
109 } catch (e) {
110 // Ignore parse errors for incomplete chunks
111 }
112 }
113 }
114 }
115 } else {
116 // Handle non-streaming response
117 const data = await response.json()
118
119 if (!response.ok) {
120 throw new Error(data.error || 'Failed to summarize')
121 }
122
123 setSummary(data.summary)
124 setUsedProvider(data.provider)
125 setUsedModel(data.model)
126 }
127 } catch (err: any) {
128 setError(err.message)
129 } finally {
130 setIsLoading(false)
131 }
132 }
133
134 return (
135 <div className="min-h-[calc(100vh-72px)] bg-gray-900 p-6">
136 <div className="max-w-4xl mx-auto">
137 <div className="flex items-center gap-3 mb-6">
138 <FileText className="w-8 h-8 text-orange-500" />
139 <h1 className="text-2xl font-bold text-white">Text Summarization</h1>
140 </div>
141
142 <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
143 {/* Input Panel */}
144 <div className="space-y-4">
145 <div>
146 <label className="block text-sm font-medium text-gray-300 mb-2">
147 Provider
148 </label>
149 <select
150 value={provider}
151 onChange={(e) => setProvider(e.target.value as Provider)}
152 disabled={isLoading}
153 className="w-full rounded-lg border border-orange-500/20 bg-gray-800 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-orange-500/50"
154 >
155 {PROVIDERS.map((p) => (
156 <option key={p.id} value={p.id}>
157 {p.name}
158 </option>
159 ))}
160 </select>
161 </div>
162
163 <div className="grid grid-cols-2 gap-4">
164 <div>
165 <label className="block text-sm font-medium text-gray-300 mb-2">
166 Max Length (words)
167 </label>
168 <input
169 type="number"
170 value={maxLength}
171 onChange={(e) =>
172 setMaxLength(parseInt(e.target.value) || 100)
173 }
174 min={20}
175 max={500}
176 disabled={isLoading}
177 className="w-full rounded-lg border border-orange-500/20 bg-gray-800 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-orange-500/50"
178 />
179 </div>
180 <div>
181 <label className="block text-sm font-medium text-gray-300 mb-2">
182 Style
183 </label>
184 <select
185 value={style}
186 onChange={(e) => setStyle(e.target.value as any)}
187 disabled={isLoading}
188 className="w-full rounded-lg border border-orange-500/20 bg-gray-800 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-orange-500/50"
189 >
190 <option value="concise">Concise</option>
191 <option value="detailed">Detailed</option>
192 <option value="bullet-points">Bullet Points</option>
193 </select>
194 </div>
195 </div>
196
197 <div className="flex items-center gap-3">
198 <label className="relative inline-flex items-center cursor-pointer">
199 <input
200 type="checkbox"
201 checked={useStreaming}
202 onChange={(e) => setUseStreaming(e.target.checked)}
203 disabled={isLoading}
204 className="sr-only peer"
205 />
206 <div className="w-11 h-6 bg-gray-700 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-orange-500/50 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-orange-600"></div>
207 </label>
208 <span className="flex items-center gap-2 text-sm text-gray-300">
209 <Zap className="w-4 h-4 text-orange-500" />
210 Enable Streaming
211 </span>
212 </div>
213
214 <div>
215 <label className="block text-sm font-medium text-gray-300 mb-2">
216 Text to Summarize
217 </label>
218 <textarea
219 value={text}
220 onChange={(e) => setText(e.target.value)}
221 disabled={isLoading}
222 rows={12}
223 className="w-full rounded-lg border border-orange-500/20 bg-gray-800 px-3 py-2 text-sm text-white focus:outline-none focus:ring-2 focus:ring-orange-500/50 resize-none"
224 placeholder="Enter text to summarize..."
225 />
226 </div>
227
228 <button
229 onClick={handleSummarize}
230 disabled={isLoading || !text.trim()}
231 className="w-full px-4 py-3 bg-orange-600 hover:bg-orange-700 disabled:bg-gray-600 text-white rounded-lg font-medium transition-colors flex items-center justify-center gap-2"
232 >
233 {isLoading ? (
234 <>
235 <Loader2 className="w-5 h-5 animate-spin" />
236 {useStreaming ? 'Streaming...' : 'Summarizing...'}
237 </>
238 ) : (
239 <>
240 {useStreaming && <Zap className="w-4 h-4" />}
241 {useStreaming ? 'Stream Summary' : 'Summarize'}
242 </>
243 )}
244 </button>
245 </div>
246
247 {/* Output Panel */}
248 <div className="bg-gray-800 rounded-lg p-6 border border-orange-500/20">
249 <h2 className="text-lg font-semibold text-white mb-4">Summary</h2>
250
251 {error && (
252 <div className="p-4 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400 mb-4">
253 {error}
254 </div>
255 )}
256
257 {summary ? (
258 <div className="space-y-4">
259 <div className="text-gray-300 whitespace-pre-wrap">
260 {summary}
261 </div>
262 <div className="pt-4 border-t border-gray-700 text-sm text-gray-400">
263 <p>
264 Provider:{' '}
265 <span className="text-orange-400">{usedProvider}</span>
266 </p>
267 <p>
268 Model: <span className="text-orange-400">{usedModel}</span>
269 </p>
270 {chunkCount > 0 && (
271 <p>
272 Streaming:{' '}
273 <span className="text-orange-400">
274 {chunkCount} chunks
275 </span>
276 </p>
277 )}
278 </div>
279 </div>
280 ) : !error && !isLoading ? (
281 <p className="text-gray-500">
282 Enter some text and click "Summarize" to generate a summary.
283 </p>
284 ) : null}
285 </div>
286 </div>
287 </div>
288 </div>
289 )
290}
291
292export const Route = createFileRoute('/summarize')({
293 component: SummarizePage,
294})