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

rerank.md

393 lines11.5 KB

1---
2title: Reranking
3id: rerank
4order: 1
5description: "Reorder candidate documents by relevance to a query with TanStack AI's rerank() API and the Cohere adapter — the precision step for RAG and search."
6keywords:
7 - tanstack ai
8 - rerank
9 - reranking
10 - relevance
11 - rag
12 - retrieval
13 - semantic search
14 - cohere
15---
16​
17You have a query and a list of candidate documents — chunks from a vector
18search, rows from a keyword query, FAQ entries — and you need them ordered by
19how well they actually answer the query. Vector similarity gets you close, but
20a dedicated reranking model is far more precise. By the end of this guide
21you'll have that list reordered, with a relevance score per document.
22​
23`rerank()` is the precision step in a retrieval pipeline: retrieve a broad set
24of candidates cheaply, then rerank to surface the few that matter.
25​
26## Providers
27​
28Reranking is available from two adapters today:
29​
30- **Cohere** (`@tanstack/ai-cohere`) — `cohereRerank('rerank-v3.5')`, talking to Cohere directly.
31- **OpenRouter** (`@tanstack/ai-openrouter`) — `openRouterRerank('cohere/rerank-v3.5')`, routing rerank through your existing OpenRouter key.
32​
33Both implement the same `rerank()` activity — swap the adapter, keep the call.
34​
35## Installation
36​
37Cohere:
38​
39<!-- ::start:tabs variant="package-manager" mode="install" -->
40​
41react: @tanstack/ai-cohere
42vue: @tanstack/ai-cohere
43solid: @tanstack/ai-cohere
44svelte: @tanstack/ai-cohere
45preact: @tanstack/ai-cohere
46angular: @tanstack/ai-cohere
47vanilla: @tanstack/ai-cohere
48octane: @tanstack/ai-cohere
49​
50<!-- ::end:tabs -->
51​
52OpenRouter:
53​
54<!-- ::start:tabs variant="package-manager" mode="install" -->
55​
56react: @tanstack/ai-openrouter
57vue: @tanstack/ai-openrouter
58solid: @tanstack/ai-openrouter
59svelte: @tanstack/ai-openrouter
60preact: @tanstack/ai-openrouter
61angular: @tanstack/ai-openrouter
62vanilla: @tanstack/ai-openrouter
63octane: @tanstack/ai-openrouter
64​
65<!-- ::end:tabs -->
66​
67Peer dependency:
68​
69<!-- ::start:tabs variant="package-manager" mode="install" -->
70​
71react: @tanstack/ai
72vue: @tanstack/ai
73solid: @tanstack/ai
74svelte: @tanstack/ai
75preact: @tanstack/ai
76angular: @tanstack/ai
77vanilla: @tanstack/ai
78octane: @tanstack/ai
79​
80<!-- ::end:tabs -->
81​
82## Basic Usage
83​
84Pass a `query` and an array of `documents`. The result's `rerankedDocuments`
85are ordered most-relevant first, and `ranking` carries the relevance score and
86the original index of each.
87​
88```typescript
89import { rerank } from '@tanstack/ai'
90import { cohereRerank } from '@tanstack/ai-cohere'
91​
92const { ranking, rerankedDocuments } = await rerank({
93 adapter: cohereRerank('rerank-v3.5'),
94 query: 'talk about rain',
95 documents: ['sunny day at the beach', 'rainy afternoon in the city'],
96 topN: 2,
97})
98​
99console.log(rerankedDocuments[0]) // 'rainy afternoon in the city'
100console.log(ranking[0]) // { index: 1, score: 0.98, document: 'rainy afternoon in the city' }
101```
102​
103The adapter reads `COHERE_API_KEY` from the environment. To pass a key
104explicitly, use `createCohereRerank('rerank-v3.5', 'co-...')`.
105​
106To rerank through OpenRouter instead, swap the adapter — everything else stays
107the same:
108​
109```typescript
110import { rerank } from '@tanstack/ai'
111import { openRouterRerank } from '@tanstack/ai-openrouter'
112​
113const { rerankedDocuments } = await rerank({
114 adapter: openRouterRerank('cohere/rerank-v3.5'),
115 query: 'talk about rain',
116 documents: ['sunny day at the beach', 'rainy afternoon in the city'],
117 topN: 2,
118})
119​
120console.log(rerankedDocuments[0]) // 'rainy afternoon in the city'
121```
122​
123`openRouterRerank` reads `OPENROUTER_API_KEY` from the environment.
124​
125## Reranking Object Documents
126​
127Documents don't have to be strings. Pass JSON-serializable objects and the
128original object is returned in the result — fully typed — so you can carry an
129id or metadata through the rerank and read it back off the ranked results.
130​
131```typescript
132import { rerank } from '@tanstack/ai'
133import { cohereRerank } from '@tanstack/ai-cohere'
134​
135const chunks = [
136 { id: 'doc-1', text: 'A heavy gaming desktop with an RTX card.' },
137 { id: 'doc-2', text: 'A lightweight ultrabook with all-day battery.' },
139​
140const { ranking } = await rerank({
141 adapter: cohereRerank('rerank-v3.5'),
142 query: 'best laptop for travel',
143 documents: chunks,
144})
145​
146// `document` is the original object — `id` is available and type-safe.
147console.log(ranking[0]?.document.id) // 'doc-2'
148```
149​
150Object documents are serialized to JSON before being sent to the provider; the
151ranking is mapped back to your original elements by index.
152​
153## Options
154​
155| Option | Type | Description |
156| ------------- | ----------------------------- | ------------------------------------------------------------------------ |
157| `adapter` | `RerankAdapter` | A rerank adapter created with a model (e.g. `cohereRerank('rerank-v3.5')`) |
158| `query` | `string` | The search query documents are scored against — required |
159| `documents` | `Array<string \| object>` | Candidate documents to rerank — required |
160| `topN` | `number` | Return only the top N results |
161| `abortSignal` | `AbortSignal` | Cancel the in-flight request |
162| `modelOptions`| provider options | Provider-specific options (see below) |
163| `middleware` | `Array<GenerationMiddleware>` | Observe-only lifecycle hooks (usage, finish, error, abort) |
164​
165### Provider Options
166​
167Cohere rerank accepts:
168​
169```typescript
170import { rerank } from '@tanstack/ai'
171import { cohereRerank } from '@tanstack/ai-cohere'
172​
173const { ranking } = await rerank({
174 adapter: cohereRerank('rerank-v3.5'),
175 query: 'refund policy',
176 documents: ['Returns accepted within 30 days.', 'Free shipping over $50.'],
177 modelOptions: {
178 // Cap tokens kept per document when chunking long inputs (Cohere default: 4096).
179 maxTokensPerDoc: 512,
180 },
181})
182​
183console.log(ranking)
184```
185​
186## Result Shape
187​
188```typescript
189import type { TokenUsage } from '@tanstack/ai'
190​
191interface RerankResult<TDocument = string> {
192 id: string
193 model: string
194 // Scored results, most relevant first.
195 ranking: Array<{ index: number; score: number; document: TDocument }>
196 // The documents reordered by relevance (ranking.map(r => r.document)).
197 rerankedDocuments: Array<TDocument>
198 // Rerank typically bills in provider "search units"
199 // (usage.billed = { quantity, unit: 'units' }). Some providers (for example
200 // OpenRouter) also report totalTokens and cost. Cohere reports only search
201 // units and leaves token counts at 0.
202 usage: TokenUsage
204```
205​
206## Server Endpoint
207​
208Reranking runs on the server (it needs your API key). Wrap it in an API route
209and call it from the client over `fetch`:
210​
211```typescript ignore
212// routes/api/rerank.ts
213import { rerank } from '@tanstack/ai'
214import { cohereRerank } from '@tanstack/ai-cohere'
215import { createFileRoute } from '@tanstack/react-router'
216​
217export const Route = createFileRoute('/api/rerank')({
218 server: {
219 handlers: {
220 POST: async ({ request }) => {
221 const body: unknown = await request.json()
222 if (
223 typeof body !== 'object' ||
224 body === null ||
225 !('query' in body) ||
226 typeof body.query !== 'string' ||
227 !('documents' in body) ||
228 !Array.isArray(body.documents)
229 ) {
230 return new Response('Invalid request body', { status: 400 })
231 }
232 const { query, documents } = body
233 const topN = 'topN' in body && typeof body.topN === 'number'
234 ? body.topN
235 : undefined
236​
237 const result = await rerank({
238 adapter: cohereRerank('rerank-v3.5'),
239 query,
240 documents,
241 topN,
242 })
243​
244 return Response.json(result)
245 },
246 },
247 },
248})
249```
250​
251```typescript ignore
252// client.ts — call the endpoint and use the reordered documents
253async function rerankDocuments(query: string, documents: Array<string>) {
254 const res = await fetch('/api/rerank', {
255 method: 'POST',
256 headers: { 'Content-Type': 'application/json' },
257 body: JSON.stringify({ query, documents, topN: 3 }),
258 })
259 const result = await res.json()
260 return result.rerankedDocuments
262```
263​
264## In a RAG Pipeline
265​
266Reranking shines as the second stage after a cheap, broad retrieval. Over-fetch
267candidates with vector search, then rerank to keep only the most relevant few
268for the prompt:
269​
270```typescript ignore
271import { rerank } from '@tanstack/ai'
272import { cohereRerank } from '@tanstack/ai-cohere'
273import { vectorSearch } from './my-vector-store'
274​
275async function retrieveContext(query: string) {
276 // 1. Over-fetch candidates cheaply.
277 const candidates = await vectorSearch(query, { limit: 50 })
278​
279 // 2. Rerank and keep the most relevant handful for the prompt.
280 const { rerankedDocuments } = await rerank({
281 adapter: cohereRerank('rerank-v3.5'),
282 query,
283 documents: candidates.map((c) => c.text),
284 topN: 5,
285 })
286​
287 return rerankedDocuments
289```
290​
291## Cancellation
292​
293Pass an `abortSignal` to cancel an in-flight request:
294​
295```typescript
296import { rerank } from '@tanstack/ai'
297import { cohereRerank } from '@tanstack/ai-cohere'
298​
299const controller = new AbortController()
300setTimeout(() => controller.abort(), 5000)
301​
302const result = await rerank({
303 adapter: cohereRerank('rerank-v3.5'),
304 query: 'q',
305 documents: ['a', 'b'],
306 abortSignal: controller.signal,
307})
308​
309console.log(result.rerankedDocuments)
310```
311​
312## Observability
313​
314Attach observe-only middleware to track usage, completion, errors, and
315cancellation — the same `GenerationMiddleware` contract the media activities
316use:
317​
318```typescript
319import { rerank } from '@tanstack/ai'
320import { cohereRerank } from '@tanstack/ai-cohere'
321​
322const result = await rerank({
323 adapter: cohereRerank('rerank-v3.5'),
324 query: 'q',
325 documents: ['a', 'b'],
326 middleware: [
327 {
328 name: 'usage-logger',
329 onUsage: (_ctx, usage) => {
330 if (usage.billed) {
331 console.log(
332 `search units billed: ${usage.billed.quantity} ${usage.billed.unit}`,
333 )
334 }
335 },
336 },
337 ],
338})
339​
340console.log(result.rerankedDocuments)
341```
342​
343> **Tip:** Pass `otelMiddleware()` to emit OpenTelemetry spans for rerank
344> calls. See [OpenTelemetry](../advanced/otel).
345​
346## Environment Variables
347​
348The Cohere rerank adapter uses:
349​
350- `COHERE_API_KEY`: Your Cohere API key
351​
352## Error Handling
353​
354```typescript
355import { rerank } from '@tanstack/ai'
356import { cohereRerank } from '@tanstack/ai-cohere'
357​
358try {
359 const result = await rerank({
360 adapter: cohereRerank('rerank-v3.5'),
361 query: 'q',
362 documents: ['a', 'b'],
363 })
364 console.log(result.rerankedDocuments)
365} catch (error) {
366 if (error instanceof Error) {
367 console.error('Rerank failed:', error.message)
368 }
370```
371​
372> Passing an empty `documents` array throws before any request is made.
373​
374## Runnable Example
375​
376`examples/ts-react-rerank` is a small TanStack Start app that runs everything
377on this page: a fixed corpus of support articles listed newest-first, a query
378box, and a side-by-side view of the original order against the reranked order
379with scores. The provider dropdown switches between the Cohere and OpenRouter
380adapters over the same `rerank()` call.
381​
382```bash
383cd examples/ts-react-rerank
384pnpm install
385cp .env.example .env # add COHERE_API_KEY and/or OPENROUTER_API_KEY
386pnpm dev
387```
388​
389## Next Steps
390​
391- [Cohere Adapter](../adapters/cohere) — models, configuration, and explicit API keys
392- [OpenRouter Adapter](../adapters/openrouter) — rerank through your OpenRouter key
393- [Middleware](../advanced/middleware) — lifecycle hooks for usage and errors