Rerank API for RAG: Add a Second Pass
How to add a rerank API for RAG after embedding search: request shape, top_n, billing units, Cohere, Qwen3 and Voyage rerank ids, Python code and a test plan.
By OceanToken Team

Editor's note: A common way for a RAG pipeline to answer badly is not a missing document. It retrieves the right passage and then buries it at position eleven, behind ten chunks that merely share vocabulary with the question. A reranker is the most direct fix for that specific failure, because it rescores each candidate against the question itself. It will not rescue a retriever that never found the passage, so measure which problem you have before you add one.
Short answer: A rerank API for RAG adds a second pass after embedding search. Retrieve a few dozen candidate chunks with embeddings, send the question and those chunks to POST /v1/rerank, and pass only the top few, by relevance_score, to your LLM. Start with cohere/rerank-4-fast and keep top_n small.
On OceanToken, the embedding call and the rerank call use the same key and the same base URL, https://api.oceantoken.ai/v1, so adding the second step is one more HTTP request, not a second vendor account. Every fact about endpoints and parameters below comes from our docs and model pages, read November 26, 2026. We have not run these models on your documents, so the quality comparison is left to the test plan near the end. Prices are on each model page; see the current rate on Rerank 4 Fast.
01 · How a rerank API for RAG fits into retrieval
Retrieval with a reranker is two different kinds of model doing two different jobs. An embedding model turns each chunk and each question into a vector on its own, so you can index millions of chunks ahead of time and search them in milliseconds. The catch is that the question and the chunk never meet inside the model. Similarity is a distance between two summaries that were computed separately.
A reranker reads the question and one candidate together and scores how well that candidate answers that question. Qwen's own write-up of its reranker describes exactly this cross-encoder design: it takes a text pair, such as a query and a candidate document, and returns a relevance score. Because it reads both at once, it can tell "refunds take 10 days" from "refund policy overview" when both sit close together in vector space. Because it reads both at once, it also cannot pre-compute anything, which is why you only show it a short list.

