Search modes

Reranking

Reorder the top hits of a search with a cross-encoder that scores the question and each hit together, from a model in your process in TypeScript, Python, Go, or Rust, or from a hosted rerank service in TypeScript.

When you rerank a search, the engine reorders its top hits by the scores of a second model, called a cross-encoder. That model takes the question and one hit as a single input and scores how closely the hit matches the question. The engine first ranks the hits of a keyword, vector, or hybrid query as it does without reranking. It then sends the text of the top hits to a rerank adapter and orders those hits by the scores that the adapter returns. The next two sections hold one program for a small help desk, written in two steps. Each of their code blocks holds the whole file, with green lines marking the lines that you add at each step and struck lines marking the lines that you remove.

Install a model that works inside your process

In every language, the engine calls the model through a rerank adapter. The adapters on this page call ms-marco-MiniLM-L-6-v2, a cross-encoder that your program loads into its process without an API key. In TypeScript, createTransformersReranker from @delali/narsil-embeddings-transformers/reranker returns an adapter that calls the model through Transformers.js. In Python, Go, and Rust, the adapter is a short class or type that you write around fastembed in Python and Rust, or around hugot in Go. The Rust fastembed crate holds no ready-made entry for this model, so the Rust program fetches the model files from the Hugging Face Hub with hf-hub and passes them to fastembed. The second Rust command adds hf-hub without its default features, so that Cargo compiles it with the HTTP client that fastembed uses. Each library downloads the model the first time that your program loads it.

pnpm add @delali/narsil @delali/narsil-embeddings-transformers @huggingface/transformers

Put the article that answers the question first

A rerank adapter accepts the question and a list of document texts, and it returns one number for each text in the same order, with a higher number for a closer match. The method of the adapter is rerank in TypeScript and Go and score in Python and Rust. When you call createTransformersReranker with no settings, the TypeScript adapter loads Xenova/ms-marco-MiniLM-L-6-v2 with 32-bit weights on its first call. The model gives each pair a raw score, which the TypeScript adapter passes through a sigmoid by default to give a number from 0 to 1. The Python and Rust adapters on this page apply the same sigmoid, while hugot applies it itself. hugot and the Rust fastembed crate return their results sorted by score, so the Go and Rust adapters put each score back at the position of its document.

The engine holds the adapter under the name ms-marco. The rerank setting of the query holds that name, the fields whose text the engine sends to the model, and the window, which is the number of top hits that the model scores. The engine builds the text of each document from those fields in the order that you list them, with one line for each value. The program sends the same question once without rerank and once with it.

import { createNarsil } from '@delali/narsil'
import { createTransformersReranker } from '@delali/narsil-embeddings-transformers/reranker'
 
const crossEncoder = createTransformersReranker()
 
const narsil = await createNarsil({ rerankAdapters: { 'ms-marco': crossEncoder } })
 
await narsil.createIndex('help-desk', { schema: { title: 'string', body: 'string' } })
 
await narsil.insertBatch('help-desk', [
  { id: 'parcel-tracking', title: 'Track a parcel after dispatch', body: 'Every parcel has a tracking code, and the carrier updates it at each depot until the parcel arrives.' },
  { id: 'damaged-delivery', title: 'Report an order that arrived damaged', body: 'Send a photo of the damage within 48 hours of delivery, and the shop refunds the full price or sends a replacement.' },
  { id: 'refund-timing', title: 'How a refund reaches your bank', body: 'A refund returns to the card that paid for the order, and your bank posts it within five working days.' },
  { id: 'tracking-link', title: 'Open a broken tracking link', body: 'A tracking link can break when the carrier moves its site, so paste the code on the carrier page.' },
  { id: 'returns-window', title: 'Return an item that you no longer want', body: 'Unopened items go back within 30 days, and the refund goes to the card that paid.' },
  { id: 'reader-replacement', title: 'Replace a reader that stops charging', body: 'Send back the unit marked R7-Mini on its base, and a replacement arrives within two working days.' },
])
 
const question = 'my parcel arrived broken, can I get a refund'
 
const plain = await narsil.query('help-desk', { term: question, limit: 6, document: false })
 
