Reranking with a Reranker

Continue with the refund knowledge base, learn how rerankers assess relevance, and call Alibaba Cloud Model Studio’s Qwen reranking model from Node.js to inspect the results.

🎯 Introduction

In the previous two articles, we used hybrid retrieval to find candidate passages and RRF to combine rankings from different retrieval methods. This article introduces a reranker, a model that compares the user’s question with candidate text to reassess which passages best answer it. We will continue with the refund knowledge base, call an existing reranking model through Alibaba Cloud Model Studio, inspect its response, and learn how to use the results in our RAG application.


🧱 What Problem Does a Reranker Solve?

The user asks:

What documents do I need to request a refund?

Suppose Qdrant has retrieved three passages in the order A → B → C:

LabelMaterialText
ARefund policyYou can request a refund within 7 days of purchase. Sale items are nonrefundable.
BRefund requirementsRefund requests require an order number and proof of purchase.
CShipping instructionsStandard orders ship within 48 hours of payment.

We can see that B best answers the question: it states what the user needs to provide. A covers the refund window and restrictions; C covers shipping time.

Retrieval finds potentially relevant material. A reranker then assesses how relevant that material is to the current question. In a RAG pipeline, it sits here:

Retrieve with Qdrant → Rerank with a reranker → Generate an answer from the material with OpenAI.

This is an optional optimization. If the original retrieval is accurate enough, you may not need a reranker.


🔍 Where Do Relevance Scores Come From?

RRF calculates scores with a fixed formula based on positions in different result lists. A reranker uses a pretrained relevance model.

For the same question, it compares:

User questionCandidate materialWhat does the model assess?
What documents do I need to request a refund?A: Refund window and restrictionsDoes this answer what documents are required?
What documents do I need to request a refund?B: Order number and proof of purchaseDoes this answer what documents are required?
What documents do I need to request a refund?C: Shipping timeDoes this answer what documents are required?

The model uses language patterns and parameters learned during training to calculate each passage’s relevance to the question. We do not need to implement those calculations ourselves: send the question and passages, then receive the model’s ranked results.

Relevance scores compare passages within the same request. They are not probabilities that an answer is correct.

🧰 Set Up Alibaba Cloud Model Studio

This article uses Alibaba Cloud Model Studio’s qwen3.7-text-rerank model. Before calling the API, obtain an API key and a Workspace ID.

1. Register and Obtain Credentials

Open the Alibaba Cloud Model Studio console and complete these steps:

The console changes periodically, so button labels and navigation may differ. Treat these steps as a guide and follow the current interface.
  1. Register or sign in to an Alibaba Cloud account, complete identity verification, and activate Model Studio as prompted.
  2. Switch the region to China (Beijing).
  3. Open the API Key page, create a key in the default workspace, and copy it somewhere secure.
  4. Open workspace management and copy the default workspace’s Workspace ID.
The full API key may only be shown when it is created. Do not commit it to Git or include it in browser-side code.

2. Free Quota and Pricing

In the Beijing region, qwen3.7-text-rerank costs CNY 0.50 per million input tokens. Eligible new users can receive a free quota of 1 million tokens, valid for 90 days. Check the console for the applicable details.

If you want to use only the free quota, open the console’s free quota page, find the model, and enable the option to stop usage when the free quota is exhausted. Confirm that the setting has taken effect before calling the API. Otherwise, charges may apply after the quota is exhausted or expires.

3. Configure Environment Variables

Run this in a macOS or Linux terminal, replacing the example values with your credentials:

export DASHSCOPE_API_KEY="your_api_key"
export BAILIAN_WORKSPACE_ID="your_workspace_id"

Run the following Node.js example in the same terminal window.

Official references: API keys, Workspace IDs, model pricing, free quota, and Rerank API.


🛠 Call a Reranker from Node.js

This section does one thing: send the question and passages A, B, and C to the model and obtain its ranking. We use the built-in fetch() in Node.js 24.x, so no additional npm packages are needed.

1. Prepare the Question and Material

Create 11.reranker.mjs and add:

const question = "What documents do I need to request a refund?";

// Assume these are candidates already retrieved by Qdrant
const docs = [
    { id: "A", title: "Refund policy", text: "You can request a refund within 7 days of purchase. Sale items are nonrefundable." },
    { id: "B", title: "Refund requirements", text: "Refund requests require an order number and proof of purchase." },
    { id: "C", title: "Shipping instructions", text: "Standard orders ship within 48 hours of payment." }
];

question is the user’s question; docs contains the candidates to rerank. These are the same passages used in the hybrid retrieval and RRF articles.

2. Call the Model Studio Rerank API

Append this to the same 11.reranker.mjs file:

