> Complete content index: https://narsil.sondelali.com/llms.txt

# 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.

URL: https://narsil.sondelali.com/docs/reranking
Section: Search modes
Version: 0.4 (@delali/narsil@0.4.3, latest)

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.

<CodeGroup sync="language">

```bash title="pnpm" tab="TypeScript"
pnpm add @delali/narsil @delali/narsil-embeddings-transformers @huggingface/transformers
```

```bash title="pip" tab="Python"
pip install delali-narsil fastembed
```

```bash title="go get" tab="Go"
go get github.com/assetcorp/narsil/packages/go/engine@v0.2.1 github.com/knights-analytics/hugot
```

```bash title="cargo" tab="Rust"
cargo add delali-narsil fastembed
cargo add hf-hub@0.5 --no-default-features --features ureq,native-tls
```

</CodeGroup>

## 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.

<CodeGroup sync="language">

```ts title="support.ts" tab="TypeScript"
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()
```

```json result open
{
  "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
    }
  ]
}
```

```python title="support.py" tab="Python"
import json
import math

from fastembed.rerank.cross_encoder import TextCrossEncoder
from narsil import Narsil


class CrossEncoder:
    def __init__(self):
        self.model = TextCrossEncoder("Xenova/ms-marco-MiniLM-L-6-v2")

    def score(self, query, documents):
        return [1 / (1 + math.exp(-logit)) for logit in self.model.rerank(query, documents)]


ARTICLES = [
    {"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."},
]

with Narsil({"rerankAdapters": {"ms-marco": CrossEncoder()}}) as narsil:
    narsil.create_index("help-desk", {"schema": {"title": "string", "body": "string"}})
    narsil.insert_batch("help-desk", ARTICLES)

    question = "my parcel arrived broken, can I get a refund"

    plain = narsil.query("help-desk", {"term": question, "limit": 6, "document": False})

    reranked = narsil.query(
        "help-desk",
        {
            "term": question,
            "limit": 6,
            "document": False,
            "rerank": {"adapter": "ms-marco", "fields": ["title", "body"], "window": 4},
        },
    )

    print(
        json.dumps(
            {
                "plain": [{"id": hit["id"], "score": round(hit["score"], 4)} for hit in plain["hits"]],
                "reranked": [{"id": hit["id"], "score": round(hit["score"], 4)} for hit in reranked["hits"]],
            },
            indent=2,
        )
    )
```

```json result open
{
  "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.0
    },
    {
      "id": "returns-window",
      "score": -0.1858
    },
    {
      "id": "reader-replacement",
      "score": -0.2001
    }
  ]
}
```

