SupabasePgvectorKeywordRetriever

SupabasePgvectorKeywordRetriever

SupabasePgvectorKeywordRetriever 는 SupabasePgvectorDocumentStore 에서 키워드 쿼리와 일치하는 문서를 가져오는 키워드 기반 리트리버예요. PostgreSQL의 전문 검색 기능을 이용해 문서를 찾아 ts_rank_cd 로 순위를 매겨요.

출처: 문서

본문

개요 (Overview)

SupabasePgvectorKeywordRetriever 는 PgvectorKeywordRetriever 를 SupabasePgvectorDocumentStore 와 함께 쓰도록 맞춘 얇은 래퍼예요.

PostgreSQL 전문 검색(to_tsvector / plainto_tsquery)으로 문서를 찾고 ts_rank_cd 함수로 순위를 매겨요. 순위는 질의 용어가 문서에 얼마나 자주 나타나는지, 용어들이 얼마나 가까이 있는지, 그리고 그 용어들이 문서의 어느 부분에 있는지(그 부분의 중요도)를 고려해요. 자세한 내용은 PostgreSQL 문서를 참고하세요.

주의할 점: ElasticsearchBM25Retriever 같은 유사 컴포넌트와 달리 이 리트리버는 기본적으로 퍼지 검색을 적용하지 않아요. 그래서 결과가 0건이 되는 걸 피하려면 질의를 신중하게 정식화해야 해요.

키워드 검색을 위해 질의와 문서 내용을 파싱하는 언어는 SupabasePgvectorDocumentStore 의 language 파라미터로 설정해요(기본값은 "english").

query 외에 이 리트리버는 top_k(가져올 최대 문서 수)와 검색 범위를 좁히는 filters 같은 선택 파라미터를 받아요.

설치 (Installation)

pip install supabase-haystack

사용법 (Usage)

단독으로 쓰기

이 리트리버는 SupabasePgvectorDocumentStore 와 인덱싱된 문서가 있어야 동작해요. Supabase 데이터베이스 연결 문자열로 SUPABASE_DB_URL 환경 변수를 설정하세요.

from haystack_integrations.document_stores.supabase import SupabasePgvectorDocumentStore
from haystack_integrations.components.retrievers.supabase import (
    SupabasePgvectorKeywordRetriever,
)

document_store = SupabasePgvectorDocumentStore()
retriever = SupabasePgvectorKeywordRetriever(document_store=document_store)
retriever.run(query="my nice query")

RAG 파이프라인에서 쓰기

이 코드를 실행하기 위한 사전 조건은 다음과 같아요:

  • OPENAI_API_KEY 환경 변수에 OpenAI API 키를 설정하세요.
  • SUPABASE_DB_URL 환경 변수에 Supabase 데이터베이스 연결 문자열을 설정하세요.
from haystack import Document, Pipeline
from haystack.components.builders.answer_builder import AnswerBuilder
from haystack.components.builders 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.supabase import SupabasePgvectorDocumentStore
from haystack_integrations.components.retrievers.supabase import (
    SupabasePgvectorKeywordRetriever,
)

prompt_template = [
    ChatMessage.from_user(
        "Given these documents, answer the question.\nDocuments:\n"
        "{% for doc in documents %}{{ doc.content }}{% endfor %}\n"
        "Question: {{question}}\nAnswer:"
    ),
]

document_store = SupabasePgvectorDocumentStore(
    language="english",
    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 = SupabasePgvectorKeywordRetriever(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)