const reranked = await narsil.query('help-desk', {
  term: question,
  limit: 6,
  document: false,
  rerank: { adapter: 'ms-marco', fields: ['title', 'body'], window: 4 },
})
 
console.log(
  JSON.stringify(
    {
      plain: plain.hits.map((hit) => ({ id: hit.id, score: hit.score })),
      reranked: reranked.hits.map((hit) => ({ id: hit.id, score: hit.score })),
    },
    (key, value) => (typeof value === 'number' ? Number(value.toFixed(4)) : value),
    2
  )
)
 
await narsil.shutdown()
{
  "plain": [
    {
      "id": "parcel-tracking",
      "score": 4.6575
    },
    {
      "id": "tracking-link",
      "score": 1.4852
    },
    {
      "id": "refund-timing",
      "score": 1.4463
    },
    {
      "id": "damaged-delivery",
      "score": 1.3178
    },
    {
      "id": "returns-window",
      "score": 0.6974
    },
    {
      "id": "reader-replacement",
      "score": 0.6495
    }
  ],
  "reranked": [
    {
      "id": "damaged-delivery",
      "score": 0.0832
    },
    {
      "id": "refund-timing",
      "score": 0.0003
    },
    {
      "id": "parcel-tracking",
      "score": 0.0002
    },
    {
      "id": "tracking-link",
      "score": 0
    },
    {
      "id": "returns-window",
      "score": -0.1858
    },
    {
      "id": "reader-replacement",
      "score": -0.2001
    }
  ]
}

Without reranking, the engine ranks parcel-tracking first and damaged-delivery, the article with the answer, fourth. With a window of 4, the model scores the top four hits, so the engine moves damaged-delivery to the top and sets the score of each of those four hits to the score from the model. returns-window and reader-replacement fall below the window, so the engine keeps them in their keyword order behind the reranked hits. The engine also scales their scores down, so that neither of them has a higher score than a reranked hit.

The model scores every hit in the window for every page, so a larger window adds model work to each page. The engine leaves each hit below the window in its place, however, even when that hit is a closer match to the question than every hit in the window. When you leave window out, the model scores the top 100 hits, or fewer when maxRerankWindow or the hybrid.depth of a hybrid query sets a lower limit.

Page through a reranked list

In this step, the program counts the calls that the engine makes to the model and fetches the results two hits at a time. In TypeScript, the program wraps the adapter from createTransformersReranker in an object that counts each call before it passes the call on. The wrapper passes shutdown on as well, so that the adapter releases the model when narsil.shutdown() calls the shutdown method of each rerank adapter. In Python, Go, and Rust, the engine calls the adapter from a thread or goroutine other than the one that sends the query, so those programs guard the counter with a lock or keep it in an atomic integer.

import { createNarsil } from '@delali/narsil'
import { createNarsil, type RerankAdapter } from '@delali/narsil'
import { createTransformersReranker } from '@delali/narsil-embeddings-transformers/reranker'
 
const crossEncoder = createTransformersReranker()
let modelCalls = 0
 
const countedCrossEncoder: RerankAdapter = {
  rerank(query, documents, signal) {
    modelCalls += 1
    return crossEncoder.rerank(query, documents, signal)
  },
  shutdown: () => crossEncoder.shutdown(),
}
 
const narsil = await createNarsil({ rerankAdapters: { 'ms-marco': crossEncoder } }) 
const narsil = await createNarsil({ rerankAdapters: { 'ms-marco': countedCrossEncoder } }) 
 
await narsil.createIndex('help-desk', { schema: { title: 'string', body: 'string' } })
 