```go title="main.go" tab="Go"
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/assetcorp/narsil/packages/go/engine"
	"github.com/knights-analytics/hugot"
	"github.com/knights-analytics/hugot/pipelines"
)

type crossEncoder struct {
	model *pipelines.CrossEncoderPipeline
}

func (c crossEncoder) Rerank(ctx context.Context, query string, documents []string) ([]float64, error) {
	output, err := c.model.RunPipeline(ctx, query, documents)
	if err != nil {
		return nil, err
	}
	scores := make([]float64, len(documents))
	for _, result := range output.Results {
		scores[result.Index] = float64(result.Score)
	}
	return scores, nil
}

func loadModel(ctx context.Context) (*hugot.Session, *pipelines.CrossEncoderPipeline, error) {
	session, err := hugot.NewGoSession(ctx)
	if err != nil {
		return nil, nil, err
	}
	if err := os.MkdirAll("./models", 0o755); err != nil {
		return nil, nil, err
	}
	options := hugot.NewDownloadOptions()
	options.OnnxFilePath = "onnx/model.onnx"
	modelPath, err := hugot.DownloadModel(ctx, "Xenova/ms-marco-MiniLM-L-6-v2", "./models", options)
	if err != nil {
		return nil, nil, err
	}
	model, err := hugot.NewPipeline(session, hugot.CrossEncoderConfig{
		ModelPath:    modelPath,
		Name:         "ms-marco-MiniLM-L-6-v2",
		OnnxFilename: "model.onnx",
	})
	return session, model, err
}

var articles = []map[string]any{
	{"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."},
}

func main() {
	if err := run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context) error {
	session, model, err := loadModel(ctx)
	if err != nil {
		return err
	}
	defer session.Destroy()

	narsil, err := engine.New(ctx, engine.Config{
		RerankAdapters: map[string]engine.RerankAdapter{"ms-marco": crossEncoder{model: model}},
	})
	if err != nil {
		return err
	}
	defer narsil.Shutdown(ctx)

	err = narsil.CreateIndex(ctx, "help-desk", engine.IndexConfig{
		Schema: engine.Schema{"title": engine.FieldString, "body": engine.FieldString},
	})
	if err != nil {
		return err
	}

	documents := make([]*engine.Document, len(articles))
	for position, article := range articles {
		documents[position] = engine.DocumentFromMap(article)
	}
	if _, err := narsil.InsertBatch(ctx, "help-desk", documents, engine.InsertOptions{}); err != nil {
		return err
	}

	question := "my parcel arrived broken, can I get a refund"

	plain, err := narsil.Query(ctx, "help-desk", engine.QueryParams{
		Term:     question,
		Limit:    engine.Some(6),
		Document: engine.NoDocumentFields(),
	})
	if err != nil {
		return err
	}

	reranked, err := narsil.Query(ctx, "help-desk", engine.QueryParams{
		Term:     question,
		Limit:    engine.Some(6),
		Document: engine.NoDocumentFields(),
		Rerank: &engine.RerankConfig{
			Adapter: "ms-marco",
			Fields:  []string{"title", "body"},
			Window:  engine.Some(4),
		},
	})
	if err != nil {
		return err
	}

	fmt.Println("plain:")
	for _, hit := range plain.Hits {
		fmt.Printf("  %s %.4f\n", hit.ID, hit.Score.Or(0))
	}
	fmt.Println("reranked:")
	for _, hit := range reranked.Hits {
		fmt.Printf("  %s %.4f\n", hit.ID, hit.Score.Or(0))
	}
	return nil
}
```

```text result open
plain:
  parcel-tracking 4.6575
  tracking-link 1.4852
  refund-timing 1.4463
  damaged-delivery 1.3178
  returns-window 0.6974
  reader-replacement 0.6495
reranked:
  damaged-delivery 0.0832
  refund-timing 0.0003
  parcel-tracking 0.0002
  tracking-link 0.0000
  returns-window -0.1858
  reader-replacement -0.2001
```