const apiKey = process.env.DASHSCOPE_API_KEY;
const workspaceId = process.env.BAILIAN_WORKSPACE_ID;

if (!apiKey || !workspaceId) {
    throw new Error("Configure DASHSCOPE_API_KEY and BAILIAN_WORKSPACE_ID first");
}

// Send the question and three passages to Alibaba Cloud Model Studio
const response = await fetch(
    `https://${workspaceId}.cn-beijing.maas.aliyuncs.com/compatible-api/v1/reranks`,
    {
        method: "POST",
        headers: {
            Authorization: `Bearer ${apiKey}`,
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            model: "qwen3.7-text-rerank",
            query: question,
            documents: docs.map(doc => doc.text),
            top_n: docs.length
        })
    }
);

if (!response.ok) {
    throw new Error(`Request failed: ${response.status} ${await response.text()}`);
}

const data = await response.json();

Focus on these four parameters:

ParameterPurpose
modelSelects Alibaba Cloud Model Studio’s Qwen text reranking model
queryThe current user question
documentsThe text of passages A, B, and C
top_nHow many ranked results to return; all three here

workspaceId in the URL is the Workspace ID obtained earlier. The model computes the relevance scores; the code contains no predefined scores.

3. Understand the API Response

To illustrate the response structure, suppose the model returns:

{
    "results": [
        { "index": 1, "relevance_score": 0.82 },
        { "index": 0, "relevance_score": 0.31 },
        { "index": 2, "relevance_score": 0.04 }
    ]
}
This is an example response for teaching purposes, not scores from an actual Model Studio call. Actual rankings and values depend on the model’s response.

You only need to understand two fields:

  • index: The passage’s position in the original docs array. For example, index: 1 identifies B, Refund requirements.
  • relevance_score: The model’s relevance score. Higher values indicate greater relevance within this request.

results is already ordered by descending relevance. This example therefore ranks the passages B → A → C, without requiring another sort() call.

4. Print the Reranked Results

Append this to the same file:

// Use the returned index to recover the original title and text
const ranked = data.results.map(result => ({
    ...docs[result.index],
    score: result.relevance_score
}));

console.log("Reranked results:");
ranked.forEach((doc, index) => {
    console.log(`${index + 1}. ${doc.title}(${doc.score.toFixed(4)})`);
});

Run the complete file:

node 11.reranker.mjs

If the API returned exactly the teaching example response above, the terminal would display:

Reranked results:
1. Refund requirements (0.8200)
2. Refund policy (0.3100)
3. Shipping instructions (0.0400)

This output demonstrates how the code displays model results; it does not report measured Model Studio scores. Real output varies with the model’s actual scoring.

In this example, B moves from second to first because “Refund requests require an order number and proof of purchase” most directly answers the question.


🔗 Use the Results in an Existing RAG Application

The example hardcodes docs. In a real project, transform the candidates retrieved by Qdrant into the same structure, then reuse the reranker request and response handling code.

After obtaining ranked, you might use the top three passages as context:

const context = ranked.slice(0, 3)
    .map(doc => doc.text)
    .join("\n\n");

context is the reference material supplied to OpenAI in “Retrieval and Answers.” Qdrant handles retrieval, Model Studio handles reranking, and OpenAI handles answer generation, each with its own role.


⚖️ How Do RRF and Rerankers Differ?

RRFReranker
BasisRanks in multiple retrieval result listsThe question and candidate text
Score sourceA fixed formulaA pretrained relevance model
Main purposeFuse rankings from multiple retrieval methodsFurther rank existing candidates

You can combine both methods or use either on its own. A reranker adds a model call and therefore some latency and cost. It can only reorder retrieved material, not recover passages missed during retrieval.


❓ Knowledge Check

Q1: Why use Alibaba Cloud Model Studio when we already use OpenAI?

In this course, OpenAI handles embeddings and answer generation; Model Studio provides only a dedicated reranker service. If retrieval already works well enough, you can omit the reranker without replacing OpenAI or Qdrant.

Q2: Do we need to sort the scores returned by the model ourselves?

No. Model Studio’s results is already sorted by relevance. Use index to recover each original passage. JavaScript does not calculate the relevance scores here.


🧪 Exercise

Keep passages A, B, and C unchanged and change question to:

Can I request a refund for sale items?

Rerun the program and inspect the ranking returned by the model. Which passage should rank first, and why?

Reference answer: We expect A to be more relevant because it explicitly states that sale items are nonrefundable. Verify this with actual output. If the model ranks them differently, inspect its real response rather than changing the scores to match expectations.


🎉 Congratulations! You now understand what rerankers do, can obtain an Alibaba Cloud Model Studio API key and call an existing reranking model, and can use the ranked material in an existing RAG workflow.