HuggingFaceTEIRanker
HuggingFaceTEIRanker
Text Embeddings Inference (TEI) API 엔드포인트를 사용해 쿼리에 대한 유사성에 따라 문서를 순위 매기는 구성 요소예요.
출처: 문서
본문
HuggingFaceTEIRanker는 지정된 쿼리에 대한 의미적 관련성에 따라 문서를 순위 매겨요. 다음 TEI API 엔드포인트 중 하나와 함께 사용할 수 있어요:
top_k 파라미터를 지정해 반환할 최대 문서 수를 설정할 수도 있어요. TEI 서버 구성에 따라 인증에 사용할 Hugging Face 토큰이 필요할 수도 있어요. HF_API_TOKEN 또는 HF_TOKEN 환경 변수로 설정하거나 Haystack의 Secret 관리로 설정할 수 있어요.
- 대표적인 파이프라인 위치: 쿼리 파이프라인에서 문서 리스트를 반환하는 컴포넌트(예: Retriever) 뒤
- 필수 init 변수:
url— TEI reranking 서비스의 기본 URL(예:"https://api.example.com"). - 필수 run 변수:
query(쿼리 문자열) /documents(문서 객체 리스트) - 출력 변수:
documents— 문서 객체 리스트 - API reference: Hugging Face API
- 패키지명:
huggingface-api-haystack
Usage
pip install huggingface-api-haystack
On its own
파이프라인 밖에서 HuggingFaceTEIRanker를 사용해 쿼리 기준으로 문서를 정렬할 수 있어요. 이 예시는 두 개의 간단한 문서를 순위 매겨요. Ranker를 실행하려면 쿼리를 전달하고, 문서를 제공하며, top_k 파라미터에 반환할 문서 수를 설정하세요.
from haystack import Document
from haystack_integrations.components.rankers.huggingface_api import (
HuggingFaceTEIRanker,
)
from haystack.utils import Secret
reranker = HuggingFaceTEIRanker(
url="http://localhost:8080",
top_k=5,
timeout=30,
token=Secret.from_token("my_api_token"),
)
docs = [
Document(content="The capital of France is Paris"),
Document(content="The capital of Germany is Berlin"),
]
result = reranker.run(query="What is the capital of France?", documents=docs)
ranked_docs = result["documents"]
print(ranked_docs)
# >> {'documents': [Document(id=..., content: 'the capital of France is Paris', score: 0.9979767),
# >> Document(id=..., content: 'the capital of Germany is Berlin', score: 0.13982213)]}
In a pipeline
HuggingFaceTEIRanker는 쿼리 파이프라인에서 Retriever 뒤에 사용할 때 가장 효율적이에요. 아래 파이프라인은 InMemoryDocumentStore에서 키워드 검색(InMemoryBM25Retriever 사용)으로 문서를 검색하고, HuggingFaceTEIRanker로 쿼리에 대한 유사성에 따라 검색된 문서를 순위 매겨요. 파이프라인은 Ranker의 기본 설정을 사용해요.
from haystack import Document, Pipeline
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack_integrations.components.rankers.huggingface_api import (
HuggingFaceTEIRanker,
)
docs = [
Document(content="Paris is in France"),
Document(content="Berlin is in Germany"),
Document(content="Lyon is in France"),
]
document_store = InMemoryDocumentStore()
document_store.write_documents(docs)
retriever = InMemoryBM25Retriever(document_store=document_store)
ranker = HuggingFaceTEIRanker(url="http://localhost:8080")
document_ranker_pipeline = Pipeline()
document_ranker_pipeline.add_component(instance=retriever, name="retriever")
document_ranker_pipeline.add_component(instance=ranker, name="ranker")
document_ranker_pipeline.connect("retriever.documents", "ranker.documents")
query = "Cities in France"
document_ranker_pipeline.run(
data={
"retriever": {"query": query, "top_k": 3},
"ranker": {"query": query, "top_k": 2},
},
)