pythonintermediate

Cohere Reranker for RAG Precision

Improve RAG retrieval quality by reranking candidate documents with Cohere's rerank API.

python
import cohere

co = cohere.Client('YOUR_COHERE_API_KEY')

query = 'How do I handle database transactions in Python?'

documents = [
    'SQLAlchemy supports ACID transactions via session commit/rollback.',
    'Python is a general-purpose programming language.',
    'Use context managers to ensure rollback on errors.',
    'PostgreSQL supports complex SQL queries.',
    'The with statement handles resource cleanup automatically.',
]

results = co.rerank(model='rerank-english-v3.0', query=query, documents=documents, top_n=3)

for r in results.results:
    print(f'Score: {r.relevance_score:.3f} | {documents[r.index]}')

Use Cases

  • RAG precision improvement
  • search ranking
  • document relevance

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.