llamaindex について
LlamaIndexは、RAGやドキュメントQ&A、ナレッジ検索を構築する開発者向けのLLMアプリケーション用データフレームワークです。データの読み込み、インデックス作成、検索、クエリに加え、ツールを使うエージェントやマルチモーダルRAGにも対応します。
主な機能
- 01多様なソースからデータを取り込む
- 02複数形式のインデックスを作成
- 03ドキュメントの検索とクエリ
- 04チャットとツール利用エージェント
- 05構造化出力と評価
活用シーン
- 01プライベート文書のQ&Aシステム構築
- 02企業データを扱うチャットボット作成
- 03ドキュメントからの構造化情報抽出
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ orchestra-research/ ai-research-skills --skill llamaindexインストール後、Claude Code で/llamaindexを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/agents.mddata_connectors.mdquery_engines.md詳細
LlamaIndex - LLM アプリケーションのためのデータフレームワーク
LLM とお客様のデータを接続するための代表的なフレームワークです。
LlamaIndex を使うべき場面
LlamaIndex が適しているケース:
- RAG(検索拡張生成)アプリケーションを構築する場合
- プライベートデータに対するドキュメント質疑応答が必要な場合
- 複数のソースからデータを取り込む場合(300 以上のコネクター)
- LLM 向けのナレッジベースを作成する場合
- エンタープライズデータを活用したチャットボットを構築する場合
- ドキュメントから構造化データの抽出が必要な場合
指標:
- GitHub スター 45,100 以上
- LlamaIndex を利用するリポジトリ 23,000 以上
- 300 以上のデータコネクター(LlamaHub)
- コントリビューター 1,715 以上
- v0.14.7(安定版)
代わりに検討すべき選択肢:
- LangChain: より汎用的で、エージェントに適している
- Haystack: 本番環境向けの検索パイプライン
- txtai: 軽量なセマンティック検索
- Chroma: ベクトルストレージのみが必要な場合
クイックスタート
インストール
# Starter package (recommended)
pip install llama-index
# Or minimal core + specific integrations
pip install llama-index-core
pip install llama-index-llms-openai
pip install llama-index-embeddings-openai
5 行で始める RAG の例
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
# Load documents
documents = SimpleDirectoryReader("data").load_data()
# Create index
index = VectorStoreIndex.from_documents(documents)
# Query
query_engine = index.as_query_engine()
response = query_engine.query("What did the author do growing up?")
print(response)
基本コンセプト
1. データコネクター - ドキュメントの読み込み
from llama_index.core import SimpleDirectoryReader, Document
from llama_index.readers.web import SimpleWebPageReader
from llama_index.readers.github import GithubRepositoryReader
# Directory of files
documents = SimpleDirectoryReader("./data").load_data()
# Web pages
reader = SimpleWebPageReader()
documents = reader.load_data(["https://example.com"])
# GitHub repository
reader = GithubRepositoryReader(owner="user", repo="repo")
documents = reader.load_data(branch="main")
# Manual document creation
doc = Document(
text="This is the document content",
metadata={"source": "manual", "date": "2025-01-01"}
)
2. インデックス - データの構造化
from llama_index.core import VectorStoreIndex, ListIndex, TreeIndex
# Vector index (most common - semantic search)
vector_index = VectorStoreIndex.from_documents(documents)
# List index (sequential scan)
list_index = ListIndex.from_documents(documents)
# Tree index (hierarchical summary)
tree_index = TreeIndex.from_documents(documents)
# Save index
index.storage_context.persist(persist_dir="./storage")
# Load index
from llama_index.core import load_index_from_storage, StorageContext
storage_context = StorageContext.from_defaults(persist_dir="./storage")
index = load_index_from_storage(storage_context)
3. クエリエンジン - 質問する
# Basic query
query_engine = index.as_query_engine()
response = query_engine.query("What is the main topic?")
print(response)
# Streaming response
query_engine = index.as_query_engine(streaming=True)
response = query_engine.query("Explain quantum computing")
for text in response.response_gen:
print(text, end="", flush=True)
# Custom configuration
query_engine = index.as_query_engine(
similarity_top_k=3, # Return top 3 chunks
response_mode="compact", # Or "tree_summarize", "simple_summarize"
verbose=True
)
4. リトリーバー - 関連するチャンクの検索
# Vector retriever
retriever = index.as_retriever(similarity_top_k=5)
nodes = retriever.retrieve("machine learning")
# With filtering
retriever = index.as_retriever(
similarity_top_k=3,
filters={"metadata.category": "tutorial"}
)
# Custom retriever
from llama_index.core.retrievers import BaseRetriever
class CustomRetriever(BaseRetriever):
def _retrieve(self, query_bundle):
# Your custom retrieval logic
return nodes
ツールを使うエージェント
基本的なエージェント
from llama_index.core.agent import FunctionAgent
from llama_index.llms.openai import OpenAI
# Define tools
def multiply(a: int, b: int) -> int:
"""Multiply two numbers."""
return a * b
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
# Create agent
llm = OpenAI(model="gpt-4o")
agent = FunctionAgent.from_tools(
tools=[multiply, add],
llm=llm,
verbose=True
)
# Use agent
response = agent.chat("What is 25 * 17 + 142?")
print(response)
RAG エージェント(ドキュメント検索 + ツール)
from llama_index.core.tools import QueryEngineTool
# Create index as before
index = VectorStoreIndex.from_documents(documents)
# Wrap query engine as tool
query_tool = QueryEngineTool.from_defaults(
query_engine=index.as_query_engine(),
name="python_docs",
description="Useful for answering questions about Python programming"
)
# Agent with document search + calculator
agent = FunctionAgent.from_tools(
tools=[query_tool, multiply, add],
llm=llm
)
# Agent decides when to search docs vs calculate
response = agent.chat("According to the docs, what is Python used for?")
高度な RAG パターン
チャットエンジン(会話型)
from llama_index.core.chat_engine import CondensePlusContextChatEngine
# Chat with memory
chat_engine = index.as_chat_engine(
chat_mode="condense_plus_context", # Or "context", "react"
verbose=True
)
# Multi-turn conversation
response1 = chat_engine.chat("What is Python?")
response2 = chat_engine.chat("Can you give examples?") # Remembers context
response3 = chat_engine.chat("What about web frameworks?")
メタデータフィルタリング
from llama_index.core.vector_stores import MetadataFilters, ExactMatchFilter
# Filter by metadata
filters = MetadataFilters(
filters=[
ExactMatchFilter(key="category", value="tutorial"),
ExactMatchFilter(key="difficulty", value="beginner")
]
)
retriever = index.as_retriever(
similarity_top_k=3,
filters=filters
)
query_engine = index.as_query_engine(filters=filters)
構造化出力
from pydantic import BaseModel
from llama_index.core.output_parsers import PydanticOutputParser
class Summary(BaseModel):
title: str
main_points: list[str]
conclusion: str
# Get structured response
output_parser = PydanticOutputParser(output_cls=Summary)
query_engine = index.as_query_engine(output_parser=output_parser)
response = query_engine.query("Summarize the document")
summary = response # Pydantic model
print(summary.title, summary.main_points)
データ取り込みのパターン
複数のファイル形式
# Load all supported formats
documents = SimpleDirectoryReader(
"./data",
recursive=True,
required_exts=[".pdf", ".docx", ".txt", ".md"]
).load_data()
Web スクレイピング
from llama_index.readers.web import BeautifulSoupWebReader
reader = BeautifulSoupWebReader()
documents = reader.load_data(urls=[
"https://docs.python.org/3/tutorial/",
"https://docs.python.org/3/library/"
])
データベース
from llama_index.readers.database import DatabaseReader
reader = DatabaseReader(
sql_database_uri="postgresql://user:pass@localhost/db"
)
documents = reader.load_data(query="SELECT * FROM articles")
API エンドポイント
from llama_index.readers.json import JSONReader
reader = JSONReader()
documents = reader.load_data("https://api.example.com/data.json")
ベクトルストアの統合
Chroma(ローカル)
from llama_index.vector_stores.chroma import ChromaVectorStore
import chromadb
# Initialize Chroma
db = chromadb.PersistentClient(path="./chroma_db")
collection = db.get_or_create_collection("my_collection")
# Create vector store
vector_store = ChromaVectorStore(chroma_collection=collection)
# Use in index
from llama_index.core import StorageContext
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)
Pinecone(クラウド)
from llama_index.vector_stores.pinecone import PineconeVectorStore
import pinecone
# Initialize Pinecone
pinecone.init(api_key="your-key", environment="us-west1-gcp")
pinecone_index = pinecone.Index("my-index")
# Create vector store
vector_store = PineconeVectorStore(pinecone_index=pinecone_index)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)
FAISS(高速)
from llama_index.vector_stores.faiss import FaissVectorStore
import faiss
# Create FAISS index
d = 1536 # Dimension of embeddings
faiss_index = faiss.IndexFlatL2(d)
vector_store = FaissVectorStore(faiss_index=faiss_index)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)
カスタマイズ
カスタム LLM
from llama_index.llms.anthropic import Anthropic
from llama_index.core import Settings
# Set global LLM
Settings.llm = Anthropic(model="claude-sonnet-4-5-20250929")
# Now all queries use Anthropic
query_engine = index.as_query_engine()
カスタム埋め込み
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
# Use HuggingFace embeddings
Settings.embed_model = HuggingFaceEmbedding(
model_name="sentence-transformers/all-mpnet-base-v2"
)
index = VectorStoreIndex.from_documents(documents)
カスタムプロンプトテンプレート
from llama_index.core import PromptTemplate
qa_prompt = PromptTemplate(
"Context: {context_str}\n"
"Question: {query_str}\n"
"Answer the question based only on the context. "
"If the answer is not in the context, say 'I don't know'.\n"
"Answer: "
)
query_engine = index.as_query_engine(text_qa_template=qa_prompt)
マルチモーダル RAG
画像 + テキスト
from llama_index.core import SimpleDirectoryReader
from llama_index.multi_modal_llms.openai import OpenAIMultiModal
# Load images and documents
documents = SimpleDirectoryReader(
"./data",
required_exts=[".jpg", ".png", ".pdf"]
).load_data()
# Multi-modal index
index = VectorStoreIndex.from_documents(documents)
# Query with multi-modal LLM
multi_modal_llm = OpenAIMultiModal(model="gpt-4o")
query_engine = index.as_query_engine(llm=multi_modal_llm)
response = query_engine.query("What is in the diagram on page 3?")
評価
応答品質
from llama_index.core.evaluation import RelevancyEvaluator, FaithfulnessEvaluator
# Evaluate relevance
relevancy = RelevancyEvaluator()
result = relevancy.evaluate_response(
query="What is Python?",
response=response
)
print(f"Relevancy: {result.passing}")
# Evaluate faithfulness (no hallucination)
faithfulness = FaithfulnessEvaluator()
result = faithfulness.evaluate_response(
query="What is Python?",
response=response
)
print(f"Faithfulness: {result.passing}")
ベストプラクティス
- ほとんどのケースでベクトルインデックスを使用する - 最も高いパフォーマンス
- インデックスをディスクに保存する - 再インデックスを避ける
- ドキュメントを適切にチャンク化する - 512〜1024 トークンが最適
- メタデータを追加する - フィルタリングと追跡を可能にする
- ストリーミングを使用する - 長い応答に対する UX が向上する
- 開発中は verbose を有効にする - 検索プロセスを確認できる
- 応答を評価する - 関連性と忠実性を確認する
- 会話にはチャットエンジンを使用する - 組み込みのメモリを利用できる
- ストレージを永続化する - インデックスを失わないようにする
- コストを監視する - 埋め込みと LLM の使用量を追跡する
よくあるパターン
ドキュメント Q&A システム
# Complete RAG pipeline
documents = SimpleDirectoryReader("docs").load_data()
index = VectorStoreIndex.from_documents(documents)
index.storage_context.persist(persist_dir="./storage")
# Query
query_engine = index.as_query_engine(
similarity_top_k=3,
response_mode="compact",
verbose=True
)
response = query_engine.query("What is the main topic?")
print(response)
print(f"Sources: {[node.metadata['file_name'] for node in response.source_nodes]}")
メモリを持つチャットボット
# Conversational interface
chat_engine = index.as_chat_engine(
chat_mode="condense_plus_context",
verbose=True
)
# Multi-turn chat
while True:
user_input = input("You: ")
if user_input.lower() == "quit":
break
response = chat_engine.chat(user_input)
print(f"Bot: {response}")
パフォーマンスベンチマーク
| 操作 | レイテンシ | 備考 |
|---|---|---|
| 100 件のドキュメントをインデックス化 | 約 10〜30 秒 | 一度だけ実行、永続化可能 |
| クエリ(ベクトル) | 約 0.5〜2 秒 | 検索 + LLM |
| ストリーミングクエリ | 最初のトークンまで約 0.5 秒 | より良い UX |
| ツールを使うエージェント | 約 3〜8 秒 | 複数のツール呼び出し |
LlamaIndex と LangChain の比較
| 機能 | LlamaIndex | LangChain |
|---|---|---|
| 最適な用途 | RAG、ドキュメント Q&A | エージェント、汎用的な LLM アプリ |
| データコネクター | 300 以上(LlamaHub) | 100 以上 |
| RAG への注力 | 中核機能 | 多くの機能の一つ |
| 学習曲線 | RAG には習得しやすい | より急 |
| カスタマイズ性 | 高い | 非常に高い |
| ドキュメント | 優れている | 良好 |
LlamaIndex を使うべき場面:
- 主なユースケースが RAG である場合
- 多くのデータコネクターが必要な場合
- ドキュメント Q&A 向けのよりシンプルな API が欲しい場合
- ナレッジ検索システムを構築する場合
LangChain を使うべき場面:
- 複雑なエージェントを構築する場合
- より汎用的なツールが必要な場合
- より高い柔軟性が欲しい場合
- 複雑な多段階のワークフローの場合
参考資料
- クエリエンジンガイド - クエリモード、カスタマイズ、ストリーミング
- エージェントガイド - ツールの作成、RAG エージェント、多段階の推論
- データコネクターガイド - 300 以上のコネクター、カスタムローダー
Resources
- GitHub: https://github.com/run-llama/llama_index ⭐ 45,100+
- Docs: https://developers.llamaindex.ai/python/framework/
- LlamaHub: https://llamahub.ai (data connectors)
- LlamaCloud: https://cloud.llamaindex.ai (enterprise)
- Discord: https://discord.gg/dGcwcsnxhU
- Version: 0.14.7+
- License: MIT
コメント
Markdown 対応