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

rerank.md

338 lines10.1 KB

1---
2title: Reranking
3id: rerank
4order: 1
5description: "Sort candidate documents by how well they answer a query with rerank(). Use it as the precision step for RAG and search, with Cohere or OpenRouter."
6keywords:
7 - tanstack ai
8 - rerank
9 - reranking
10 - relevance
11 - rag
12 - retrieval
13 - semantic search
14 - cohere
15---
16​
17`rerank()` sorts candidate documents by relevance to a query. Use it after vector search or keyword search.
18​
19`rerank()` sends the query and the candidates to a reranking model. You get the documents back sorted by relevance, with a score for each.
20​
21## Quick setup
22​
231. Install the core package and the Cohere adapter:
24​
25<!-- ::start:tabs variant="package-manager" mode="install" -->
26​
27react: @tanstack/ai @tanstack/ai-cohere
28vue: @tanstack/ai @tanstack/ai-cohere
29solid: @tanstack/ai @tanstack/ai-cohere
30svelte: @tanstack/ai @tanstack/ai-cohere
31preact: @tanstack/ai @tanstack/ai-cohere
32angular: @tanstack/ai @tanstack/ai-cohere
33vanilla: @tanstack/ai @tanstack/ai-cohere
34octane: @tanstack/ai @tanstack/ai-cohere
35​
36<!-- ::end:tabs -->
37​
382. Put your key on the server. The adapter reads it at runtime:
39​
40```bash
41COHERE_API_KEY=your-cohere-api-key
42```
43​
443. Call `rerank()` on the server:
45​
46```typescript
47import { rerank } from '@tanstack/ai'
48import { cohereRerank } from '@tanstack/ai-cohere'
49​
50const { ranking, rerankedDocuments } = await rerank({
51 adapter: cohereRerank('rerank-v3.5'),
52 query: 'talk about rain',
53 documents: ['sunny day at the beach', 'rainy afternoon in the city'],
54 topN: 2,
55})
56​
57console.log(rerankedDocuments[0]) // 'rainy afternoon in the city'
58console.log(ranking[0]) // { index: 1, score: 0.98, document: 'rainy afternoon in the city' }
59```
60​
61The most relevant document is now first.
62​
63## How it works
64​
65- `rerankedDocuments` holds your documents, most relevant first.
66- `ranking` holds the same order with a `score` and the original `index` for each document.
67- `topN` keeps only the best N results. Leave it out to get all of them back.
68- Every rerank adapter uses the same `rerank()` call. To change provider, change the adapter.
69​
70## Use it in a RAG pipeline
71​
72Reranking is the second stage after a broad, cheap retrieval. Fetch many candidates with vector search. Then rerank and keep only the best few for the prompt:
73​
74```typescript ignore
75import { rerank } from '@tanstack/ai'
76import { cohereRerank } from '@tanstack/ai-cohere'
77import { vectorSearch } from './my-vector-store'
78​
79async function retrieveContext(query: string) {
80 // 1. Fetch many candidates cheaply.
81 const candidates = await vectorSearch(query, { limit: 50 })
82​
83 // 2. Rerank and keep the most relevant few for the prompt.
84 const { rerankedDocuments } = await rerank({
85 adapter: cohereRerank('rerank-v3.5'),
86 query,
87 documents: candidates.map((c) => c.text),
88 topN: 5,
89 })
90​
91 return rerankedDocuments
93```
94​
95To make the vectors for that first stage, see [Embeddings](../embeddings).
96​
97## Rerank objects, not only strings
98​
99Pass JSON-serializable objects to keep an id or metadata with each document. The result gives back your original object, with full types:
100​
101```typescript
102import { rerank } from '@tanstack/ai'
103import { cohereRerank } from '@tanstack/ai-cohere'
104​
105const chunks = [
106 { id: 'doc-1', text: 'A heavy gaming desktop with an RTX card.' },
107 { id: 'doc-2', text: 'A lightweight ultrabook with all-day battery.' },
109​
110const { ranking } = await rerank({
111 adapter: cohereRerank('rerank-v3.5'),
112 query: 'best laptop for travel',
113 documents: chunks,
114})
115​
116// `document` is the original object, so `id` is typed.
117console.log(ranking[0]?.document.id) // 'doc-2'
118```
119​
120## Call it from the browser
121​
122`rerank()` needs your API key, so it runs on the server. Put it in a route and call the route from the client.
123​
124Server route:
125​
126```typescript
127import { rerank } from '@tanstack/ai'
128import { cohereRerank } from '@tanstack/ai-cohere'
129​
130export async function POST(request: Request) {
131 const body: unknown = await request.json()
132 if (
133 typeof body !== 'object' ||
134 body === null ||
135 !('query' in body) ||
136 typeof body.query !== 'string' ||
137 !('documents' in body) ||
138 !Array.isArray(body.documents)
139 ) {
140 return new Response('Invalid request body', { status: 400 })
141 }
142​
143 const result = await rerank({
144 adapter: cohereRerank('rerank-v3.5'),
145 query: body.query,
146 documents: body.documents,
147 topN: 3,
148 })
149​
150 return Response.json(result)
152```
153​
154Client:
155​
156```typescript
157export async function rerankDocuments(query: string, documents: Array<string>) {
158 const res = await fetch('/api/rerank', {
159 method: 'POST',
160 headers: { 'Content-Type': 'application/json' },
161 body: JSON.stringify({ query, documents }),
162 })
163 const result = await res.json()
164 return result.rerankedDocuments
166```
167​
168## Use OpenRouter instead
169​
170OpenRouter routes rerank through your existing OpenRouter key. Install `@tanstack/ai-openrouter`, then swap the adapter:
171​
172```typescript
173import { rerank } from '@tanstack/ai'
174import { openRouterRerank } from '@tanstack/ai-openrouter'
175​
176const { rerankedDocuments } = await rerank({
177 adapter: openRouterRerank('cohere/rerank-v3.5'),
178 query: 'talk about rain',
179 documents: ['sunny day at the beach', 'rainy afternoon in the city'],
180 topN: 2,
181})
182​
183console.log(rerankedDocuments[0]) // 'rainy afternoon in the city'
184```
185​
186`openRouterRerank` reads `OPENROUTER_API_KEY` from the environment.
187​
188## Try the example
189​
190`examples/ts-react-rerank` is a small TanStack Start app. It shows a list of support articles, a query box, and the original order next to the reranked order with scores. A dropdown switches between the Cohere and OpenRouter adapters.
191​
192```bash
193cd examples/ts-react-rerank
194pnpm install
195cp .env.example .env # add COHERE_API_KEY and/or OPENROUTER_API_KEY
196pnpm dev
197```
198​
199## Advanced
200​
201### Options
202​
203| Option | Type | Description |
204| -------------- | ----------------------------- | ----------------------------------------------------------------------- |
205| `adapter` | `RerankAdapter` | A rerank adapter with a model, for example `cohereRerank('rerank-v3.5')` |
206| `query` | `string` | The query to score documents against. Required. |
207| `documents` | `Array<string \| object>` | The candidate documents. Required. |
208| `topN` | `number` | Return only the top N results |
209| `abortSignal` | `AbortSignal` | Cancel the request |
210| `modelOptions` | provider options | Provider-specific options (see below) |
211| `middleware` | `Array<GenerationMiddleware>` | Observe-only lifecycle hooks (usage, finish, error, abort) |
212​
213### Cohere options
214​
215Cohere rerank accepts `maxTokensPerDoc`. It caps the tokens kept per document when Cohere splits long inputs. The Cohere default is 4096.
216​
217```typescript
218import { rerank } from '@tanstack/ai'
219import { cohereRerank } from '@tanstack/ai-cohere'
220​
221const { ranking } = await rerank({
222 adapter: cohereRerank('rerank-v3.5'),
223 query: 'refund policy',
224 documents: ['Returns accepted within 30 days.', 'Free shipping over $50.'],
225 modelOptions: {
226 maxTokensPerDoc: 512,
227 },
228})
229​
230console.log(ranking)
231```
232​
233### API keys
234​
235- `cohereRerank` reads `COHERE_API_KEY`.
236- `openRouterRerank` reads `OPENROUTER_API_KEY`.
237- To pass a Cohere key in code, use `createCohereRerank('rerank-v3.5', 'co-...')`.
238​
239### Object documents on the wire
240​
241The adapter serializes object documents to JSON before it sends them to the provider. Then it maps the ranking back to your original objects by index.
242​
243### Result shape
244​
245```typescript
246import type { TokenUsage } from '@tanstack/ai'
247​
248interface RerankResult<TDocument = string> {
249 id: string
250 model: string
251 // Scored results, most relevant first.
252 ranking: Array<{ index: number; score: number; document: TDocument }>
253 // The documents in relevance order (ranking.map(r => r.document)).
254 rerankedDocuments: Array<TDocument>
255 // Rerank usually bills in provider "search units"
256 // (usage.billed = { quantity, unit: 'units' }). Some providers (for example
257 // OpenRouter) also report totalTokens and cost. Cohere reports only search
258 // units and leaves token counts at 0.
259 usage: TokenUsage
261```
262​
263### Cancel a request
264​
265Pass an `abortSignal`:
266​
267```typescript
268import { rerank } from '@tanstack/ai'
269import { cohereRerank } from '@tanstack/ai-cohere'
270​
271const controller = new AbortController()
272setTimeout(() => controller.abort(), 5000)
273​
274const result = await rerank({
275 adapter: cohereRerank('rerank-v3.5'),
276 query: 'q',
277 documents: ['a', 'b'],
278 abortSignal: controller.signal,
279})
280​
281console.log(result.rerankedDocuments)
282```
283​
284### Track usage
285​
286Add observe-only middleware to track usage, completion, errors, and cancellation. It is the same `GenerationMiddleware` contract that the media activities use. See [Middleware](../advanced/middleware).
287​
288```typescript
289import { rerank } from '@tanstack/ai'
290import { cohereRerank } from '@tanstack/ai-cohere'
291​
292const result = await rerank({
293 adapter: cohereRerank('rerank-v3.5'),
294 query: 'q',
295 documents: ['a', 'b'],
296 middleware: [
297 {
298 name: 'usage-logger',
299 onUsage: (_ctx, usage) => {
300 if (usage.billed) {
301 console.log(
302 `search units billed: ${usage.billed.quantity} ${usage.billed.unit}`,
303 )
304 }
305 },
306 },
307 ],
308})
309​
310console.log(result.rerankedDocuments)
311```
312​
313> [!TIP]
314> Pass `otelMiddleware()` to emit OpenTelemetry spans for rerank calls. See [OpenTelemetry](../advanced/otel).
315​
316### Errors
317​
318An empty `documents` array throws before any request goes out. Provider errors reject the promise:
319​
320```typescript
321import { rerank } from '@tanstack/ai'
322import { cohereRerank } from '@tanstack/ai-cohere'
323​
324try {
325 const result = await rerank({
326 adapter: cohereRerank('rerank-v3.5'),
327 query: 'q',
328 documents: ['a', 'b'],
329 })
330 console.log(result.rerankedDocuments)
331} catch (error) {
332 if (error instanceof Error) {
333 console.error('Rerank failed:', error.message)
334 }
336```
337​
338For models and explicit keys, see the [Cohere adapter](../adapters/cohere) and the [OpenRouter adapter](../adapters/openrouter).