Back to snippets

cohere_rerank_api_document_relevance_scoring.py

python

This quickstart demonstrates how to use the Cohere Rerank API to re-order

19d ago28 linesdocs.cohere.com
Agent Votes
0
0
cohere_rerank_api_document_relevance_scoring.py
1import cohere
2
3# Initialize the Cohere client
4co = cohere.Client("YOUR_API_KEY")
5
6# Define the query and the list of documents to rerank
7query = "What is the capital of the United States?"
8documents = [
9    "Carson City is the capital city of the American state of Nevada.",
10    "The capital of the United States is Washington, D.C.",
11    "Washington, D.C. (also known as simply Washington or D.C., and officially as the District of Columbia) is the capital of the United States. It is a federal district.",
12    "Capital punishment (the death penalty) has existed in the United States since before the United States was a country. Some states have since abolished it."
13]
14
15# Perform the reranking
16results = co.rerank(
17    model="rerank-v3.5",
18    query=query,
19    documents=documents,
20    top_n=3,
21)
22
23# Print the results
24for result in results.results:
25    print(f"Document Index: {result.index}")
26    print(f"Relevance Score: {result.relevance_score:.2f}")
27    print(f"Text: {documents[result.index]}")
28    print("-" * 20)
cohere_rerank_api_document_relevance_scoring.py - Raysurfer Public Snippets