Reranking with a Reranker
🎯 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:
| Label | Material | Text |
|---|---|---|
| A | Refund policy | You can request a refund within 7 days of purchase. Sale items are nonrefundable. |
| B | Refund requirements | Refund requests require an order number and proof of purchase. |
| C | Shipping instructions | Standard 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 question | Candidate material | What does the model assess? |
|---|---|---|
| What documents do I need to request a refund? | A: Refund window and restrictions | Does this answer what documents are required? |
| What documents do I need to request a refund? | B: Order number and proof of purchase | Does this answer what documents are required? |
| What documents do I need to request a refund? | C: Shipping time | Does 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.
🧰 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:
- Register or sign in to an Alibaba Cloud account, complete identity verification, and activate Model Studio as prompted.
- Switch the region to China (Beijing).
- Open the API Key page, create a key in the default workspace, and copy it somewhere secure.
- Open workspace management and copy the default workspace’s Workspace ID.
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:
| Parameter | Purpose |
|---|---|
model | Selects Alibaba Cloud Model Studio’s Qwen text reranking model |
query | The current user question |
documents | The text of passages A, B, and C |
top_n | How 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 }
]
}
You only need to understand two fields:
index: The passage’s position in the originaldocsarray. For example,index: 1identifies 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?
| RRF | Reranker | |
|---|---|---|
| Basis | Ranks in multiple retrieval result lists | The question and candidate text |
| Score source | A fixed formula | A pretrained relevance model |
| Main purpose | Fuse rankings from multiple retrieval methods | Further 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.
RRF Rank Fusion
Use a complete refund example to understand the limits of keyword priority, combine two retrieval rankings with RRF, and learn the role of reranking.
MCP Overview
Understand the problem MCP solves, its communication architecture and tool call flow, and how it relates to function calling and REST APIs.