```rust title="src/main.rs" tab="Rust"
use std::sync::{Arc, Mutex};

use fastembed::{RerankInitOptionsUserDefined, TextRerank, TokenizerFiles, UserDefinedRerankingModel};
use hf_hub::api::sync::Api;
use narsil::{
    AdapterError, DocumentProjection, Hit, IndexConfig, Narsil, NarsilConfig, QueryParams, RerankAdapter,
    RerankConfig, Value, parse_json,
};

struct CrossEncoder(Mutex<TextRerank>);

impl CrossEncoder {
    fn load() -> Result<Self, Box<dyn std::error::Error>> {
        let repository = Api::new()?.model("Xenova/ms-marco-MiniLM-L-6-v2".into());
        let tokenizer = TokenizerFiles {
            tokenizer_file: std::fs::read(repository.get("tokenizer.json")?)?,
            config_file: std::fs::read(repository.get("config.json")?)?,
            special_tokens_map_file: std::fs::read(repository.get("special_tokens_map.json")?)?,
            tokenizer_config_file: std::fs::read(repository.get("tokenizer_config.json")?)?,
        };
        let model = UserDefinedRerankingModel::new(repository.get("onnx/model.onnx")?, tokenizer);
        let reranker = TextRerank::try_new_from_user_defined(model, RerankInitOptionsUserDefined::default())?;
        Ok(Self(Mutex::new(reranker)))
    }
}

impl RerankAdapter for CrossEncoder {
    fn score(&self, query: &str, documents: &[String]) -> Result<Vec<f64>, AdapterError> {
        let mut model = self.0.lock().map_err(|_| AdapterError::from("the model lock is poisoned"))?;
        let results = model.rerank(query.to_string(), documents.to_vec(), false, None)?;
        let mut scores = vec![0.0; documents.len()];
        for result in results {
            scores[result.index] = 1.0 / (1.0 + (-f64::from(result.score)).exp());
        }
        Ok(scores)
    }
}

const ARTICLES: &str = r#"[
  { "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." }
]"#;

fn print_hits(label: &str, hits: &[Hit]) {
    println!("{label}:");
    for hit in hits {
        println!("  {} {:.4}", hit.id, hit.score.unwrap_or(0.0));
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let narsil = Narsil::open(NarsilConfig::default())?;
    narsil.register_rerank_adapter("ms-marco", Arc::new(CrossEncoder::load()?))?;

    narsil.create_index(
        "help-desk",
        IndexConfig {
            schema: parse_json(r#"{ "title": "string", "body": "string" }"#)?,
            ..IndexConfig::default()
        },
    )?;

    let mut documents = Vec::new();
    if let Value::Array(articles) = parse_json(ARTICLES)? {
        for article in articles {
            if let Value::Object(document) = article {
                documents.push(document);
            }
        }
    }
    narsil.insert_batch("help-desk", documents)?;

    let question = "my parcel arrived broken, can I get a refund";

    let plain = narsil.query(
        "help-desk",
        &QueryParams {
            term: Some(question.into()),
            limit: Some(6),
            document: Some(DocumentProjection::None),
            ..QueryParams::default()
        },
    )?;

    let reranked = narsil.query(
        "help-desk",
        &QueryParams {
            term: Some(question.into()),
            limit: Some(6),
            document: Some(DocumentProjection::None),
            rerank: Some(RerankConfig {
                adapter: "ms-marco".into(),
                fields: vec!["title".into(), "body".into()],
                window: Some(4),
                ..RerankConfig::default()
            }),
            ..QueryParams::default()
        },
    )?;

    print_hits("plain", &plain.hits);
    print_hits("reranked", &reranked.hits);
    Ok(())
}
```

```text result open
plain:
  parcel-tracking 4.6575
  tracking-link 1.4852
  refund-timing 1.4463
  damaged-delivery 1.3178
  returns-window 0.6974
  reader-replacement 0.6495
reranked:
  damaged-delivery 0.0832
  refund-timing 0.0003
  parcel-tracking 0.0002
  tracking-link 0.0000
  returns-window -0.1858
  reader-replacement -0.2001
```

</CodeGroup>

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.

<CodeGroup sync="language">

```ts title="support.ts" tab="TypeScript"
import { createNarsil } from '@delali/narsil' // [!code --]
import { createNarsil, type RerankAdapter } from '@delali/narsil' // [!code ++]
import { createTransformersReranker } from '@delali/narsil-embeddings-transformers/reranker'

const crossEncoder = createTransformersReranker()
let modelCalls = 0 // [!code ++:9]

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 } }) // [!code --]
const narsil = await createNarsil({ rerankAdapters: { 'ms-marco': countedCrossEncoder } }) // [!code ++]

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 }) // [!code --:19]

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 }> = [] // [!code ++:14]

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()
```

```json result open
[
  {
    "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
  }
]
```

