Open History to see the last commit
1import { useState } from 'react'
2import { ArrowRight, Loader2, TriangleAlert } from 'lucide-react'
3import {
4 MODELS_BY_PROVIDER,
5 PROVIDERS,
6 PROVIDER_ENV_VARS,
7 PROVIDER_LABELS,
8 defaultModelFor,
9 isProvider,
10} from '@/lib/models'
11import { EXAMPLE_QUERIES, SUPPORT_DOCS } from '@/lib/documents'
12import { rerankDocumentsFn } from '@/lib/server-functions'
13import type { SupportDoc } from '@/lib/documents'
14import type { Provider } from '@/lib/models'
15import type { RerankResult } from '@tanstack/ai'
16
17function scoreColor(score: number): string {
18 if (score >= 0.5) return 'bg-emerald-500'
19 if (score >= 0.1) return 'bg-amber-500'
20 return 'bg-gray-600'
21}
22
23function errorMessage(error: unknown): string {
24 return error instanceof Error ? error.message : String(error)
25}
26
27export default function RerankPanel() {
28 const [query, setQuery] = useState(EXAMPLE_QUERIES[0] ?? '')
29 const [provider, setProvider] = useState<Provider>('cohere')
30 const [model, setModel] = useState(() => defaultModelFor('cohere'))
31 const [topN, setTopN] = useState(5)
32 const [isRunning, setIsRunning] = useState(false)
33 const [error, setError] = useState<string | null>(null)
34 const [result, setResult] = useState<RerankResult<SupportDoc> | null>(null)
35
36 function changeProvider(next: Provider) {
37 setProvider(next)
38 setModel(defaultModelFor(next))
39 }
40
41 async function run() {
42 setIsRunning(true)
43 setError(null)
44 try {
45 const data = await rerankDocumentsFn({
46 data: { query, provider, model, topN },
47 })
48 setResult(data)
49 } catch (caught) {
50 setError(errorMessage(caught))
51 setResult(null)
52 } finally {
53 setIsRunning(false)
54 }
55 }
56
57 const usage = result?.usage
58
59 return (
60 <div className="space-y-6">
61 {/* ---------- Controls ---------- */}
62 <div className="bg-gray-800/50 border border-gray-700 rounded-xl p-6 space-y-4">
63 <div className="flex flex-wrap gap-2">
64 {EXAMPLE_QUERIES.map((example) => (
65 <button
66 key={example}
67 type="button"
68 onClick={() => setQuery(example)}
69 className={`text-sm px-3 py-1.5 rounded-full border transition-colors ${
70 query === example
71 ? 'bg-purple-600 border-purple-500 text-white'
72 : 'bg-gray-900 border-gray-700 text-gray-300 hover:bg-gray-700'
73 }`}
74 >
75 {example}
76 </button>
77 ))}
78 </div>
79
80 <form
81 className="flex flex-col gap-4"
82 onSubmit={(event) => {
83 event.preventDefault()
84 void run()
85 }}
86 >
87 <label className="block">
88 <span className="text-sm font-medium text-gray-300">Query</span>
89 <input
90 value={query}
91 onChange={(event) => setQuery(event.target.value)}
92 placeholder="What is the user actually asking for?"
93 className="mt-1 w-full rounded-lg bg-gray-900 border border-gray-700 px-3 py-2 text-white placeholder-gray-500 focus:border-purple-500 focus:outline-none"
94 />
95 </label>
96
97 <div className="flex flex-wrap gap-4">
98 <label className="block">
99 <span className="text-sm font-medium text-gray-300">
100 Provider
101 </span>
102 <select
103 value={provider}
104 onChange={(event) => {
105 const next = event.target.value
106 if (isProvider(next)) changeProvider(next)
107 }}
108 className="mt-1 block rounded-lg bg-gray-900 border border-gray-700 px-3 py-2 text-white focus:border-purple-500 focus:outline-none"
109 >
110 {PROVIDERS.map((entry) => (
111 <option key={entry} value={entry}>
112 {PROVIDER_LABELS[entry]}
113 </option>
114 ))}
115 </select>
116 </label>
117
118 <label className="block grow">
119 <span className="text-sm font-medium text-gray-300">Model</span>
120 <select
121 value={model}
122 onChange={(event) => setModel(event.target.value)}
123 className="mt-1 block w-full rounded-lg bg-gray-900 border border-gray-700 px-3 py-2 text-white focus:border-purple-500 focus:outline-none"
124 >
125 {MODELS_BY_PROVIDER[provider].map((entry) => (
126 <option key={entry} value={entry}>
127 {entry}
128 </option>
129 ))}
130 </select>
131 </label>
132
133 <label className="block">
134 <span className="text-sm font-medium text-gray-300">top N</span>
135 <input
136 type="number"
137 min={1}
138 max={SUPPORT_DOCS.length}
139 value={topN}
140 onChange={(event) =>
141 setTopN(Number.parseInt(event.target.value, 10) || 1)
142 }
143 className="mt-1 block w-24 rounded-lg bg-gray-900 border border-gray-700 px-3 py-2 text-white focus:border-purple-500 focus:outline-none"
144 />
145 </label>
146 </div>
147
148 <button
149 type="submit"
150 disabled={isRunning || query.trim().length === 0}
151 className="inline-flex items-center justify-center gap-2 self-start rounded-lg bg-purple-600 px-5 py-2.5 font-medium text-white transition-colors hover:bg-purple-500 disabled:cursor-not-allowed disabled:bg-gray-700 disabled:text-gray-400"
152 >
153 {isRunning ? (
154 <Loader2 className="w-4 h-4 animate-spin" />
155 ) : (
156 <ArrowRight className="w-4 h-4" />
157 )}
158 {isRunning ? 'Reranking…' : 'Rerank'}
159 </button>
160 </form>
161 </div>
162
163 {/* ---------- Error ---------- */}
164 {error !== null && (
165 <div className="flex gap-3 rounded-xl border border-red-800 bg-red-950/50 p-4 text-red-200">
166 <TriangleAlert className="w-5 h-5 shrink-0 mt-0.5" />
167 <div>
168 <p className="font-medium">Rerank failed</p>
169 <p className="text-sm text-red-300/90 mt-1">{error}</p>
170 <p className="text-sm text-red-300/70 mt-2">
171 Set{' '}
172 <code className="font-mono">{PROVIDER_ENV_VARS[provider]}</code>{' '}
173 in <code className="font-mono">.env</code> and restart the dev
174 server.
175 </p>
176 </div>
177 </div>
178 )}
179
180 {/* ---------- Results ---------- */}
181 <div className="grid gap-6 md:grid-cols-2">
182 <section>
183 <h2 className="text-sm font-semibold uppercase tracking-wide text-gray-400 mb-3">
184 Original order
185 </h2>
186 <ol className="space-y-2">
187 {SUPPORT_DOCS.map((doc, index) => (
188 <li
189 key={doc.id}
190 className="flex gap-3 rounded-lg border border-gray-800 bg-gray-900/60 p-3"
191 >
192 <span className="font-mono text-xs text-gray-500 pt-0.5">
193 {index + 1}
194 </span>
195 <span className="text-sm text-gray-300">{doc.title}</span>
196 </li>
197 ))}
198 </ol>
199 </section>
200
201 <section>
202 <h2 className="text-sm font-semibold uppercase tracking-wide text-gray-400 mb-3">
203 Reranked{result ? ` — top ${result.ranking.length}` : ''}
204 </h2>
205
206 {result === null ? (
207 <p className="rounded-lg border border-dashed border-gray-700 p-6 text-sm text-gray-500">
208 Run a query to see the model reorder these documents by relevance.
209 </p>
210 ) : (
211 <>
212 <ol className="space-y-2">
213 {result.ranking.map((entry, position) => (
214 <li
215 key={entry.document.id}
216 className="rounded-lg border border-gray-700 bg-gray-800/60 p-3"
217 >
218 <div className="flex items-baseline gap-3">
219 <span className="font-mono text-xs text-purple-400 pt-0.5">
220 {position + 1}
221 </span>
222 {/* `entry.document` is the original SupportDoc object,
223 typed — no id lookup needed. */}
224 <span className="text-sm text-white grow">
225 {entry.document.title}
226 </span>
227 <span
228 className="font-mono text-xs text-gray-400 shrink-0"
229 title="relevance score"
230 >
231 {entry.score.toFixed(3)}
232 </span>
233 </div>
234 <div className="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-gray-700">
235 <div
236 className={`h-full rounded-full ${scoreColor(entry.score)}`}
237 style={{
238 width: `${Math.max(entry.score * 100, 1)}%`,
239 }}
240 />
241 </div>
242 <p className="mt-2 text-xs text-gray-500">
243 was #{entry.index + 1} in the original order
244 </p>
245 </li>
246 ))}
247 </ol>
248
249 <dl className="mt-4 rounded-lg border border-gray-800 bg-gray-900/60 p-3 text-xs text-gray-400 space-y-1">
250 <div className="flex justify-between gap-4">
251 <dt>model</dt>
252 <dd className="font-mono text-gray-300">{result.model}</dd>
253 </div>
254 {usage?.billed && (
255 <div className="flex justify-between gap-4">
256 <dt>billed</dt>
257 <dd className="font-mono text-gray-300">
258 {usage.billed.quantity}{' '}
259 {usage.billed.unit === 'units'
260 ? `search unit${usage.billed.quantity === 1 ? '' : 's'}`
261 : usage.billed.unit}
262 </dd>
263 </div>
264 )}
265 {usage !== undefined && usage.totalTokens > 0 && (
266 <div className="flex justify-between gap-4">
267 <dt>total tokens</dt>
268 <dd className="font-mono text-gray-300">
269 {usage.totalTokens}
270 </dd>
271 </div>
272 )}
273 {usage?.cost !== undefined && (
274 <div className="flex justify-between gap-4">
275 <dt>cost</dt>
276 <dd className="font-mono text-gray-300">
277 ${usage.cost.toFixed(6)}
278 </dd>
279 </div>
280 )}
281 </dl>
282 </>
283 )}
284 </section>
285 </div>
286 </div>
287 )
288}