MVI: 데이터용으로 가장 생산적이고 사용하기 쉬운 serverless vector index입니다. MVI를 시작하려면 계정에 가입하기만 하면 됩니다. 인프라를 관리하거나 서버를 운영하거나 확장성에 대해 걱정할 필요가 없습니다. MVI는 필요에 따라 자동으로 확장되는 서비스입니다.
MVI에 가입하고 액세스하려면 Momento Console을 방문하세요.

설정

필수 구성 요소 설치

다음이 필요합니다:
  • MVI와 상호작용하기 위한 momento 패키지
  • OpenAI API와 상호작용하기 위한 openai 패키지
  • 텍스트 토크나이징을 위한 tiktoken 패키지
pip install -qU  momento langchain-openai langchain-community tiktoken

API 키 입력

import getpass
import os

Momento: 데이터 인덱싱용

API 키를 받으려면 Momento Console을 방문하세요.
if "MOMENTO_API_KEY" not in os.environ:
    os.environ["MOMENTO_API_KEY"] = getpass.getpass("Momento API Key:")

OpenAI: 텍스트 임베딩용

if "OPENAI_API_KEY" not in os.environ:
    os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")

데이터 로드

여기서는 LangChain의 예제 데이터셋인 State of the Union 연설을 사용합니다. 먼저 관련 모듈을 로드합니다:
from langchain_community.document_loaders import TextLoader
from langchain_community.vectorstores import MomentoVectorIndex
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import CharacterTextSplitter
그다음 데이터를 로드합니다:
loader = TextLoader("../../how_to/state_of_the_union.txt")
documents = loader.load()
len(documents)
1
데이터가 하나의 큰 파일이므로 문서는 하나뿐입니다:
len(documents[0].page_content)
38539
이것은 큰 텍스트 파일이므로 질문 응답을 위해 청크로 분할합니다. 이렇게 하면 사용자 질문에 가장 관련성이 높은 청크에서 답변할 수 있습니다.
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
docs = text_splitter.split_documents(documents)
len(docs)
42

데이터 인덱싱

데이터 인덱싱은 MomentoVectorIndex 객체를 인스턴스화하는 것만큼 간단합니다. 여기서는 from_documents helper를 사용하여 객체를 생성하고 데이터를 인덱싱합니다:
vector_db = MomentoVectorIndex.from_documents(
    docs, OpenAIEmbeddings(), index_name="sotu"
)
이는 API 키를 사용하여 Momento Vector Index 서비스에 연결하고 데이터를 인덱싱합니다. 인덱스가 이전에 존재하지 않았다면 이 과정에서 생성됩니다. 이제 데이터는 검색 가능합니다.

데이터 질의

인덱스에 직접 질문하기

데이터를 질의하는 가장 직접적인 방법은 인덱스를 검색하는 것입니다. VectorStore API를 사용하여 다음과 같이 수행할 수 있습니다:
query = "What did the president say about Ketanji Brown Jackson"
docs = vector_db.similarity_search(query)
docs[0].page_content
'Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.'
이 결과에는 Ketanji Brown Jackson에 대한 관련 정보가 포함되어 있지만, 간결하고 사람이 읽기 쉬운 답변은 아닙니다. 다음 섹션에서 이를 해결하겠습니다.

LLM을 사용하여 유창한 답변 생성

MVI에 데이터가 인덱싱되면, vector similarity search를 활용하는 어떤 chain과도 통합할 수 있습니다. 여기서는 인덱싱된 데이터에서 질문에 답하는 방법을 보여주기 위해 RetrievalQA 체인을 사용합니다. 먼저 관련 모듈을 로드합니다:
from langchain.chains import RetrievalQA
from langchain_openai import ChatOpenAI
그다음 retrieval QA 체인을 인스턴스화합니다:
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
qa_chain = RetrievalQA.from_chain_type(llm, retriever=vector_db.as_retriever())
qa_chain({"query": "What did the president say about Ketanji Brown Jackson?"})
{'query': 'What did the president say about Ketanji Brown Jackson?',
 'result': "The President said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to serve on the United States Supreme Court. He described her as one of the nation's top legal minds and mentioned that she has received broad support from various groups, including the Fraternal Order of Police and former judges appointed by Democrats and Republicans."}

다음 단계

완료입니다! 이제 데이터를 인덱싱했으며 Momento Vector Index를 사용해 질의할 수 있습니다. vector similarity search를 지원하는 어떤 chain에서도 동일한 인덱스를 사용해 데이터를 질의할 수 있습니다. Momento를 사용하면 vector 데이터 인덱싱뿐만 아니라 API 호출 캐시와 채팅 메시지 기록 저장도 가능합니다. 자세한 내용은 다른 Momento LangChain 통합을 확인해 보세요. Momento Vector Index에 대해 더 알아보려면 Momento Documentation을 방문하세요.
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I