Python: rerank candidate texts
ConfigureAPI_BASE_URL (including /v1), API_KEY, and a reranking model’s API_MODEL using the Python SDK guide. Save as rerank.py and run python rerank.py. It reuses the SDK’s generic HTTP client.post helper, not a nonexistent client.rerank method, and needs no additional vendor SDK.
The example explicitly sends top_n: 2 and return_documents: false, validates result indices and scores, sorts descending by score, and maps each index back to the original text. It uses application-owned text even if a channel still returns document.
Indices, scores, and result counts
results[].index is a zero-based position in this request’s documents array, not a rank or database ID. After filtering, chunking, or selecting candidates, retain the mapping from that final array to application IDs. Never use a result’s position in the score list to fetch the source text.
Higher scores usually indicate greater relevance within a query. They are not universally calibrated probabilities or directly comparable across models. The example requires finite scores without forcing a 0–1 range. Evaluate thresholds with your model and representative application data. Empty results produces an empty list rather than invented candidates. A model may still rank irrelevant candidates; apply application thresholds before answering.
Set top_n explicitly to a positive integer no larger than the candidate count. Some channels may ignore the requested count. The example locally keeps the first two results, which does not reduce documents already processed upstream. top_n controls returned results, not knowledge-base retrieval size.
Channel differences
The query and documents are sent to the configured gateway and upstream.
return_documents: false does not prevent uploading source text. For structured documents, serialize stable text in the application and keep separate application IDs. Bound candidate counts and text lengths before tuning reranking parameters; do not send the entire corpus at once.
Combine with Embeddings
The flow is: Embeddings for a vector index → application candidate retrieval → Rerank → selected source text to a chat model. Rerank can also operate on candidates from keyword search. For errors, check model capability, nonempty query/documents, length, and optional parameters. Even on HTTP 200, validate theresults shape, duplicate/out-of-range indices, and invalid scores. This example exits on malformed output and disables automatic retries.
Score interpretation: Cohere Rerank best practices. That provider’s request limits are not universal channel limits.
Next: combine retrieval, optional reranking, and cited answers in the RAG guide.
简体中文