Lantern 벡터 저장소

Lantern 벡터 저장소 (auto-retriever) (Lantern Vector Store)

이 가이드에서는 Lantern 벡터 DB에서 자동 검색(Auto-Retrieval) 을 수행하는 방법을 배워볼게요. 자연어 쿼리를 주면 LLM이 메타데이터 필터와 검색어를 함께 추론해서, 단순 top-k 검색보다 훨씬 정밀한 검색이 가능해진답니다. 원리는 Pinecone, Chroma, Weaviate 등 다른 벡터 DB에도 그대로 적용돼요.

출처: 문서

본문

이 가이드에서는 LlamaIndex에서 자동 검색(auto-retrieval) 을 수행하는 방법을 보여줍니다.

많은 인기 벡터 DB는 의미적 검색(semantic search)을 위한 쿼리 문자열 외에도 메타데이터 필터 세트를 지원합니다. 자연어 쿼리가 주어지면 먼저 LLM을 사용해 메타데이터 필터 세트와 벡터 DB에 전달할 올바른 쿼리 문자열을 추론합니다(둘 중 하나는 비어 있을 수도 있습니다). 이 전체 쿼리 번들을 벡터 DB에 대해 실행합니다.

이를 통해 top-k 의미적 검색보다 더 역동적이고 표현력 있는 형태의 검색이 가능해집니다. 주어진 쿼리에 대한 관련 컨텍스트가 메타데이터 태그 필터링만 필요할 수도 있고, 필터링된 집합 안에서 필터링과 의미적 검색을 결합해야 할 수도 있으며, 단순한 의미적 검색만으로 충분할 수도 있습니다.

Lantern 예제를 보여드리지만, 자동 검색은 다른 많은 벡터 DB(예: Pinecone, Chroma, Weaviate 등)에서도 구현되어 있습니다.

콜랩 노트북에서 열고 있다면 LlamaIndex 설치가 필요할 거예요 🦙.

%pip install llama-index-vector-stores-lantern
!pip install llama-index psycopg2-binary asyncpg
import logging
import sys


logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
# set up OpenAI
import os


os.environ["OPENAI_API_KEY"] = "<your-api-key>"


import openai


openai.api_key = os.environ["OPENAI_API_KEY"]
import psycopg2
from sqlalchemy import make_url


connection_string = "postgresql://postgres:***@localhost:5432"


url = make_url(connection_string)


db_name = "postgres"
conn = psycopg2.connect(connection_string)
conn.autocommit = True
from llama_index.core import VectorStoreIndex, StorageContext
from llama_index.vector_stores.lantern import LanternVectorStore
from llama_index.core.schema import TextNode


nodes = [
    TextNode(
        text=(
            "Michael Jordan is a retired professional basketball player,"
            " widely regarded as one of the greatest basketball players of all"
            " time."
        ),
        metadata={
            "category": "Sports",
            "country": "United States",
        },
    ),
    TextNode(
        text=(
            "Angelina Jolie is an American actress, filmmaker, and"
            " humanitarian. She has received numerous awards for her acting"
            " and is known for her philanthropic work."
        ),
        metadata={
            "category": "Entertainment",
            "country": "United States",
        },
    ),
    TextNode(
        text=(
            "Elon Musk is a business magnate, industrial designer, and"
            " engineer. He is the founder, CEO, and lead designer of SpaceX,"
            " Tesla, Inc., Neuralink, and The Boring Company."
        ),
        metadata={
            "category": "Business",
            "country": "United States",
        },
    ),
    TextNode(
        text=(
            "Rihanna is a Barbadian singer, actress, and businesswoman. She"
            " has achieved significant success in the music industry and is"
            " known for her versatile musical style."
        ),
        metadata={
            "category": "Music",
            "country": "Barbados",
        },
    ),
    TextNode(
        text=(
            "Cristiano Ronaldo is a Portuguese professional footballer who is"
            " considered one of the greatest football players of all time. He"
            " has won numerous awards and set multiple records during his"
            " career."
        ),
        metadata={
            "category": "Sports",
            "country": "Portugal",
        },
    ),
]

Lantern 벡터 저장소로 벡터 인덱스 구축하기 (Build Vector Index with Lantern Vector Store)

여기서는 데이터를 벡터 저장소에 로드합니다. 위에서 언급했듯이 각 노드의 텍스트와 메타데이터 모두 Lantern에서의 상응하는 표현으로 변환됩니다. 이제 이 데이터에 대해 의미적 검색과 메타데이터 필터링을 모두 실행할 수 있습니다.

vector_store = LanternVectorStore.from_params(
    database=db_name,
    host=url.host,
    password=url.password,
    port=url.port,
    user=url.username,
    table_name="famous_people",
    embed_dim=1536,  # openai embedding dimension
    m=16,  # HNSW M parameter
    ef_construction=128,  # HNSW ef construction parameter
    ef=64,  # HNSW ef search parameter
)


storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex(nodes, storage_context=storage_context)

VectorIndexAutoRetriever 정의하기

핵심 모듈인 VectorIndexAutoRetriever 를 정의합니다. 이 모듈은 벡터 저장소 컬렉션과 지원하는 메타데이터 필터에 대한 구조화된 설명을 포함하는 VectorStoreInfo 를 입력받습니다. 이 정보는 자동 검색 프롬프트에서 사용되어 LLM이 메타데이터 필터를 추론하게 됩니다.

from llama_index.core.retrievers import VectorIndexAutoRetriever
from llama_index.core.vector_stores import MetadataInfo, VectorStoreInfo



vector_store_info = VectorStoreInfo(
    content_info="brief biography of celebrities",
    metadata_info=[
        MetadataInfo(
            name="category",
            type="str",
            description=(
                "Category of the celebrity, one of [Sports, Entertainment,"
                " Business, Music]"
            ),
        ),
        MetadataInfo(
            name="country",
            type="str",
            description=(
                "Country of the celebrity, one of [United States, Barbados,"
                " Portugal]"
            ),
        ),
    ],
)
retriever = VectorIndexAutoRetriever(
    index, vector_store_info=vector_store_info
)

샘플 데이터로 실행하기 (Running over some sample data)

샘플 데이터를 대상으로 실행해 봅니다. 메타데이터 필터가 어떻게 추론되는지 살펴보세요. 이는 더 정확한 검색에 도움이 됩니다!

retriever.retrieve("Tell me about two celebrities from United States")

더 알아보기 (Learn more)