Rerank retrieved passages with Cohere Rerank and map results back by index
Send retrieved passages and the query to /v2/rerank, map each returned index back to the original text, then check score order, top_n and the document-count limit. No API was called here.
Task and deliverable · Inputs and environment · Mechanism and parameters
At a glance
Cohere's Rerank endpoint takes a query and a list of texts and returns them ordered by semantic relevance. The official quickstart says it adds a semantic boost to any keyword or vector search system. The sample output carries only an index and a relevance_score (document=None), so the text has to be looked up from your own list. This guide follows the quickstart's four company-policy passages through one task: rerank, map back by index, check score order and top_n, check the document-count limit, and see how structured records become YAML strings. No Cohere API was called and no key was created in this batch. Code marked as this site's illustration was written by the editors and only rehearsed locally with fake data.
From candidate list to index-mapped check table
Fix the candidates and the query
Collect the passages from your retrieval step into a string list
documentsand write onequery. The official quickstart uses Rerank after a keyword or vector search; its example is four short company-policy passages and the question "Are there fitness-related perks?". Results point back by position, so do not add, remove or reorder anything after sending. If you need business IDs, keep a separate ID list of the same length asdocuments(editorial advice).Send the /v2/rerank request
The endpoint is
POST https://api.cohere.com/v2/rerankwith Bearer authentication.model,queryanddocumentsare required;top_nis optional, and without it all results come back. The quickstart uses the Python SDK: create a client withcohere.ClientV2, then callco.rerank(model="rerank-v5.0-pro", query=query, documents=documents, top_n=2).Read index and score
The overview says
index=0is the first document, so this guide treatsindexas a position in thedocumentsyou passed (editorial reading). The reference sample response gives every result anindexand arelevance_score. Best practices says scores are normalized to[0, 1], with values near 1 meaning high relevance. The official sample output isindex=2 relevance_score=0.115670934andindex=1 relevance_score=0.01729751withdocument=None, so the text has to come from your own list.Look the text up by index
For each result, take
documents[result.index]to get the reranked text order. In the example, first place is index 2, "Health and Wellness Benefits", which mentions gym memberships and yoga classes; second place is index 1, the remote-work policy. Indexes 0 and 3 are absent becausetop_n=2keeps only two results.Check, then hand over
The check table answers five questions: every
indexis in range and unique, scores sit in[0, 1]and do not rise, the number of results equalstop_n, structured records went in as YAML strings with key order intact, and the document count stayed within the limit. The token limit has no executable check here and is marked not done. Hand the table downstream only when the five checks pass; if any fails, keep the raw response and mark the batch undelivered (editorial rule).
Task and deliverable
The task: you already have a user question and a few candidate passages from keyword or vector search. You want them reordered by semantic relevance, the top N kept, and a reliable way to tell which original candidate each result refers to. The deliverable is a check table listing rank, index, relevance_score and the start of each text. The official quickstart data is enough for it: four short company-policy passages, the question "Are there fitness-related perks?", and top_n=2.
Completion has five conditions: each index in results.results matches the position in the original documents; relevance_score runs from high to low; top_n takes effect; structured documents are passed as YAML strings with key order kept; the document count stays within the limit. The first three can be checked from the response itself, the fourth by reading the code that builds the request, and the fifth against the official limits table. The token limit is a sixth item that is not done: the official pages give no token-counting method, and the check script here does not check tokens.
Inputs and environment
- A Cohere API key. A comment in the quickstart code says you can get a free key on the dashboard's API keys page, and the rate-limits page splits keys into evaluation (trial) keys, which are free but limited in usage, and paid production keys. This guide created no account and used no key.
- Python and the official SDK:
pip install -U cohere. The quickstart usesimport cohereandcohere.ClientV2("COHERE_API_KEY"), where the string is a placeholder to replace with a real key before running; this site's illustrative cURL command reads theCOHERE_API_KEYenvironment variable (editorial change). - The candidate texts as a list of strings. The allowed count is 1 to 10,000 (see the limits table below), and the reference recommends no more than 1,000 per request.
- A model name. The quickstart and reference examples both use
rerank-v5.0-pro. The models page also listsrerank-v5.0-fast,rerank-v4.0-proand others; for v5, pro favors quality and fast favors low latency and high throughput. The pages read for this guide give no per-model prices. - PyYAML, only if your candidates are structured records. The overview example has
import yaml, but the page gives no install command, so you install it yourself (editorial addition).
Mechanism and parameters
Where Rerank sits: the overview puts it plainly. Given a query and a list of documents, Rerank orders the documents from most to least relevant. The "Best for" section of the models page says it improves relevance on top of existing keyword, vector or hybrid search with no re-indexing. So it does not find candidates; it only reorders them and scores each one.
Response shape: the reference's 200 response has results (an ordered list), id and meta; the properties of each result item are collapsed in the fetched page, so this guide does not assert which fields are required. In the official sample responses every result has an index and a relevance_score; relevant_spans appears only when the request enabled it and the model found spans. The quickstart's printed object shows document=None, so you fetch the text from your own list with index.
index starts at 0: the overview says that, as in Python, index=0 is the first document. The reference sample response gives every result an index, but the fetched page does not expand its field definition, so this guide relies on the overview and treats index as a position in the list you passed (editorial reading).
Reading relevance_score: best practices says scores are normalized to [0, 1], near 1 meaning high relevance and near 0 low, and warns against inferring ratios from the numbers; for example you cannot assume a document scoring 0.9109375 is twice as relevant as one scoring 0.04421997. The same page says the score depends on the query and can be higher or lower depending on the query and passages sent. In the official sample the top passage scores only 0.115670934; that is an observation about the sample output, not a rule. To set a relevant/not-relevant cutoff, best practices suggests picking 30 to 50 representative queries, pairing each with a borderline-relevant document, running them all and using the average score as a reference.
top_n and order: top_n limits how many results come back, and without it all do. The pages do not say what happens when top_n exceeds the number of documents, or which of two equal scores comes first. The reference calls the results an ordered list and the overview says most to least relevant; this guide turns that into a non-increasing-scores check, which is an editorial check built on those statements.
Fields and requirements
| Field | What the official pages say | How this task uses it |
|---|---|---|
model | Required string, for example rerank-v5.0-pro | Use the quickstart's model name; a misspelled name is a common thing to check (editorial), and the official error list gives only the 404 status name |
query | Required string, the search query | Holds the user question; for v5 it shares the 32,768-token context with the document |
documents | Required list of strings; no more than 1,000 per request recommended; long documents truncated to max_tokens_per_doc; structured data best formatted as YAML strings | Holds the candidate list; no adding, removing or reordering after sending |
top_n | Optional integer limiting the number of results; all results if omitted | Set to 2 in the example; check that 2 results return |
max_tokens_per_doc | Optional, default 4096, long documents truncated to this value | Watch it with long candidates; unchanged here |
relevant_spans | Optional; supported only for Rerank v5 and newer models | Not enabled in this task |
priority | Optional integer, default 0; lower numbers mean higher priority, and under load higher-priority requests are handled first and are least likely to be dropped | Not set in this task |
results[].index | Present in every result of the official sample responses; the field definition is collapsed in the fetched page | Used to look up text and business IDs; treated as a documents position per the overview (editorial reading) |
results[].relevance_score | Present in every result of the official sample responses; best practices says it is normalized to [0, 1] and not a linear proportion | Used for ordering and for a threshold you calibrate yourself |
meta.billed_units | Optional; the overview sample shows search_units=1.0, the reference sample shows input_tokens=192 | Not treated as a bill; the pages do not say which applies to v5 |
Steps to complete the task
Install dependencies and prepare the key: run pip install -U cohere. The official Python code writes the key as the placeholder string "COHERE_API_KEY", which you replace yourself before running; this site's illustrative cURL command reads the COHERE_API_KEY environment variable instead. Check: python -c "import cohere" raises no error (an editorial check). Keep the key out of files you commit (editorial advice).
Fix the candidate list: put the retrieval results into documents and keep a doc_ids list of the same length. Check: len(documents) == len(doc_ids) and the count is between 1 and 10,000. Above 1,000, ask whether you really need one request, because the reference recommends staying below that. Token limit: the official pages give no token-counting method, so this guide does not check it and the item is not done; the editorial advice is to keep candidates short.
Send the request: co.rerank(model="rerank-v5.0-pro", query=query, documents=documents, top_n=2). Check: the call raises nothing, results.results is a list, and each print(result) line looks like document=None index=2 relevance_score=0.115670934.
Look up the text: for each result in results.results, take the text from documents[result.index] and the business ID from doc_ids[result.index]. Check: every index is an integer inside range(len(documents)) and none repeats. The list used here must be the one you sent.
Check order and count: collect all relevance_score values and confirm they equal their own descending sort and lie within [0, 1]; confirm the number of results equals top_n (two of four in this example). Both are editorial checks, since the pages only say the results are an ordered list.
Read the scores: use them for ordering and for a threshold you calibrate yourself. Check: do not compare 0.115670934 with results from another query. For a relevant/not-relevant call, calibrate first with best practices' 30-to-50-query method.
Write the check table and choose the exit (editorial rule): one row per result with rank, index, business ID, score and the start of the text, then read the first result and confirm it actually answers the question. Deliver only if everything passes; otherwise keep the raw response and request parameters, mark the batch undelivered, and pass nothing half-finished downstream.
Worked example
The example uses the official quickstart data directly: four company-policy passages, the question "Are there fitness-related perks?" and top_n=2. The first bash block holds the install and environment lines: pip install -U cohere comes from the quickstart, while pip install pyyaml and the export line are editorial additions. None of it was run.
pip install -U cohere
pip install pyyaml
export COHERE_API_KEY="<your-cohere-api-key>"
The Python block is the quickstart's own code (Cohere Platform version), with the page's three snippets joined in order: create the client, define documents, rerank and print. The quickstart writes the key as the string "COHERE_API_KEY", which is a placeholder to replace with a real key before running; it was not replaced here and nothing was run.
import cohere
co = cohere.ClientV2(
"COHERE_API_KEY"
) # Get your free API key here: https://dashboard.cohere.com/api-keys
documents = [
"Reimbursing Travel Expenses: Easily manage your travel expenses by submitting them through our finance tool. Approvals are prompt and straightforward.",
"Working from Abroad: Working remotely from another country is possible. Simply coordinate with your manager and ensure your availability during core hours.",
"Health and Wellness Benefits: We care about your well-being and offer gym memberships, on-site yoga classes, and comprehensive health insurance.",
"Performance Reviews Frequency: We conduct informal check-ins every quarter and formal performance reviews twice a year.",
]
# Add the user query
query = "Are there fitness-related perks?"
# Rerank the documents
results = co.rerank(
model="rerank-v5.0-pro", query=query, documents=documents, top_n=2
)
for result in results.results:
print(result)
The official sample output is two lines, the two results for top_n=2.
document=None index=2 relevance_score=0.115670934
document=None index=1 relevance_score=0.01729751
Mapping the output back to the original order gives the table below. Only the scores for index 2 and index 1 come from the official sample output; index 0 and 3 do not appear in the results, and the sample output gives no scores for them.
| Original index | Start of the text | Rerank position | relevance_score |
|---|---|---|---|
| 0 | Reimbursing Travel Expenses: Easily manage your travel expenses… | Not returned | Not given in the sample output |
| 1 | Working from Abroad: Working remotely from another country is possible… | 2 | 0.01729751 |
| 2 | Health and Wellness Benefits: We care about your well-being and offer gym memberships… | 1 | 0.115670934 |
| 3 | Performance Reviews Frequency: We conduct informal check-ins every quarter… | Not returned | Not given in the sample output |
First place is the third item of the original list (index 2). It mentions gym memberships, yoga classes and health insurance, which matches "fitness-related perks". Second place is index 1, the remote-work policy, with a score of 0.01729751 against 0.115670934 for the first. The pages do not explain why it ranks ahead of indexes 0 and 3, and this guide does not guess.
Below is a check script written for this site. Run it after the official code above, since it reuses documents and results, and it brings its own doc_ids list of the same length as documents (the example IDs are invented here). The 1-to-1,000 assertion in the script is this site's own limit, not an API limit (see the limits table for the official ones). It asserts the document count, the result count, that each index is valid and unique, and that scores are in range and descending, then prints the check table with business IDs in results.results order. It does not check tokens. The code was only rehearsed locally with fake data and never connected to Cohere.
doc_ids = ["fin-001", "hr-014", "hr-022", "hr-031"] # same length and order as documents
assert len(documents) == len(doc_ids), "doc_ids must match documents"
assert 1 <= len(documents) <= 1000, "outside this site's own 1-1,000 limit" # editorial limit, not an API limit
rows = results.results
assert len(rows) == 2, "top_n=2 should return 2 results"
indexes = [row.index for row in rows]
assert len(set(indexes)) == len(indexes), "duplicate index"
assert all(0 <= i < len(documents) for i in indexes), "index outside documents"
scores = [row.relevance_score for row in rows]
assert all(0 <= s <= 1 for s in scores), "score outside [0, 1]"
assert scores == sorted(scores, reverse=True), "scores are not descending"
print("rank index doc_id score document")
for rank, row in enumerate(rows, start=1):
print(f"{rank:<5} {row.index:<6} {doc_ids[row.index]:<8} {row.relevance_score:<12} {documents[row.index][:40]}")
The expected output is below. It comes from plugging the two official sample values into the script and is not a real response. Passing assertions only show that the response has the shape described above; they say nothing about ranking quality, so read the first passage to judge whether it answers the question.
rank index doc_id score document
1 2 hr-022 0.115670934 Health and Wellness Benefits: We care ab
2 1 hr-014 0.01729751 Working from Abroad: Working remotely fr
If you prefer not to use the SDK, you can send the HTTP request directly. The block below uses the endpoint and Bearer authentication from the reference, with the same body as the Python call, and reads the key from the COHERE_API_KEY environment variable (editorial change). It passed a syntax check and was not sent.
curl --request POST \
--url https://api.cohere.com/v2/rerank \
--header 'accept: application/json' \
--header 'content-type: application/json' \
--header "Authorization: Bearer $COHERE_API_KEY" \
--data '{
"model": "rerank-v5.0-pro",
"query": "Are there fitness-related perks?",
"documents": [
"Reimbursing Travel Expenses: Easily manage your travel expenses by submitting them through our finance tool. Approvals are prompt and straightforward.",
"Working from Abroad: Working remotely from another country is possible. Simply coordinate with your manager and ensure your availability during core hours.",
"Health and Wellness Benefits: We care about your well-being and offer gym memberships, on-site yoga classes, and comprehensive health insurance.",
"Performance Reviews Frequency: We conduct informal check-ins every quarter and formal performance reviews twice a year."
],
"top_n": 2
}'
When candidates are structured records
If candidates are records with fields rather than plain text, the reference and best practices both recommend formatting them as YAML strings before putting them in documents. Best practices explains why key order matters: long documents are truncated, so keep the order of keys when building the YAML string, which in Python means yaml.dump(doc, sort_keys=False).
Below is the overview's approach applied to two records invented for this guide, with business IDs kept separately in doc_ids. PyYAML's yaml.dump sorts keys by default, so without sort_keys=False the Content field would come before Title. That is PyYAML's behavior rather than something the Cohere pages say; it was confirmed by running PyYAML locally, with no call to Cohere.
import yaml
records = [
{"Title": "Gym memberships", "Content": "On-site yoga classes and gym memberships."},
{"Title": "Performance reviews", "Content": "Formal reviews happen twice a year."},
]
doc_ids = ["policy-017", "policy-021"]
yaml_docs = [yaml.dump(record, sort_keys=False) for record in records]
print(yaml_docs[0], end="")
Title: Gym memberships
Content: On-site yoga classes and gym memberships.
Then pass documents=yaml_docs to co.rerank(...). Everything else stays the same. The SDK's results is a response object whose list lives in its results attribute, so the lookup is results.results[i].index, which points to the same position in yaml_docs, records and doc_ids. To use the check script above on this branch, replace its documents with yaml_docs and its doc_ids with the list from this section.
Limits and defaults
| Item | Official value | What the same pages add or disagree on |
|---|---|---|
| Documents per request | Minimum 1, maximum 10,000; v5 returns an error above that | The reference also recommends no more than 1,000 per request for best results |
max_tokens_per_doc (v5) | Default 4096, minimum 1, no maximum given | Long v5 documents are truncated to this value |
| Context length for v5 and v4 | 32,768 tokens, query and document combined | The models page gives 32,768 for v5 pro and fast, and 4096 for v3.5 and v3.0 |
| Tokens per query | The limits table gives a maximum of 2048 | The v4 paragraph on the same page lets the query take up to half the context, and the v5 paragraph says only that the 32,768 is shared; the three statements differ |
| Rerank rate limit | Trial key 10 requests per minute, production key 1,000 per minute | Rate-limits page |
| Trial key monthly calls | 1,000 API calls a month | The page does not say whether this is counted per endpoint or give a separate Rerank quota |
The models page notes that a document's tokens plus the query's tokens count together toward the per-document context limit, and says a document that exceeds it is chunked automatically and processed in several inferences. Best practices says that for v5 long documents are truncated to max_tokens_per_doc. The official pages give no token-counting method, so the check script does not check tokens and that item is not done. The two pages describe long documents differently, and this guide does not decide which one applies to v5 today. The editorial advice is to cut candidates short enough that you never rely on truncation or chunking.
Checking results and failure exits
- Success (editorial rule): the request raises nothing; every
indexis between 0 andlen(documents)-1and none repeats; scores are within[0, 1]and non-increasing; the result count equalstop_n; the text and business IDs you look up make sense. Deliver the check table only when all five hold. - 401 or 403: the official reference error list gives only the names Unauthorized Error and Forbidden Error, and the fetched page states no cause. Editorial troubleshooting advice: check that the key was read correctly and has permission, and do not print the key while debugging.
- 400 or 422: the official error list gives only the names Bad Request Error and Unprocessable Entity Error, with no cause. Editorial troubleshooting advice: confirm
model,queryanddocumentsare present anddocumentsis a list of strings. - 404: the official error list gives only the name Not Found Error. Editorial troubleshooting advice: check the model name spelling and the endpoint address.
- 429: the reference error list gives only the name Too Many Requests Error. The trial key's Rerank limit is 10 per minute, so several batches in a row can hit it easily. The pages give no retry interval or backoff, so this guide sets none; it only suggests slowing down and keeping the failed batches.
- More than 10,000 documents: best practices says v5 returns an error but gives no status code or message, so do not depend on a specific error text. If you must split into batches, note that the pages do not say whether scores from different batches can be merged and sorted together, and best practices says a score depends on the query and passages sent. The editorial advice is to narrow candidates to 1,000 or fewer during retrieval rather than batch.
- Out-of-range or repeated
index: per the overview,indexrefers to a position in the list you passed, so a violation most likely means the lookup list is not the one you sent, or the response is abnormal. Stop using that batch and keep the raw response (editorial judgment). - Rising scores, or a result count that differs from
top_n: the official pages call the results an ordered list, so do not re-sort and deliver; keep the raw response and mark the batch undelivered (editorial rule). - Stop and fall back (editorial advice): if the same batch fails the check twice, shrink to fewer candidates (for example 20) and shorter texts to confirm the pipeline, then scale up again. If it still fails, turn reranking off, keep the retrieval order and label the results as not reranked.
Limits of this guide
- Price: the pages read for this guide give no Rerank price. The overview sample's
meta.billed_unitsissearch_units=1.0and the reference sample's isinput_tokens=192; the two pages show different billing units and do not say which one applies torerank-v5.0-pro. Take prices from the official pricing page, which this guide did not read. - Returned text: in the reference sample response each result carries
indexandrelevance_score(and may also carryrelevant_spans), and the pages do not explain thedocument=Nonein the quickstart's printout. This guide therefore looks the text up itself and did not test whether any parameter makes the API return it. - Score thresholds: the pages give only a method for calibrating your own and no universal threshold. The models page mentions calibrated relevance scores for Rerank 5 but gives no number you could apply directly.
- Languages and input: the overview says Rerank models cover 100+ languages; the models page says Rerank 5 takes text only and does not support instructions that change how relevance is judged, and lists Chinese among its focus languages.
relevant_spans: supported only for v5 and newer models, it returns the spans of each document that contributed to its rank, and the models page says it gives character offsets. This guide does not go into it.- Token-limit check: not done. The official pages give no token-counting method, and the check script only checks the document count.
- Other deployments: the quickstart page lists deployment tabs such as private deployment, Bedrock, SageMaker and Azure AI, but their code was not fetched; this guide covers only the Cohere Platform.
In this batch nothing was called, installed or run: not the Cohere API, not the cohere SDK, not any Cohere request in this guide. No account or key was created, and no key quota or billing was checked. Fields, limits and sample output come from Cohere's quickstart, overview, reference, best-practices, models and rate-limits pages, listed in the sources. The scripts marked as this site's illustration were only rehearsed locally with fake data, and the expected output comes from plugging in the official sample values; it is not a real response. Actual scores, latency, error text and throttling behavior need one real response from your own key to judge.
Article sources
Original editorial content; official descriptions and checking suggestions are distinguished.