await narsil.insertBatch('help-desk', [
  { id: 'parcel-tracking', title: 'Track a parcel after dispatch', body: 'Every parcel has a tracking code, and the carrier updates it at each depot until the parcel arrives.' },
  { id: 'damaged-delivery', title: 'Report an order that arrived damaged', body: 'Send a photo of the damage within 48 hours of delivery, and the shop refunds the full price or sends a replacement.' },
  { id: 'refund-timing', title: 'How a refund reaches your bank', body: 'A refund returns to the card that paid for the order, and your bank posts it within five working days.' },
  { id: 'tracking-link', title: 'Open a broken tracking link', body: 'A tracking link can break when the carrier moves its site, so paste the code on the carrier page.' },
  { id: 'returns-window', title: 'Return an item that you no longer want', body: 'Unopened items go back within 30 days, and the refund goes to the card that paid.' },
  { id: 'reader-replacement', title: 'Replace a reader that stops charging', body: 'Send back the unit marked R7-Mini on its base, and a replacement arrives within two working days.' },
])
 
const question = 'my parcel arrived broken, can I get a refund'
 
const plain = await narsil.query('help-desk', { term: question, limit: 6, document: false }) 
 
const reranked = await narsil.query('help-desk', {
  term: question,
  limit: 6,
  document: false,
  rerank: { adapter: 'ms-marco', fields: ['title', 'body'], window: 4 },
})
 
console.log(
  JSON.stringify(
    {
      plain: plain.hits.map((hit) => ({ id: hit.id, score: hit.score })),
      reranked: reranked.hits.map((hit) => ({ id: hit.id, score: hit.score })),
    },
    (key, value) => (typeof value === 'number' ? Number(value.toFixed(4)) : value),
    2
  )
)
const pages: Array<{ offset: number; hits: string[]; modelCalls: number }> = [] 
 
for (const offset of [0, 2, 4, 6]) {
  const page = await narsil.query('help-desk', {
    term: question,
    offset,
    limit: 2,
    document: false,
    rerank: { adapter: 'ms-marco', fields: ['title', 'body'], window: 4 },
  })
  pages.push({ offset, hits: page.hits.map((hit) => hit.id), modelCalls })
}
 
console.log(JSON.stringify(pages, null, 2))
 
await narsil.shutdown()
[
  {
    "offset": 0,
    "hits": [
      "damaged-delivery",
      "refund-timing"
    ],
    "modelCalls": 1
  },
  {
    "offset": 2,
    "hits": [
      "parcel-tracking",
      "tracking-link"
    ],
    "modelCalls": 2
  },
  {
    "offset": 4,
    "hits": [
      "returns-window",
      "reader-replacement"
    ],
    "modelCalls": 3
  },
  {
    "offset": 6,
    "hits": [],
    "modelCalls": 3
  }
]

The engine reranks the same top hits for every page of one query, so each hit appears on exactly one page. The engine calls the model once for each page that holds hits. That includes the third page, which holds only hits from below the window, because the engine scores the window again to place them. The page at offset 6 starts after the last hit, so the engine makes no call for it. Each result also holds a cursor for the next page. The engine accepts that cursor only with the same query, so it raises SEARCH_INVALID_CURSOR when you send the cursor back with another rerank setting.

Limit the work that one query can ask of the model

You can limit the work of the model with two engine settings:

  • maxRerankWindow is the largest window that a query can set. You can set it to a whole number from 1 to 1,000, and it is 100 by default. The engine raises RERANK_CONFIG_INVALID for a query that sets a larger window.
  • rerankTimeout, which is 30,000 ms by default, is how long the engine waits for the adapter before it raises RERANK_FAILED.

The Python engine accepts the same two keys. In Go, the fields are MaxRerankWindow and RerankTimeout, which holds a time.Duration, while in Rust they are max_rerank_window and rerank_timeout_ms on NarsilConfig.

At the timeout, the TypeScript engine aborts the signal that it passes to the adapter as a third argument, while the Go engine cancels the context of the adapter, so an adapter that checks either one can stop early. The Rust engine stops waiting at the timeout, although the adapter keeps working in its thread until the model returns.

The engine also refuses a query in these cases:

  • When a query sets both rerank and sort, the engine raises SEARCH_INVALID_MODE, because both options set the order of the hits.
  • When the adapter name in a query matches none of the adapters that you register, the engine raises RERANK_CONFIG_INVALID. It raises the same code when fields lists a field that the schema declares as anything other than string, string[], verbatim, or verbatim[].
  • The model compares each hit with the query's term, or with its vector.text when it has no term, while rerank.query, when you set it, takes the place of that text. When a query holds none of the three, the engine raises RERANK_CONFIG_INVALID.
  • When an adapter throws, returns a list of another length, or returns a number that is not finite, the engine raises RERANK_FAILED.