```python title="support.py" tab="Python"
import json
import math
import threading  # [!code ++]

from fastembed.rerank.cross_encoder import TextCrossEncoder
from narsil import Narsil


class CrossEncoder:
    def __init__(self):
        self.model = TextCrossEncoder("Xenova/ms-marco-MiniLM-L-6-v2")
        self.calls = 0  # [!code ++:2]
        self.lock = threading.Lock()

    def score(self, query, documents):
        with self.lock:  # [!code ++:2]
            self.calls += 1
        return [1 / (1 + math.exp(-logit)) for logit in self.model.rerank(query, documents)]


ARTICLES = [
    {"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."},
]

with Narsil({"rerankAdapters": {"ms-marco": CrossEncoder()}}) as narsil:  # [!code --]
cross_encoder = CrossEncoder()  # [!code ++:3]

with Narsil({"rerankAdapters": {"ms-marco": cross_encoder}}) as narsil:
    narsil.create_index("help-desk", {"schema": {"title": "string", "body": "string"}})
    narsil.insert_batch("help-desk", ARTICLES)

    question = "my parcel arrived broken, can I get a refund"

    plain = narsil.query("help-desk", {"term": question, "limit": 6, "document": False})  # [!code --:21]

    reranked = narsil.query(
        "help-desk",
        {
            "term": question,
            "limit": 6,
            "document": False,
            "rerank": {"adapter": "ms-marco", "fields": ["title", "body"], "window": 4},
        },
    )

    print(
        json.dumps(
            {
                "plain": [{"id": hit["id"], "score": round(hit["score"], 4)} for hit in plain["hits"]],
                "reranked": [{"id": hit["id"], "score": round(hit["score"], 4)} for hit in reranked["hits"]],
            },
            indent=2,
        )
    )
    pages = []  # [!code ++:15]
    for offset in [0, 2, 4, 6]:
        page = narsil.query(
            "help-desk",
            {
                "term": question,
                "offset": offset,
                "limit": 2,
                "document": False,
                "rerank": {"adapter": "ms-marco", "fields": ["title", "body"], "window": 4},
            },
        )
        pages.append({"offset": offset, "hits": [hit["id"] for hit in page["hits"]], "modelCalls": cross_encoder.calls})

    print(json.dumps(pages, indent=2))
```

```json result open
[
  {
    "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
  }
]
```

```go title="main.go" tab="Go"
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"sync/atomic" // [!code ++]

	"github.com/assetcorp/narsil/packages/go/engine"
	"github.com/knights-analytics/hugot"
	"github.com/knights-analytics/hugot/pipelines"
)

type crossEncoder struct {
	model *pipelines.CrossEncoderPipeline
	calls *atomic.Int64 // [!code ++]
}

func (c crossEncoder) Rerank(ctx context.Context, query string, documents []string) ([]float64, error) {
	c.calls.Add(1) // [!code ++]
	output, err := c.model.RunPipeline(ctx, query, documents)
	if err != nil {
		return nil, err
	}
	scores := make([]float64, len(documents))
	for _, result := range output.Results {
		scores[result.Index] = float64(result.Score)
	}
	return scores, nil
}

func loadModel(ctx context.Context) (*hugot.Session, *pipelines.CrossEncoderPipeline, error) {
	session, err := hugot.NewGoSession(ctx)
	if err != nil {
		return nil, nil, err
	}
	if err := os.MkdirAll("./models", 0o755); err != nil {
		return nil, nil, err
	}
	options := hugot.NewDownloadOptions()
	options.OnnxFilePath = "onnx/model.onnx"
	modelPath, err := hugot.DownloadModel(ctx, "Xenova/ms-marco-MiniLM-L-6-v2", "./models", options)
	if err != nil {
		return nil, nil, err
	}
	model, err := hugot.NewPipeline(session, hugot.CrossEncoderConfig{
		ModelPath:    modelPath,
		Name:         "ms-marco-MiniLM-L-6-v2",
		OnnxFilename: "model.onnx",
	})
	return session, model, err
}

var articles = []map[string]any{
	{"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."},
}

func main() {
	if err := run(context.Background()); err != nil {
		log.Fatal(err)
	}
}

func run(ctx context.Context) error {
	session, model, err := loadModel(ctx)
	if err != nil {
		return err
	}
	defer session.Destroy()

	modelCalls := &atomic.Int64{} // [!code ++:2]

	narsil, err := engine.New(ctx, engine.Config{
		RerankAdapters: map[string]engine.RerankAdapter{"ms-marco": crossEncoder{model: model}}, // [!code --]
		RerankAdapters: map[string]engine.RerankAdapter{"ms-marco": crossEncoder{model: model, calls: modelCalls}}, // [!code ++]
	})
	if err != nil {
		return err
	}
	defer narsil.Shutdown(ctx)

	err = narsil.CreateIndex(ctx, "help-desk", engine.IndexConfig{
		Schema: engine.Schema{"title": engine.FieldString, "body": engine.FieldString},
	})
	if err != nil {
		return err
	}

	documents := make([]*engine.Document, len(articles))
	for position, article := range articles {
		documents[position] = engine.DocumentFromMap(article)
	}
	if _, err := narsil.InsertBatch(ctx, "help-desk", documents, engine.InsertOptions{}); err != nil {
		return err
	}

	question := "my parcel arrived broken, can I get a refund"

	plain, err := narsil.Query(ctx, "help-desk", engine.QueryParams{ // [!code --:31]
		Term:     question,
		Limit:    engine.Some(6),
		Document: engine.NoDocumentFields(),
	})
	if err != nil {
		return err
	}

	reranked, err := narsil.Query(ctx, "help-desk", engine.QueryParams{
		Term:     question,
		Limit:    engine.Some(6),
		Document: engine.NoDocumentFields(),
		Rerank: &engine.RerankConfig{
			Adapter: "ms-marco",
			Fields:  []string{"title", "body"},
			Window:  engine.Some(4),
		},
	})
	if err != nil {
		return err
	}

	fmt.Println("plain:")
	for _, hit := range plain.Hits {
		fmt.Printf("  %s %.4f\n", hit.ID, hit.Score.Or(0))
	}
	fmt.Println("reranked:")
	for _, hit := range reranked.Hits {
		fmt.Printf("  %s %.4f\n", hit.ID, hit.Score.Or(0))
	}
	for _, offset := range []int{0, 2, 4, 6} { // [!code ++:21]
		page, err := narsil.Query(ctx, "help-desk", engine.QueryParams{
			Term:     question,
			Offset:   offset,
			Limit:    engine.Some(2),
			Document: engine.NoDocumentFields(),
			Rerank: &engine.RerankConfig{
				Adapter: "ms-marco",
				Fields:  []string{"title", "body"},
				Window:  engine.Some(4),
			},
		})
		if err != nil {
			return err
		}
		ids := make([]string, len(page.Hits))
		for position, hit := range page.Hits {
			ids[position] = hit.ID
		}
		fmt.Printf("offset %d: %v model calls: %d\n", offset, ids, modelCalls.Load())
	}
	return nil
}
```

