Cohere로 Reranking하기
Cohere로 Reranking하기
이 페이지는 reranking을 사용해 검색 결과를 정리하는 방법을 설명해요. 기본 검색이 반환한 후보 결과 목록을 쿼리와 비교해 가장 관련성 높은 순서로 재정렬해 볼게요.
출처: 문서
본문
이 튜토리얼에서는 reranking을 사용해 검색 결과를 정리하는 방법을 보여줄게요.
Reranking은 다른 검색 메커니즘이 반환한 초기 결과 집합을 재정렬해 쿼리에 가장 관련성 높은 결과를 우선시하는 과정이에요. 즉, rerank 엔진은 후보 결과 목록을 가져와 쿼리와 대조해 평가한 다음, 가장 관련성 높은 결과를 우선하도록 재정렬된 동일한 목록을 반환해요.
이 튜토리얼은 코드 불필요한 Cohere 소개인 "Build Things with Cohere"에서 각색했어요. 환경을 설정하려면 다음 중 하나를 완료하세요:
-
튜토리얼 시리즈의 Part 1: 설치 및 설정을 완료해요.
-
그리고/또는 SDK 설치와 키 발급에 대한 빠른 안내가 있는 Quickstart를 확인해요.
Reranking 예시 (A Reranking Example)
아래 예시는 벡터 데이터베이스를 사용해 관련 문서를 검색하지만, 더 나은 결과를 얻기 위해 rerank 엔드포인트를 사용해요.
Cohere SDK의 rerank 엔드포인트를 사용해 간단한 reranking 애플리케이션을 만드는 단계를 함께 살펴볼게요.
시맨틱 검색 튜토리얼과 같은 여행 문서를 사용하고, 그 튜토리얼의 {query}도 사용할게요.
먼저 문서의 임베딩을 얻고 주어진 쿼리와 유사한 문서를 찾는 것으로 시작해요 (cosine similarity 또는 dot product 사용).
PYTHON
import cohere
co = cohere.ClientV2(api_key="YOUR_COHERE_API_KEY")
## Step 1: Get the embeddings and find the top similar
# 1.A. Set up the documents and the search query
docs = [
{
"title": "Travel",
"text": "Reimbursing travel expenses: Easily manage your travel expenses by submitting them through our expenses tool. Approvals are prompt and straightforward.",
},
{
"title": "Travel",
"text": "Working remotely from abroad: Working remotely from another country is possible. Simply coordinate with your manager and ensure your availability during core hours.",
},
{
"title": "Health",
"text": "Financial wellness resources: We offer financial planning tools and counseling to support your financial health.",
},
{
"title": "Health",
"text": "Health and wellness benefits: We care about your well-being and offer gym memberships, on-site yoga classes, and comprehensive health insurance.",
},
{
"title": "Product",
"text": "Product roadmap: We build product features based on user research and validate that we build the right thing.",
},
{
"title": "Product",
"text": "Product strategy: We discuss product strategy in quarterly reviews that involve our product, engineering, and design teams.",
},
]
query = "How do I get reimbursed for a trip?"
# 1.B. Embed the documents
doc_emb = co.embed(
model="embed-v4.0",
texts=[doc["text"] for doc in docs],
input_type="search_document",
embedding_types=["float"],
).embeddings.float_
# 1.C. Embed the query
query_emb = co.embed(
model="embed-v4.0",
texts=[query],
input_type="search_query",
embedding_types=["float"],
).embeddings.float_[0]
# 1.D. Find the documents most similar to the query (cosine similarity)
def cosine_similarity(v1, v2):
dot_product = sum(a * b for a, b in zip(v1, v2))
norm1 = sum(a * a for a in v1) ** 0.5
norm2 = sum(a * a for a in v2) ** 0.5
return dot_product / (norm1 * norm2)
# Compute similarities
similarities = [cosine_similarity(query_emb, doc) for doc in doc_emb]
# Get top 3 indices by similarity
top_3_indices = sorted(range(len(similarities)), key=lambda i: similarities[i], reverse=True)[:3]
# Show the top documents
print("Top 3 documents by similarity:")
for idx in top_3_indices:
print(docs[idx]["title"], docs[idx]["text"])
2단계: 결과 Rerank하기
Reranking은 다른 검색 메커니즘이 반환한 초기 결과 집합을 재정렬해 쿼리에 가장 관련성 높은 결과를 우선시하는 과정이에요. reranking 엔진은 후보 결과를 입력으로 받아 쿼리와 대조해 평가한 다음 재정렬된 결과를 반환해요.
이제 기본 검색이 반환한 상위 3개 문서를 rerank할게요.
PYTHON
## Step 2: Rerank the results
reranked = co.rerank(
model="rerank-v4.0",
query=query,
documents=docs,
top_n=3,
rank_fields=["text"],
return_documents=False,
)
# Print the results
for i, r in enumerate(reranked.results):
print(f"{i+1}. {docs[r.index][\"title\"]}: {r.relevance_score}")
이 rerank 호출의 출력은 다음과 같아요:
1. Travel: 0.68
2. Product: 0.34
3. Health: 0.33
다음 단계 (Next Steps)
검색과 생성을 결합하는 방법을 보려면 RAG 튜토리얼을 살펴보세요: RAG with Cohere.