AlloyDBKeywordRetriever

AlloyDBKeywordRetriever

AlloyDB Document Store에서 쿼리와 일치하는 문서를 가져오는 키워드 기반 Retriever예요.

파이프라인에서 가장 흔한 위치:

  1. RAG 파이프라인에서 PromptBuilder 앞
  2. 의미 검색(semantic search) 파이프라인의 마지막 컴포넌트
  3. 추출형 QA 파이프라인에서 TransformersExtractiveReader 앞

필수 init 변수: document_store — AlloyDBDocumentStore 인스턴스 필수 run 변수: query — 문자열 출력 변수: documents — 쿼리와 일치하는 문서 목록 API reference: AlloyDB GitHub link: https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/alloydb Package name: alloydb-haystack

출처: 문서

본문

Overview

AlloyDBKeywordRetriever는 AlloyDBDocumentStore와 호환되는 키워드 기반 Retriever예요.

PostgreSQL 전문(full-text) 검색(to_tsvector / plainto_tsquery)으로 Documents를 찾고, ts_rank_cd로 순위를 매깁니다. 순위는 쿼리 용어가 Document에 얼마나 자주 나타나는지, 용어들이 얼마나 가까이 있는지, 그리고 발생한 부분이 Document에서 얼마나 중요한지에 따라 결정돼요. 자세한 내용은 PostgreSQL 문서를 참고하세요.

ElasticsearchBM25Retriever 같은 유사 컴포넌트와 달리, 이 Retriever는 기본적으로 퍼지(fuzzy) 검색을 적용하지 않는다는 점을 기억하세요. 그래서 결과가 0건 나오지 않도록 쿼리를 신중하게 작성해야 해요.

키워드 검색을 위해 쿼리와 Document 내용을 파싱할 때 사용하는 언어는 AlloyDBDocumentStore의 language 파라미터로 설정합니다(기본값 "english"). 데이터베이스에서 지원하는 언어 목록을 보려면 다음을 실행하세요:

SELECT cfgname FROM pg_ts_config;

query 외에도 AlloyDBKeywordRetriever는 선택 파라미터를 받아요. top_k(가져올 최대 Document 수)와 검색 공간을 좁히는 filters가 있죠.

Installation

alloydb-haystack 통합을 설치하세요:

pip install alloydb-haystack

AlloyDB 클러스터와 인스턴스를 설정하려면 AlloyDB quickstart를 따르세요.

Usage

On its own

이 Retriever는 실행하려면 AlloyDBDocumentStore와 인덱싱된 Documents가 필요해요.

AlloyDB 인스턴스에 연결하려면 ALLOYDB_INSTANCE_URI, ALLOYDB_USER, ALLOYDB_PASSWORD 환경 변수를 설정하세요.

from haystack_integrations.document_stores.alloydb import AlloyDBDocumentStore
from haystack_integrations.components.retrievers.alloydb import (
    AlloyDBKeywordRetriever,
)

document_store = AlloyDBDocumentStore()
retriever = AlloyDBKeywordRetriever(document_store=document_store)
retriever.run(query="my nice query")

In a RAG pipeline

이 코드 실행에 필요한 준비물은 다음과 같아요:

  • OpenAI API 키가 담긴 OPENAI_API_KEY 환경 변수 설정
  • AlloyDB 인스턴스에 연결하기 위한 ALLOYDB_INSTANCE_URI, ALLOYDB_USER, ALLOYDB_PASSWORD 환경 변수 설정
from haystack import Document, Pipeline
from haystack.components.builders.answer_builder import AnswerBuilder
from haystack.components.builders.chat_prompt_builder import ChatPromptBuilder
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.document_stores.types import DuplicatePolicy
from haystack_integrations.document_stores.alloydb import AlloyDBDocumentStore
from haystack_integrations.components.retrievers.alloydb import (
    AlloyDBKeywordRetriever,
)

## Create a RAG query pipeline
prompt_template = [
    ChatMessage.from_system("You are a helpful assistant."),
    ChatMessage.from_user(
        "Given these documents, answer the question.\nDocuments:\n"
        "{% for doc in documents %}{{ doc.content }}{% endfor %}\n"
        "Question: {{question}}\nAnswer:",
    ),
]
document_store = AlloyDBDocumentStore(
    language="english",  # this parameter influences text parsing for keyword retrieval
    recreate_table=True,
)
documents = [
    Document(content="There are over 7,000 languages spoken around the world today."),
    Document(
        content="Elephants have been observed to behave in a way that indicates a high level of self-awareness, such as recognizing themselves in mirrors.",
    ),
    Document(
        content="In certain parts of the world, like the Maldives, Puerto Rico, and San Diego, you can witness the phenomenon of bioluminescent waves.",
    ),
]
document_store.write_documents(documents=documents, policy=DuplicatePolicy.SKIP)

retriever = AlloyDBKeywordRetriever(document_store=document_store)
rag_pipeline = Pipeline()
rag_pipeline.add_component(name="retriever", instance=retriever)
rag_pipeline.add_component(
    instance=ChatPromptBuilder(
        template=prompt_template,
        required_variables={"question", "documents"},
    ),
    name="prompt_builder",
)
rag_pipeline.add_component(instance=OpenAIChatGenerator(), name="llm")
rag_pipeline.add_component(instance=AnswerBuilder(), name="answer_builder")

rag_pipeline.connect("retriever", "prompt_builder.documents")
rag_pipeline.connect("prompt_builder.prompt", "llm.messages")
rag_pipeline.connect("llm.replies", "answer_builder.replies")
rag_pipeline.connect("retriever", "answer_builder.documents")

question = "languages spoken around the world today"
result = rag_pipeline.run(
    {
        "retriever": {"query": question},
        "prompt_builder": {"question": question},
        "answer_builder": {"query": question},
    },
)
print(result["answer_builder"])

더 알아보기 (Learn more)