Cohere로 시맨틱 검색하기

Cohere로 시맨틱 검색하기

이 페이지는 임베딩을 사용해 시맨틱 검색을 구현하는 방법을 설명해요. 키워드 일치에만 의존하지 않고 쿼리의 의도와 맥락적 의미를 이해하는 검색 애플리케이션을 함께 만들어 볼게요.

출처: 문서

본문

시맨틱 검색은 키워드 일치에만 의존하지 않고 사용자 검색 쿼리의 의도와 맥락적 의미를 이해하는 검색 기법이에요. 이를 통해 시맨틱 검색은 찾고자 하는 의도를 진정으로 이해할 수 있고, 훨씬 더 관련성 높은 결과 집합을 만들어내요. 따라서 단어와 구의 시맨틱 의미를 포착하는 텍스트의 벡터 표현인 임베딩이 필요해요.

Cohere에서는 Embed 엔드포인트를 사용해 임베딩을 쉽게 만들 수 있어요.

이 튜토리얼에서는 시맨틱 검색 애플리케이션을 함께 구축해 볼게요. 이 애플리케이션은 사용자가 쿼리와 관련된 문서를 찾도록 도와줘요. 쿼리를 입력으로 받아 쿼리와의 관련성 순으로 정렬된 문서 목록을 반환해요.

이 튜토리얼은 코드 불필요한 Cohere 소개인 "Build Things with Cohere"에서 각색했어요. 환경을 설정하려면 다음 중 하나를 완료하세요:

임베딩 만들기 (Create Embeddings)

Cohere의 Embed 엔드포인트는 텍스트에서 임베딩을 만들어요. SDK의 embed 메서드를 사용해 임베딩을 만들 수 있어요.

이 예제에서는 여행 문서 데이터베이스를 쿼리해 주어진 쿼리에 가장 관련성 높은 문서를 찾아볼게요.

제목과 설명이 있는 여행 문서를 사용할게요:

PYTHON

import cohere

co = cohere.ClientV2(api_key="YOUR_COHERE_API_KEY")

# Define the documents that form our database
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.",
    },
]

# Print the documents
  for d in docs: print(d)

먼저 검색 쿼리의 임베딩을 얻어요. 그다음 쿼리 임베딩과 비교할 문서들의 임베딩을 얻어요.

참고로 검색 프로세스를 최적화하기 위해 데이터베이스 검색을 반환 결과와 별도로 수행할 수 있어요.

1단계: 쿼리 임베딩하기 (Embed the Query)

embed 엔드포인트를 사용해 사용자의 쿼리를 임베딩할게요.

PYTHON

import cohere

co = cohere.ClientV2(api_key="YOUR_COHERE_API_KEY")

# Create the search query
query = "How do I get reimbursed for a trip?"

# Get the embedding for the query
query_emb = co.embed(
    model="embed-v4.0",
    texts=[query],
    input_type="search_query",
    embedding_types=["float"],
).embeddings.float_[0]

2단계: 문서 임베딩하기 (Embed the documents)

문서들도 임베딩할게요.

PYTHON


import cohere

co = cohere.ClientV2(api_key="YOUR_COHERE_API_KEY")

# Get the documents
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.",
    },
]

# Get the embedding for the documents
doc_emb = co.embed(
    model="embed-v4.0",
    texts=[doc["text"] for doc in docs],  # Get only the texts from the docs
    input_type="search_document",
    embedding_types=["float"],
).embeddings.float_

3단계: 가장 유사한 문서 찾기

이제 쿼리와 문서 사이의 거리를 계산하고, 거리가 가장 작은 문서들을 찾을 수 있어요.

cosine_similarity와 dot product는 흔히 사용되는 두 가지 측정 방식이에요. 여기서는 DotProduct를 사용하고 상위 n개의 가장 유사한 문서의 인덱스를 얻을게요.

PYTHON


# Find out the documents that are most similar to the query
def compute_documents_scores(query_emb, doc_emb):
    scores = []
    for i, doc in enumerate(docs):
        score = 0
        for j in range(len(doc_emb[i])):
            score += query_emb[j] * doc_emb[i][j]
        scores.append(score)
    return scores

scores = compute_documents_scores(query_emb, doc_emb)

# Print the scores
for idx, score in enumerate(scores):
    print(f"{idx}: {score}")

for idx in sorted(range(len(scores)), key=lambda i: scores[i], reverse=True):
    print(docs[idx]["title"], scores[idx])    

다음 단계 (Next Steps)

임베딩과 시맨틱 검색을 갖추었으니 이제 애플리케이션 구축을 계속할 수 있어요. 검색 결과를 더 잘 이해하고 싶다면 reranking 튜토리얼을 확인해 보세요.

더 알아보기 (Learn more)