배경 및 목적
LlamaIndex 공식 문서에 있는 "Building a RAG pipeline" 이해
RAG pipeline의 stage별로 약간의 고도화 적용
참고 자료
LlamaIndex 공식 문서 : Learn > Building a RAG pipeline
활용 툴
Visual studio code(jupyter notebook)
LlamaIndex
DBeaver
실행 과정
RAG pipeline
RAG pipeline
RAG pipeline Stage별 적용 내용
Loading : SimpleDirectoryReader
Indexing & Embedding : VectorStoreIndex
Storing : chromadb
Querying
Retrieval : VectorIndexRetriever, similarity_top_k = 2(유사도 상위 2개)
PostProcessing
SimilarityPostprocessor(similarity_cotoff=0.2)
KeywordNodePostprocessor(required_keywords, exclude_keyword)
Response Synthesis : get_response_synthesizer
#### 작성 코드
필요한 라이브러리와 모듈 임포트, LlamaIndex Settings, 환경 변수(api key) 로드
# 필요한 라이브러리와 모듈 임포트
from dotenv import load_dotenv
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.llms.openai import OpenAI
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core import Settings
import chromadb
# LlamaIndex Settings
Settings.llm = OpenAI(model="gpt-4o-mini", temperature=0)
Settings.embed_model = OpenAIEmbedding(model="text-embedding-3-small")
# .env 파일에서 환경 변수(OPENAI_API_KEY) 로드
load_dotenv()Chromadb 관련
# Chromadb 관련 모듈 임포트
from llama_index.vector_stores.chroma import ChromaVectorStore
from llama_index.core import StorageContext
# Chromadb 클라이언트 초기화
db = chromadb.PersistentClient(path="./chroma_db")
# "quickstart" 컬렉션 생성 또는 가져오기
chroma_collection = db.get_or_create_collection("quickstart")
ChromaVectorStore 및 StorageContext 설정
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
storage_context = StorageContext.from_defaults(vector_store=vector_store)컬렉션에 데이터가 있는지 확인하고 작업 수행
if chroma_collection.count() == 0:
print("Collection is empty. Indexing documents...")
# load documents
documents = SimpleDirectoryReader("./data").load_data()
# create your index
index = VectorStoreIndex.from_documents(
documents, storage_context=storage_context
)
print("Indexing completed.")
else:
print(f"Collection already contains {chroma_collection.count()} items. Loading existing index...")
# load your index from stored vectors
index = VectorStoreIndex.from_vector_store(
vector_store, storage_context=storage_context
)
print("Existing index loaded.")실행 결과
Collection already contains 22 items. Loading existing index...
Existing index loaded.Querying Stage 필요 라이브러리 임포트