관리형 인덱스 사용하기

관리형 인덱스 사용하기 (Using Managed Indices)

관리형 인덱스(Managed Index)는 LlamaIndex 내부가 아니라 API를 통해 관리되는 특별한 인덱스예요. Google, Vectara, Vertex AI와 같은 관리형 인덱스를 사용하는 방법을 알아봅시다.

출처: 문서

본문

LlamaIndex는 관리형 인덱스(Managed Index)와 여러 통합 지점을 제공합니다. 관리형 인덱스는 LlamaIndex의 일부로 로컬에서 관리되지 않고 Vectara 같은 API를 통해 관리되는 특수한 유형의 인덱스입니다.

관리형 인덱스 사용하기

LlamaIndex 내의 다른 인덱스(트리, 키워드 테이블, 리스트)와 마찬가지로 어떤 ManagedIndex든 문서 컬렉션으로 구성할 수 있습니다. 구성이 끝나면 인덱스를 쿼리에 사용할 수 있습니다.

인덱스에 이전에 문서가 채워져 있다면, 바로 쿼리에 사용할 수도 있습니다.

Google Generative Language Semantic Retriever

Google의 Semantic Retriever는 쿼리와 검색 기능을 모두 제공합니다. 관리형 인덱스를 만들고 문서를 넣은 뒤 LlamaIndex 어디서든 쿼리 엔진이나 리트리버를 사용하면 됩니다.

from llama_index.core import SimpleDirectoryReader
from llama_index.indices.managed.google import GoogleIndex


# Create a corpus
index = GoogleIndex.create_corpus(display_name="My first corpus!")
print(f"Newly created corpus ID is {index.corpus_id}.")


# Ingestion
documents = SimpleDirectoryReader("data").load_data()
index.insert_documents(documents)


# Querying
query_engine = index.as_query_engine()
response = query_engine.query("What did the author do growing up?")


# Retrieving
retriever = index.as_retriever()
source_nodes = retriever.retrieve("What did the author do growing up?")

전체 내용은 노트북 가이드를 참고하세요.

Vectara

먼저 가입하고 Vectara Console에서 코퍼스(일명 Index)를 만든 뒤 접근용 API 키를 추가하세요. API 키를 얻으면 환경 변수로 export합니다.

import os


os.environ["VECTARA_API_KEY"] = "<YOUR_VECTARA_API_KEY>"
os.environ["VECTARA_CORPUS_KEY"] = "<YOUR_VECTARA_CORPUS_KEY>"

그런 다음 Vectara Index를 구성하고 다음과 같이 쿼리합니다.

from llama_index.core import ManagedIndex, SimpleDirectoryReade
from llama_index.indices.managed.vectara import VectaraIndex


# Load documents and build index
vectara_corpus_key = os.environ.get("VECTARA_CORPUS_KEY")
vectara_api_key = os.environ.get("VECTARA_API_KEY")


documents = SimpleDirectoryReader("../paul_graham_essay/data").load_data()
index = VectaraIndex.from_documents(
    documents,
    vectara_corpus_key=vectara_corpus_key,
    vectara_api_key=vectara_api_key,
)

참고 사항:

  • 환경 변수 VECTARA_CORPUS_KEY와 VECTARA_API_KEY가 이미 환경에 있다면 호출에서 명시적으로 지정하지 않아도 되며, VectaraIndex 클래스가 환경에서 읽습니다.
  • 여러 Vectara 코퍼스에 연결하려면 VECTARA_CORPUS_KEY를 쉼표로 구분된 목록으로 설정할 수 있습니다. 예를 들어 12,51은 코퍼스 12와 코퍼스 51에 연결됩니다.

코퍼스에 이미 문서가 있다면 다음과 같이 VectaraIndex를 구성해 데이터에 바로 접근할 수 있습니다.

index = VectaraIndex()

VectaraIndex는 새 문서를 로드하지 않고 기존 코퍼스에 연결됩니다.

인덱스를 쿼리하려면 다음과 같이 쿼리 엔진을 구성합니다.

query_engine = index.as_query_engine(summary_enabled=True)
print(query_engine.query("What did the author do growing up?"))

또는 채팅 기능을 사용할 수 있습니다.

chat_engine = index.as_chat_engine()
print(chat_engine.chat("What did the author do growing up?").response)

채팅은 이후 chat 호출이 대화 기록을 유지하는 식으로 예상대로 동작합니다. 이 모든 작업은 Vectara 플랫폼에서 이루어지므로 추가 로직을 넣을 필요가 없습니다.

더 많은 예제는 아래를 참고하세요.

Vertex AI RAG (LlamaIndex on Vertex AI)

LlamaIndex on Vertex AI for RAG은 Google Cloud Vertex AI의 관리형 RAG 인덱스입니다.

먼저 Google Cloud 프로젝트를 만들고 Vertex AI API를 활성화한 뒤, 다음 코드로 관리형 인덱스를 만듭니다.

from llama_index.indices.managed.vertexai import VertexAIIndex


# TODO(developer): Replace these values with your project information
project_id = "YOUR_PROJECT_ID"
location = "us-central1"


# Optional: If using an existing corpus
corpus_id = "YOUR_CORPUS_ID"


# Optional: If creating a new corpus
corpus_display_name = "my-corpus"
corpus_description = "Vertex AI Corpus for LlamaIndex"


# Create a corpus or provide an existing corpus ID
index = VertexAIIndex(
    project_id,
    location,
    corpus_display_name=corpus_display_name,
    corpus_description=corpus_description,
)
print(f"Newly created corpus name is {index.corpus_name}.")


# Import files from Google Cloud Storage or Google Drive
index.import_files(
    uris=["https://drive.google.com/file/123", "gs://my_bucket/my_files_dir"],
    chunk_size=512,  # Optional
    chunk_overlap=100,  # Optional
)


# Upload local file
index.insert_file(
    file_path="my_file.txt",
    metadata={"display_name": "my_file.txt", "description": "My file"},
)


# Querying
query_engine = index.as_query_engine()
response = query_engine.query("What is RAG and why it is helpful?")


# Retrieving
retriever = index.as_retriever()
nodes = retriever.retrieve("What is RAG and why it is helpful?")

전체 내용은 노트북 가이드를 참고하세요.

더 알아보기 (Learn more)