Call a hosted rerank service from TypeScript

Only the TypeScript package includes an adapter for a hosted service. createHttpReranker from @delali/narsil/rerankers/http returns an adapter that calls any service that serves the Cohere-compatible /rerank route, such as Cohere's API. This program takes your Cohere key from COHERE_API_KEY and reranks the same help desk with Cohere's model.

hosted.ts
import { createNarsil } from '@delali/narsil'
import { createHttpReranker } from '@delali/narsil/rerankers/http'
 
const apiKey = process.env.COHERE_API_KEY
if (apiKey === undefined) {
  throw new Error('Set COHERE_API_KEY to an API key from your Cohere dashboard')
}
 
const narsil = await createNarsil({
  rerankAdapters: {
    cohere: createHttpReranker({ baseUrl: 'https://api.cohere.com/v2', model: 'rerank-v5.0-pro', apiKey }),
  },
})
 
await narsil.createIndex('help-desk', { schema: { title: 'string', body: 'string' } })
 
await narsil.insertBatch('help-desk', [
  { id: 'parcel-tracking', title: 'Track a parcel after dispatch', body: 'Every parcel has a tracking code, and the carrier updates it at each depot until the parcel arrives.' },
  { id: 'damaged-delivery', title: 'Report an order that arrived damaged', body: 'Send a photo of the damage within 48 hours of delivery, and the shop refunds the full price or sends a replacement.' },
  { id: 'refund-timing', title: 'How a refund reaches your bank', body: 'A refund returns to the card that paid for the order, and your bank posts it within five working days.' },
  { id: 'tracking-link', title: 'Open a broken tracking link', body: 'A tracking link can break when the carrier moves its site, so paste the code on the carrier page.' },
  { id: 'returns-window', title: 'Return an item that you no longer want', body: 'Unopened items go back within 30 days, and the refund goes to the card that paid.' },
  { id: 'reader-replacement', title: 'Replace a reader that stops charging', body: 'Send back the unit marked R7-Mini on its base, and a replacement arrives within two working days.' },
])
 
const reranked = await narsil.query('help-desk', {
  term: 'my parcel arrived broken, can I get a refund',
  limit: 6,
  document: false,
  rerank: { adapter: 'cohere', fields: ['title', 'body'], window: 4 },
})
 
console.log(reranked.hits.map((hit) => hit.id))
 
await narsil.shutdown()

The program prints the ids in the order of the scores from Cohere's model, which can differ from the order of the local model above. The adapter posts the model, the question, and the documents to baseUrl followed by /rerank, and it sends the key as a bearer token. From the reply, the adapter takes one relevance_score for each document and puts it back at the position of that document. Four options change how the adapter calls the service:

  • By default, the adapter retries a reply of 429, 500, 502, 503, or 504, or a network failure, up to 3 times. Set maxRetries to change that number.
  • The adapter gives up on a call after 30,000 ms unless you set another timeout.
  • The adapter splits a list of more than 1,000 documents across several requests. Set maxDocumentsPerRequest to change that size.
  • apiKey can be a function, which the adapter calls before each rerank, so that the adapter sends the current key with every request.

In Python, Go, or Rust, an adapter for the same route is a class or type, like the ones above, whose scoring method posts the question and the documents and returns the scores.

The HTTP server accepts rerankAdapters among its options and registers them on the engine that it serves, so that a client in any language can set rerank in its query. By default, the server's limits.maxRerankWindow caps the window of a request at 100, or at the engine's limit when that is lower. The server returns status 400 for RERANK_CONFIG_INVALID and status 503 for RERANK_FAILED.

Where to go next

  • Read Hybrid search for the fused list of keyword and vector hits, which the engine reorders in a reranked hybrid query.
  • Read Embedding adapters for the other adapter that the engine calls, which turns text into vectors.
  • Read HTTP server for serving the engine and its rerank adapters to clients in other languages.