Epsilla 벡터 저장소

Epsilla 벡터 저장소 (Epsilla Vector Store)

이번엔 Epsilla를 이용해 LlamaIndex에서 벡터 검색을 수행하는 방법을 배워볼게요. Epsilla는 경량 벡터 데이터베이스라서 로컬 환경에서도 가볍게 올려 실습할 수 있답니다. 사전 준비로 Epsilla 벡터 DB를 실행 중이어야 하고 pyepsilla 패키지가 설치되어 있어야 해요.

출처: 문서

본문

이 노트북에서는 Epsilla를 사용해 LlamaIndex에서 벡터 검색을 수행하는 방법을 보여드리겠습니다.

사전 조건으로, 실행 중인 Epsilla 벡터 데이터베이스(예: 도커 이미지로 실행)와 pyepsilla 패키지 설치가 필요합니다. 전체 문서는 docs에서 확인하세요.

%pip install llama-index-vector-stores-epsilla
!pip/pip3 install pyepsilla

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

!pip install llama-index
import logging
import sys


# Uncomment to see debug logs
# logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
# logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))


from llama_index.core import SimpleDirectoryReader, Document, StorageContext
from llama_index.core import VectorStoreIndex
from llama_index.vector_stores.epsilla import EpsillaVectorStore
import textwrap

OpenAI 설정

먼저 openai api key를 추가해 보겠습니다. 이 키는 인덱스에 로드된 문서에 대한 임베딩을 생성하는 데 사용됩니다.

import openai
import getpass


OPENAI_API_KEY = getpass.getpass("OpenAI API Key:")
openai.api_key = OPENAI_API_KEY

데이터 다운로드

!mkdir -p 'data/paul_graham/'
!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'

문서 로드 (Loading documents)

SimpleDirectoryReader 를 사용해 /data/paul_graham 폴더에 저장된 문서를 로드합니다.

# load documents
documents = SimpleDirectoryReader("./data/paul_graham/").load_data()
print(f"Total documents: {len(documents)}")
print(f"First document, id: {documents[0].doc_id}")
print(f"First document, hash: {documents[0].hash}")
Total documents: 1
First document, id: ac7f23f0-ce15-4d94-a0a2-5020fa87df61
First document, hash: 4c702b4df575421e1d1af4b1fd50511b226e0c9863dbfffeccb8b689b8448f35

인덱스 생성 (Create the index)

여기서는 앞서 로드한 문서를 사용해 Epsilla가 지원하는 인덱스를 생성합니다. EpsillaVectorStore 는 몇 가지 인자를 받습니다.

  • client (Any): 연결할 Epsilla 클라이언트.

  • collection_name (str, optional): 사용할 컬렉션. 기본값은 “llama_collection”.

  • db_path (str, optional): 데이터베이스가 영속화될 경로. 기본값은 “/tmp/langchain-epsilla”.

  • db_name (str, optional): 로드된 데이터베이스에 부여할 이름. 기본값은 “langchain_store”.

  • dimension (int, optional): 임베딩의 차원. 제공되지 않으면 첫 삽입 시 컬렉션 생성이 수행됩니다. 기본값은 None.

  • overwrite (bool, optional): 같은 이름의 기존 컬렉션을 덮어쓸지 여부. 기본값은 False.

Epsilla vectordb는 기본 호스트 “localhost”와 포트 “8888”에서 실행됩니다.

# Create an index over the documnts
from pyepsilla import vectordb


client = vectordb.Client()
vector_store = EpsillaVectorStore(client=client, db_path="/tmp/llamastore")


storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(
    documents, storage_context=storage_context
)
[INFO] Connected to localhost:8888 successfully.

데이터 쿼리 (Query the data)

이제 문서가 인덱스에 저장되었으니 인덱스에 질문을 던질 수 있습니다.

query_engine = index.as_query_engine()
response = query_engine.query("Who is the author?")
print(textwrap.fill(str(response), 100))
The author of the given context information is Paul Graham.
response = query_engine.query("How did the author learn about AI?")
print(textwrap.fill(str(response), 100))
The author learned about AI through various sources. One source was a novel called "The Moon is a
Harsh Mistress" by Heinlein, which featured an intelligent computer called Mike. Another source was
a PBS documentary that showed Terry Winograd using SHRDLU, a program that could understand natural
language. These experiences sparked the author's interest in AI and motivated them to start learning
about it, including teaching themselves Lisp, which was regarded as the language of AI at the time.

다음으로, 이전 데이터를 덮어쓰기(overwrite) 해 보겠습니다.

vector_store = EpsillaVectorStore(client=client, overwrite=True)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
single_doc = Document(text="Epsilla is the vector database we are using.")
index = VectorStoreIndex.from_documents(
    [single_doc],
    storage_context=storage_context,
)


query_engine = index.as_query_engine()
response = query_engine.query("Who is the author?")
print(textwrap.fill(str(response), 100))
There is no information provided about the author in the given context.
response = query_engine.query("What vector database is being used?")
print(textwrap.fill(str(response), 100))
Epsilla is the vector database being used.

다음으로, 기존 컬렉션에 데이터를 더 추가해 보겠습니다.

vector_store = EpsillaVectorStore(client=client, overwrite=False)
index = VectorStoreIndex.from_vector_store(vector_store=vector_store)
for doc in documents:
    index.insert(document=doc)


query_engine = index.as_query_engine()
response = query_engine.query("Who is the author?")
print(textwrap.fill(str(response), 100))
The author of the given context information is Paul Graham.
response = query_engine.query("What vector database is being used?")
print(textwrap.fill(str(response), 100))
Epsilla is the vector database being used.

더 알아보기 (Learn more)