So the pipeline looks like this. Embed your chunks once and store the vectors. At question time, embed the question with the same model, pull the nearest few dozen chunks, send them with the question to the rerank endpoint, and keep the best handful for the prompt. Our docs describe search over your own documents in the same two steps: embeddings find passages close to the question, and rerank puts the best of them first.
02 · Step one: embedding recall with GTE-Large
The first stage is a normal embeddings call. POST /v1/embeddings follows OpenAI's Embeddings API, so client.embeddings.create() works once the base URL points at OceanToken. We use GTE-Large (thenlper/gte-large) in the examples because it is the model our earlier guide to calling the GTE-Large embedding API covers, but any embedding model in the catalog works the same way.
Three rules from our docs matter here, and breaking the first one fails silently. Use the same model for your documents and for the questions you search with; the docs say plainly that vectors from different models cannot be compared. If you ever switch embedding models, you re-embed the whole corpus, which is the trade-off our GTE-Large vs text-embedding-3-small comparison walks through. Second, batch: one request with a list of inputs is faster and simpler than one request per chunk. Third, embeddings are charged per input token, so re-embedding a large corpus is a cost you plan for, not a free retry.
GTE-Large has a short window. Its API reference and its model page list a 512-token context, while the one-line summary in our docs index says 1K. Plan around 512. That means chunking long documents before you embed them, and it is one more reason a reranker helps: small chunks retrieve precisely but carry little context, so you want the strongest few of them, not the first few. What happens to a chunk longer than the window, truncation or an error, is not stated in the reference, so check it on your own data before you rely on either.
03 · Step two: the rerank call, field by field
POST /v1/rerank follows Cohere's rerank request. Every rerank model on OceanToken that we checked lists the same four parameters in its API reference, which is what makes it easy to swap one for another.
| Field | Required | What it does |
|---|---|---|
model |
Yes | The rerank model id, such as cohere/rerank-4-fast |
query |
Yes | The text to rank against, usually the user's question |
documents |
Yes | A list of strings: your candidate chunks |
top_n |
No | Return only the best N results |
The response lists results by relevance, best first. Each result carries index and relevance_score, and Cohere models add meta.billed_units.search_units.
| Response field | Meaning |
|---|---|
results[].index |
The position of that document in the list you sent |
results[].relevance_score |
Higher means more relevant to the query |
meta.billed_units.search_units |
On Cohere models, the units this call was billed for |
The pitfall is index. The response does not echo your text back; it gives you a position in your own documents list. If you build that list from a dictionary, a set, or a database result whose order is not stable, you can map scores to the wrong chunks and never notice, because the answer will still look plausible. Keep the candidates in a plain list, keep their ids in a parallel list, and look up by index.
The other thing to read carefully is top_n. Leave it out and you get every document back in ranked order, which is useful while you are tuning. Set it in production so you send less over the wire and cannot accidentally stuff thirty chunks into the prompt.
04 · End-to-end Python: GTE-Large recall, then rerank
Here is the full loop: embed the corpus once, embed the question, take the nearest candidates, rerank them with cohere/rerank-4-fast, and build the prompt from the top results. It uses the OpenAI SDK for embeddings and chat, and a plain HTTP call for rerank, since the OpenAI SDK has no rerank method.
import os
import numpy as np
import requests
from openai import OpenAI
BASE = "https://api.oceantoken.ai/v1"
KEY = os.environ["OCEANTOKEN_API_KEY"]
client = OpenAI(base_url=BASE, api_key=KEY)
EMBED_MODEL = "thenlper/gte-large"
RERANK_MODEL = "cohere/rerank-4-fast"
chunks = [
"Refunds reach your card within 10 days of the return arriving.",
"Shipping takes three to five working days.",
"Gift cards cannot be exchanged for cash.",
# ... your chunks, each under GTE-Large's 512-token window
]
def embed(texts):
resp = client.embeddings.create(model=EMBED_MODEL, input=texts)
return np.array([d.embedding for d in resp.data])
doc_vecs = embed(chunks)
doc_vecs /= np.linalg.norm(doc_vecs, axis=1, keepdims=True)
def retrieve(question, k=40):
q = embed([question])[0]
q /= np.linalg.norm(q)
order = np.argsort(doc_vecs @ q)[::-1][:k]
return [chunks[i] for i in order]
def rerank(question, candidates, top_n=5):
r = requests.post(
f"{BASE}/rerank",
headers={"Authorization": f"Bearer {KEY}"},
json={"model": RERANK_MODEL, "query": question,
"documents": candidates, "top_n": top_n},
timeout=30,
)
r.raise_for_status()
body = r.json()
print("search units:", body.get("meta", {}).get("billed_units"))
return [(candidates[x["index"]], x["relevance_score"]) for x in body["results"]]
question = "How long do refunds take?"
top = rerank(question, retrieve(question))
context = "\n\n".join(text for text, _ in top)
answer = client.chat.completions.create(
model="qwen/qwen3.8-flash",
messages=[
{"role": "system", "content": "Answer only from the context."},
{"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"},
],
)
print(answer.choices[0].message.content)
The values k=40 and top_n=5 are starting points to tune, not results we measured. The shape of the idea is what matters: recall wide so the right chunk is somewhere in the list, then let the reranker cut it down hard. A production system would keep vectors in a vector database rather than a NumPy array, but the two API calls stay exactly as written. The final chat model, qwen/qwen3.8-flash here (rates on /qwen-api), is interchangeable too; any model id from the model catalog works in that last call.
05 · Cohere rerank API: what carries over
If you already call the Cohere rerank API, your request body carries over: model, query, documents and top_n are the same fields, and the response has the same results[].index and relevance_score. You change the URL to https://api.oceantoken.ai/v1/rerank, the key, and the model name to the publisher/model form, such as cohere/rerank-4-fast or cohere/rerank-4-pro.
What does not obviously carry over is everything beyond those four fields. Cohere's own API reference lists more options, including max_tokens_per_doc, which it says defaults to 4,096 and truncates longer documents, and relevant_spans. Our API references for the Cohere rerank models list only the four fields above. Our docs say that, for text models, a parameter a model does not support is dropped and the request still runs, so a success does not prove an option took effect. We have not seen that rule stated for rerank specifically, so treat any extra Cohere field as untested until you have compared results with and without it.
Billing works in Cohere's unit. Our docs say Cohere rerank models are charged per search unit, the number returned in meta.billed_units.search_units. Rather than guess how your batch sizes map to units, log that field for a day of real traffic; it tells you directly what each call cost in units. The price per unit is on the Rerank 4 Fast and Rerank 4 Pro model pages. Cohere's reference also recommends against sending more than 1,000 documents in a single request, which is far above what a RAG second pass needs anyway.
06 · Qwen3 reranker API
The Qwen3 reranker API on OceanToken is qwen/qwen3-reranker-8b on the same POST /v1/rerank endpoint, with the same four fields and the same response. Switching from a Cohere reranker to it is a one-line change to RERANK_MODEL in the code above.
Qwen's own announcement describes the Qwen3 reranker family as 0.6B, 4B and 8B models built on the Qwen3 foundation model, using the cross-encoder design described earlier and supporting user-defined instructions for different tasks. It says the Qwen3 embedding and reranking series as a whole supports more than 100 languages, including programming languages. Two of those points are worth acting on. If your corpus mixes languages, or your users ask in one language about documents written in another, this is a reranker to put in your test set. If your documents are code, the same applies.
The instruction point needs care. Our API reference for qwen/qwen3-reranker-8b has no separate instruction field; it lists only model, query, documents and top_n. Voyage's documentation for its reranker suggests putting instructions into the query text itself. Whether a prefixed instruction in query helps the Qwen reranker through this endpoint is something to measure, not assume. The billing unit differs from Cohere too: our docs say rerank models other than Cohere's are charged per token, and the rate is on the Qwen3 Reranker 8B model page.
07 · Four rerank model ids side by side
These are the four rerank ids we checked in our docs catalog and on oceantoken.ai on November 26, 2026. All four take the same request, so the table is about who made the model and how you pay, not about integration work.
| Model id | Publisher | Billing unit (our docs) | Model page in one line |
|---|---|---|---|
cohere/rerank-4-fast |
Cohere | Per search unit | Cohere's search model for relevance in search and RAG |
cohere/rerank-4-pro |
Cohere | Per search unit | Same description as Fast, the Pro tier |
qwen/qwen3-reranker-8b |
Qwen | Per token | Text reranker built on the Qwen3 architecture |
voyageai/rerank-2.5 |
Voyage AI | Per token | Reranker optimized for quality, with instruction-following |
The model pages carry the publishers' own marketing claims, including at least one accuracy percentage. We do not repeat those here, because a benchmark across someone else's datasets says little about your support tickets or contracts. Voyage's docs do state a limit worth knowing: for rerank-2.5, the query can be up to 8,000 tokens and the query plus any single document up to 32,000 tokens. The current rate for voyageai/rerank-2.5 is on its Voyage Rerank 2.5 model page.
08 · Rerank vs embeddings only: when you can skip it
Rerank vs embeddings only comes down to where your failures are. If the right chunk is usually in the top three by vector similarity already, a reranker adds a network call and a bill for little gain. If the right chunk is usually in the top thirty but rarely in the top three, a reranker is the most direct fix.
There are cases where we would not add one. A small, clean FAQ corpus where every question maps to one obvious answer rarely needs it. A pipeline where latency budgets are tight and answers are already good should not take on an extra round trip for theory's sake. And if you can fit the whole corpus into the model's context, retrieval itself may be optional; our piece on when to stuff a 1M context instead of using RAG covers that decision.
The case for adding one is strongest with large or messy corpora, short chunks like the ones GTE-Large's window forces, questions phrased differently from the documents, and multilingual content. Our GTE-Large vs BGE-M3 comparison for multilingual RAG mentions the rerank endpoint in passing; this guide is the full version of that step.
| Your situation | Embeddings only | Add a rerank pass |
|---|---|---|
| Right chunk usually in the top 3 already | Fine | Little to gain |
| Right chunk in the top 30, rarely the top 3 | Weak answers | Strong case |
| Right chunk often missing from the top 50 | Fix retrieval first | Will not help |
| Short chunks from a 512-token embedder | Context gets thin | Helps pick the best |
| Mixed-language documents and questions | Depends on embedder | Test a multilingual reranker |
| Strict latency budget, answers already good | Keep it simple | Skip for now |
09 · Choosing candidate count and top_n
Two numbers control the pipeline: how many candidates you retrieve and how many you keep. They pull in different directions. More candidates raise the chance the right chunk is in the list, but each one is more text for the reranker to read, which costs tokens or units and adds latency. A larger top_n gives the LLM more context, but also more distractors.

