LlamaIndex Tutorial: Building RAG Applications
Last updated: June 7 2025
Introduction
LlamaIndexは、Retrieval-Augmented Generation (RAG) を通じて、Large Language Models (LLMs) をプライベートデータに接続する強力なデータフレームワークです。このチュートリアルでは、ドキュメントをクエリできるインテリジェントなアプリケーションを構築するための基本的な概念を説明します。
Key Components
- Documents: データと関連するメタデータを表現するための基本的なコンテナです。テキスト、PDF、API出力、データベースレコードなど、さまざまなデータソースをラップする役割を果たします
- Data Connectors: さまざまなソースからデータを取り込むためのツール
- LlamaHub: オープンソースのデータコネクタのレジストリで、LlamaIndexアプリケーション(+ Agent Tools、Llama Packs)に簡単に組み込むことができます
- Nodes: ソースドキュメントの「チャンク」であり、テキストチャンク、画像、その他の形式が含まれます。Documentsと同様に、メタデータや他のノードとの関係情報を含みます
- Index: ユーザーのクエリに対して関連するコンテキストを迅速に取得するためのデータ構造
- Query Engine: 質問をするためのインターフェース
- Response Synthesizer: ユーザーのクエリと取得されたノード(またはテキストチャンク)のセットを受け取り、最終的な応答を生成するコンポーネント
1. セットアップとインストール
# Uncomment to install required packages
# !pip install llama-index openai python-dotenv -qimport os
from dotenv import load_dotenv
from llama_index.core import (
SimpleDirectoryReader,
VectorStoreIndex,
Document,
Settings
)
from llama_index.core.node_parser import SentenceSplitter
from llama_index.llms.openai import OpenAI
from llama_index.embeddings.openai import OpenAIEmbedding# Load environment variables from .env file
load_dotenv()
# Load API keys from .env file
openai_api_key = os.getenv("OPENAI_API_KEY")
# Verify API key is loaded
if openai_api_key:
print("✅ OpenAI API key loaded from .env file")
os.environ["OPENAI_API_KEY"] = openai_api_key
else:
print("❌ OpenAI API key not found in .env file")
print("Please add OPENAI_API_KEY=your-actual-key to your .env file")✅ OpenAI API key loaded from .env file
# Configure global settings
Settings.llm = OpenAI(model="gpt-3.5-turbo", temperature=0.1)
Settings.embed_model = OpenAIEmbedding(model="text-embedding-ada-002")2. ドキュメントの読み込み
# Method 1: Create sample documents
sample_text = """
LlamaIndex is a data framework for building LLM applications.
It provides tools to ingest, structure, and access private data for LLMs.
The framework supports various data sources including PDFs, databases, and APIs.
RAG is the core technique that allows LLMs to answer questions about your data.
"""
documents = [Document(text=sample_text)]
# Method 2: Load from directory (uncomment to use)
# !mkdir -p data
# documents = SimpleDirectoryReader("data").load_data()
print(f"Loaded {len(documents)} documents")
print(f"First document preview: {documents[0].text[:100]}...")Loaded 1 documents First document preview: LlamaIndex is a data framework for building LLM applications. It provides tools to ingest, structu...
3. Document Chunking (Node Parsing)
Chunking は、ドキュメントをより良い検索のために小さな部分に分割します。主な考慮事項:
- Chunk Size: 小さいチャンク = より正確、大きいチャンク = より多くの文脈
- Overlap: 境界での情報損失を防ぐ
- Default: 1024トークン、20トークンのオーバーラップ
# Configure text splitter
text_splitter = SentenceSplitter(
chunk_size=512, # Smaller chunks for demo
chunk_overlap=50
)
# Parse documents into nodes
nodes = text_splitter.get_nodes_from_documents(documents)
print(f"Created {len(nodes)} nodes")
print(f"First node: {nodes[0].text}")
print(f"Node metadata: {nodes[0].metadata}")Created 1 nodes
First node: LlamaIndex is a data framework for building LLM applications.
It provides tools to ingest, structure, and access private data for LLMs.
The framework supports various data sources including PDFs, databases, and APIs.
RAG is the core technique that allows LLMs to answer questions about your data.
Node metadata: {}
4. ベクターインデックスの作成
VectorStoreIndex はテキストを埋め込み(セマンティック検索のための数値表現)に変換します。
# Method 1: Direct from documents
index = VectorStoreIndex.from_documents(documents, show_progress=True)
# Method 2: From nodes (more control)
# index = VectorStoreIndex(nodes, show_progress=True)
print("Vector index created successfully!")Parsing nodes: 0%| | 0/1 [00:00<?, ?it/s]
Generating embeddings: 0%| | 0/1 [00:00<?, ?it/s]
Vector index created successfully!
5. クエリエンジンの構築
Query Engine は、検索および応答生成プロセスを処理します。
# Create query engine
query_engine = index.as_query_engine(
similarity_top_k=2, # Retrieve top 2 most similar chunks
streaming=False
)
# Test query
response = query_engine.query("What is LlamaIndex?")
print("Answer:", response)
print("\nSource nodes:")
for node in response.source_nodes:
print(f"- Score: {node.score:.3f}")
print(f" Text: {node.text[:100]}...\n")Answer: LlamaIndex is a data framework for building LLM applications that provides tools for ingesting, structuring, and accessing private data for LLMs. Source nodes: - Score: 0.894 Text: LlamaIndex is a data framework for building LLM applications. It provides tools to ingest, structur...
6. Advanced: Custom Retrieval
より良い結果を得るためにリトリーバルを微調整します。
# Get retriever for more control
retriever = index.as_retriever(
similarity_top_k=3,
# filters=MetadataFilters(...) # Add metadata filters if needed
)
# Test retrieval
retrieved_nodes = retriever.retrieve("How does RAG work?")
print(f"Retrieved {len(retrieved_nodes)} nodes:")
for i, node in enumerate(retrieved_nodes):
print(f"\nNode {i+1} (Score: {node.score:.3f}):")
print(node.text[:150] + "...")Retrieved 1 nodes: Node 1 (Score: 0.794): LlamaIndex is a data framework for building LLM applications. It provides tools to ingest, structure, and access private data for LLMs. The framework...
7. 永続性とストレージ
ドキュメントを再処理しないように、インデックスを保存してください。
# Save index
index.storage_context.persist(persist_dir="./storage")
print("Index saved to ./storage")
# Load index (for future sessions)
from llama_index.core import StorageContext, load_index_from_storage
# storage_context = StorageContext.from_defaults(persist_dir="./storage")
# loaded_index = load_index_from_storage(storage_context)
# query_engine = loaded_index.as_query_engine()Index saved to ./storage
8. インタラクティブデモ
# Interactive query function
def ask_question(question):
response = query_engine.query(question)
print(f"Question: {question}")
print(f"Answer: {response}")
print("-" * 50)
# Test different questions
questions = [
"What is LlamaIndex?",
"How does RAG work?",
"What data sources does LlamaIndex support?"
]
for q in questions:
ask_question(q)Question: What is LlamaIndex? Answer: LlamaIndex is a data framework designed for creating LLM applications, offering tools for managing private data from different sources like PDFs, databases, and APIs. It utilizes the RAG technique to enable LLMs to analyze and respond to inquiries about the data. -------------------------------------------------- Question: How does RAG work? Answer: RAG works as the core technique that enables LLMs to respond to inquiries regarding the data by utilizing the tools provided within the LlamaIndex framework. -------------------------------------------------- Question: What data sources does LlamaIndex support? Answer: LlamaIndex supports various data sources including PDFs, databases, and APIs. --------------------------------------------------
重要なポイント
ベストプラクティス
- Chunk Size: 1024トークンから始めて、データに基づいて調整する
- Embeddings: ドメインに適したモデルを選択する
- Retrieval:
similarity_top_kの値を試してみる - Persistence: 本番環境で使用するためにインデックスを必ず保存する
次のステップ
- ノードパーサー(Semantic, Hierarchical)の異なる種類を試す
- セマンティック検索とキーワード検索を組み合わせたハイブリッド検索を試す
- 正確な検索のためにメタデータフィルタリングを実装する
- 会話型インターフェースのためのチャットエンジンを構築する
- エージェントを使用してマルチステップ推論を実装する
パフォーマンス向上のヒント
- 正確な回答のために小さいチャンクを使用する
- 包括的なコンテキストのために大きいチャンクを使用する
- スケーリングのためにベクターデータベース(Pinecone, Chroma)を検討する
- 品質を測定するために評価指標を実装する
LlamaIndexは、RAGアプリケーションを簡単に構築できる一方で、高度なユースケースに対応する柔軟性も提供します。シンプルに始めて、必要に応じて徐々に複雑さを追加してください!