```text result open
offset 0: [damaged-delivery refund-timing] model calls: 1
offset 2: [parcel-tracking tracking-link] model calls: 2
offset 4: [returns-window reader-replacement] model calls: 3
offset 6: [] model calls: 3
```

```rust title="src/main.rs" tab="Rust"
use std::sync::atomic::{AtomicUsize, Ordering}; // [!code ++]
use std::sync::{Arc, Mutex};

use fastembed::{RerankInitOptionsUserDefined, TextRerank, TokenizerFiles, UserDefinedRerankingModel};
use hf_hub::api::sync::Api;
use narsil::{
    AdapterError, DocumentProjection, Hit, IndexConfig, Narsil, NarsilConfig, QueryParams, RerankAdapter,
    RerankConfig, Value, parse_json,
};

struct CrossEncoder(Mutex<TextRerank>); // [!code --]
struct CrossEncoder { // [!code ++:4]
    model: Mutex<TextRerank>,
    calls: AtomicUsize,
}

impl CrossEncoder {
    fn load() -> Result<Self, Box<dyn std::error::Error>> {
        let repository = Api::new()?.model("Xenova/ms-marco-MiniLM-L-6-v2".into());
        let tokenizer = TokenizerFiles {
            tokenizer_file: std::fs::read(repository.get("tokenizer.json")?)?,
            config_file: std::fs::read(repository.get("config.json")?)?,
            special_tokens_map_file: std::fs::read(repository.get("special_tokens_map.json")?)?,
            tokenizer_config_file: std::fs::read(repository.get("tokenizer_config.json")?)?,
        };
        let model = UserDefinedRerankingModel::new(repository.get("onnx/model.onnx")?, tokenizer);
        let reranker = TextRerank::try_new_from_user_defined(model, RerankInitOptionsUserDefined::default())?;
        Ok(Self(Mutex::new(reranker))) // [!code --]
        Ok(Self { model: Mutex::new(reranker), calls: AtomicUsize::new(0) }) // [!code ++]
    }
}

impl RerankAdapter for CrossEncoder {
    fn score(&self, query: &str, documents: &[String]) -> Result<Vec<f64>, AdapterError> {
        let mut model = self.0.lock().map_err(|_| AdapterError::from("the model lock is poisoned"))?; // [!code --]
        self.calls.fetch_add(1, Ordering::Relaxed); // [!code ++:2]
        let mut model = self.model.lock().map_err(|_| AdapterError::from("the model lock is poisoned"))?;
        let results = model.rerank(query.to_string(), documents.to_vec(), false, None)?;
        let mut scores = vec![0.0; documents.len()];
        for result in results {
            scores[result.index] = 1.0 / (1.0 + (-f64::from(result.score)).exp());
        }
        Ok(scores)
    }
}

const ARTICLES: &str = r#"[
  { "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." }
]"#;

fn print_hits(label: &str, hits: &[Hit]) { // [!code --:5]
    println!("{label}:");
    for hit in hits {
        println!("  {} {:.4}", hit.id, hit.score.unwrap_or(0.0));
    }
fn ids(hits: &[Hit]) -> Vec<&str> { // [!code ++:2]
    hits.iter().map(|hit| hit.id.as_str()).collect()
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cross_encoder = Arc::new(CrossEncoder::load()?); // [!code ++:2]

    let narsil = Narsil::open(NarsilConfig::default())?;
    narsil.register_rerank_adapter("ms-marco", Arc::new(CrossEncoder::load()?))?; // [!code --]
    narsil.register_rerank_adapter("ms-marco", cross_encoder.clone())?; // [!code ++]

    narsil.create_index(
        "help-desk",
        IndexConfig {
            schema: parse_json(r#"{ "title": "string", "body": "string" }"#)?,
            ..IndexConfig::default()
        },
    )?;

    let mut documents = Vec::new();
    if let Value::Array(articles) = parse_json(ARTICLES)? {
        for article in articles {
            if let Value::Object(document) = article {
                documents.push(document);
            }
        }
    }
    narsil.insert_batch("help-desk", documents)?;

    let question = "my parcel arrived broken, can I get a refund";

    let plain = narsil.query( // [!code --:28]
        "help-desk",
        &QueryParams {
            term: Some(question.into()),
            limit: Some(6),
            document: Some(DocumentProjection::None),
            ..QueryParams::default()
        },
    )?;

    let reranked = narsil.query(
        "help-desk",
        &QueryParams {
            term: Some(question.into()),
            limit: Some(6),
            document: Some(DocumentProjection::None),
            rerank: Some(RerankConfig {
                adapter: "ms-marco".into(),
                fields: vec!["title".into(), "body".into()],
                window: Some(4),
                ..RerankConfig::default()
            }),
            ..QueryParams::default()
        },
    )?;

    print_hits("plain", &plain.hits);
    print_hits("reranked", &reranked.hits);
    for offset in [0, 2, 4, 6] { // [!code ++:20]
        let page = narsil.query(
            "help-desk",
            &QueryParams {
                term: Some(question.into()),
                offset: Some(offset),
                limit: Some(2),
                document: Some(DocumentProjection::None),
                rerank: Some(RerankConfig {
                    adapter: "ms-marco".into(),
                    fields: vec!["title".into(), "body".into()],
                    window: Some(4),
                    ..RerankConfig::default()
                }),
                ..QueryParams::default()
            },
        )?;
        let calls = cross_encoder.calls.load(Ordering::Relaxed);
        println!("offset {offset}: {:?} model calls: {calls}", ids(&page.hits));
    }
    Ok(())
}
```

```text result open
offset 0: ["damaged-delivery", "refund-timing"] model calls: 1
offset 2: ["parcel-tracking", "tracking-link"] model calls: 2
offset 4: ["returns-window", "reader-replacement"] model calls: 3
offset 6: [] model calls: 3
```

</CodeGroup>

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.

```ts title="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](/docs/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](/docs/hybrid-search) for the fused list of keyword and vector hits, which the engine reorders in a reranked hybrid query.
- Read [Embedding adapters](/docs/embedding-adapters) for the other adapter that the engine calls, which turns text into vectors.
- Read [HTTP server](/docs/http-server) for serving the engine and its rerank adapters to clients in other languages.