Our recommendation is to widen recall and tighten top_n. Start with a few dozen candidates and a handful kept. Then measure two things separately. Recall at your candidate count tells you whether the retriever is finding the right chunk at all. The position of the right chunk after reranking tells you whether the reranker is doing its job. If recall is low, raising top_n will not help; fix chunking or the embedding model. If recall is high but answers are still wrong, try cohere/rerank-4-pro or one of the other rerank ids on the same evaluation set before changing anything else.
How to test this on your workload
We have not run these models on your documents, so here is the plan we would follow. It needs no new tools, only the code above and a spreadsheet.
- Collect 50 to 100 real questions from logs or support tickets, and for each one mark the chunk id that actually answers it.
- Run embeddings only with your current model and record where the right chunk lands in the top 40.
- Add the rerank pass with
cohere/rerank-4-fast, notop_n, and record the right chunk's new position. - Repeat step 3 with
cohere/rerank-4-pro,qwen/qwen3-reranker-8bandvoyageai/rerank-2.5, changing only the model id. - Count questions where the right chunk moved into your intended
top_n, and questions where it fell out. - Log cost units from
meta.billed_unitson Cohere calls and the request cost in the console's Logs for the others. - Time each call from request to response on your real candidate sizes.
- Test the edges: a chunk longer than 512 tokens on GTE-Large, and an instruction prefixed to
queryon the Qwen and Voyage rerankers.
Our take: Add a reranker when your logs show the right chunk being retrieved but ranked too low; skip it when it is either already near the top or not retrieved at all. Start with cohere/rerank-4-fast, retrieve wide, keep few, and switch models only when your own evaluation set says another one moves more right answers into the top results.
Running it on OceanToken
Both stages of the pipeline run on one account. From our docs and model pages, as of November 26, 2026:
- One key, one base URL. Embeddings, rerank and the final chat call all go to
https://api.oceantoken.ai/v1with the same key, so the second pass is one more request in code you already have. - OpenAI-compatible embeddings, Cohere-shaped rerank. The OpenAI SDK handles embeddings and chat after changing the base URL; the rerank body is Cohere's shape, so existing Cohere code moves with a URL and model-name change.
- Swap rerankers by model id. All four rerank ids take the same four fields, so comparing them is a config change.
- Prepaid, with cost per request visible. You pay per use from a prepaid balance with no subscription, and the console's Logs show what each request cost.
Price: see the current rate on each model page: Rerank 4 Fast, Qwen3 Reranker 8B, and GTE-Large.
FAQ
What endpoint does a rerank call use? POST https://api.oceantoken.ai/v1/rerank, with model, query, documents and an optional top_n.
Does the rerank response include my document text? No. It returns index, the position in the list you sent, plus relevance_score, so keep your candidates in a stable list.
Can I use the OpenAI SDK for rerank? Not directly, since it has no rerank method. Use a plain HTTP request with the same key and base URL; embeddings and chat still use the SDK.
How is rerank billed? Cohere rerank models are billed per search unit, shown in meta.billed_units.search_units; other rerank models are billed per token. Rates are on each model page.
Do I need the same model for the reranker and the embeddings? No. The same-model rule applies to embeddings only: documents and questions must be embedded with one model. The reranker reads raw text, so any rerank id works with any embedder.
Which reranker should I start with? cohere/rerank-4-fast, then compare the others on your own questions before switching.
Sources
- OceanToken docs: Embeddings and rerank (checked 2026-11-26)
- OceanToken docs: Rerank 4 Fast API reference (checked 2026-11-26)
- OceanToken docs: GTE-Large API reference (JSON) (checked 2026-11-26)
- Cohere: Rerank API reference (checked 2026-11-26)
- Qwen: Qwen3 Embedding and Reranker announcement (checked 2026-11-26)
- Voyage AI: Rerankers documentation (checked 2026-11-26)
Get your OceanToken API key
- Create an OceanToken account and an API key.
- Copy the snippet below, paste your key, and run it.
- Check the current rate on the Rerank 4 Fast model page.
curl https://api.oceantoken.ai/v1/rerank \
-H "Authorization: Bearer $OCEANTOKEN_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model": "cohere/rerank-4-fast", "query": "How long do refunds take?", "documents": ["Shipping takes three to five working days.", "Refunds reach your card within 10 days of the return arriving."], "top_n": 1}'
More from the blog
Veo 3.1 Reference Images API Guide
How to send reference images to Veo 3.1 through the API: input_references vs first frame, which tiers take them, two-shot Python script and a consistency test.
LLM Function Calling API Across Models
Write one LLM function calling API loop that works across GPT, Claude, Gemini, Qwen, GLM and DeepSeek: tool_choice, streaming and the silent no-call trap.
LLM Image Input API: Screenshots and Scans
Send screenshots, photos and scans to a chat model with one LLM image input API: URL vs base64 data URL, per-model image limits, the 400 error and token costs.