llamaindex について
LlamaIndexは、データをLLMアプリケーションに接続するフレームワークです。RAG、文書の質問応答、ナレッジ検索システムの開発向けに、データコネクター、インデックス、リトリーバー、クエリエンジンを提供し、複数のデータソースやベクトルストアに対応します。
主な機能
- 01複数のデータソース用コネクター
- 02ベクトル、リスト、ツリーインデックス
- 03リトリーバーとクエリエンジン
- 04ストリーミングクエリとチャット
- 05ベクトルストア連携
- 06マルチモーダルRAG
活用シーン
- 01プライベート文書の質問応答システム構築
- 02多様なソースからのデータ取り込み
- 03企業データを扱うチャットボットの作成
- 04文書からの構造化情報の抽出
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ kalarislabs/ research-agent-skills --skill llamaindexインストール後、Claude Code で/llamaindexを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/advanced-rag-patterns.mdagents-with-tools.mdagents.mddata_connectors.mdquery_engines.md詳細
LlamaIndex - LLM アプリケーション向けデータフレームワーク
LLM とデータをつなぐ主要なフレームワークです。
LlamaIndex を使う場面
次の場合に LlamaIndex を使用してください:
- RAG(検索拡張生成)アプリケーションを構築する
- プライベートデータを対象に、ドキュメントへの質問応答が必要
- 複数のソースからデータを取り込む(300 以上のコネクター)
- LLM 向けのナレッジベースを作成する
- エンタープライズデータを使ったチャットボットを構築する
- ドキュメントから構造化データを抽出する必要がある
指標:
- 23,000 以上のリポジトリで LlamaIndex が使用されています
- 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
ツールを使うエージェント
詳細、コード例、パラメータ表については、references/agents-with-tools.md を参照してください。この手順が該当する場合に読んでください。
高度な RAG パターン
詳細、コード例、パラメータ表については、references/advanced-rag-patterns.md を参照してください。この手順が該当する場合に読んでください。
データ取り込みパターン
複数のファイル形式
# Load all supported formats
documents = SimpleDirectoryReader(
"./data",
recursive=True,
required_exts=[".pdf", ".docx", ".txt", ".md"]
).load_data()
ウェブスクレイピング
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 が向上します
- 開発中は詳細出力を有効にする - 検索プロセスを確認できます
- 応答を評価する - 関連性と忠実性を確認します
- 会話にはチャットエンジンを使用する - メモリが組み込まれています
- ストレージを永続化する - インデックスを失わないようにします
- コストを監視する - 埋め込みと 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 への注力 | 中核機能 | 多くの機能のうちの 1 つ |
| 学習曲線 | RAG ではより簡単 | より急 |
| カスタマイズ性 | 高い | 非常に高い |
| ドキュメント | 非常に充実 | 充実 |
次の場合に LlamaIndex を使用してください:
- 主なユースケースが RAG である
- 多くのデータコネクターが必要
- ドキュメント Q&A 向けのよりシンプルな API が必要
- ナレッジ検索システムを構築する
次の場合に LangChain を使用してください:
- 複雑なエージェントを構築する
- より汎用的なツールが必要
- より高い柔軟性が必要
- 複雑な複数ステップのワークフローを扱う
参考資料
- クエリエンジンガイド - クエリモード、カスタマイズ、ストリーミング
- エージェントガイド - ツールの作成、RAG エージェント、複数ステップの推論
- データコネクターガイド - 300 以上のコネクター、カスタムローダー
リソース
- GitHub: https://github.com/run-llama/llama_index ⭐ 45,100+
- ドキュメント: https://developers.llamaindex.ai/python/framework/
- LlamaHub: https://llamahub.ai(データコネクター)
- LlamaCloud: https://cloud.llamaindex.ai(エンタープライズ)
- Discord: https://discord.gg/dGcwcsnxhU
- バージョン: 0.14.7+
- ライセンス: MIT
エージェントの運用手順
- 環境を確認します。 フレームワークのバージョン、モデルプロバイダー、API キー、レート制限を確認します。
- 入力を明確にします。 データまたはユーザーから、形式、識別子、パラメーターを確認します。結果を左右する値は推測せず、質問します。
- まず小規模に実行します。 既知の入力を使って単一の呼び出しまたはチェーンをテストし、生の出力を確認します。
- 上記の指示と参考資料を使って、タスク全体を実行します。
- 結果を検証します。 小規模なラベル付きデータセットで評価し、構造化出力をスキーマと照合し、プロンプトと応答を記録します。
- 報告します。 実行した内容(バージョン、コマンド、パラメーター)、確認した内容、未確定の事項を明示します。
| このような場合 | 対応方法 |
|---|---|
| 出力が期待されるスキーマと一致しない | 検証と再試行を追加し、スキーマを厳密にするか、プロンプトを簡潔にします。 |
| これらの指示に記載された関数、フラグ、エンドポイントがインストール済みバージョンに存在しない | インストール済みバージョンのドキュメント(help()、--help、公式ドキュメント)を確認し、適宜調整してユーザーに伝えます。API を決して捏造しないでください。 |
| 必須の入力、識別子、パラメーターが曖昧 | ユーザーに質問するか、実行前に仮定を明示します。 |
整合性に関するルール
- 結果、パラメーター、識別子、引用、統計を決して捏造しないでください。実行または検証できない場合は、その旨を明確に伝えてください。
- ユーザーの同意なしに、個人情報や機密データを外部 API に送信しないでください。
- ここに記載されたバージョン固有の詳細は古くなっている可能性があるため、インストール済みバージョンの公式ドキュメントで確認してください。
- 費用が発生する、共有 GPU やクラウドのクォータを消費する、個人データまたは患者データにアクセスする、あるいは取り消せない操作を行う前に、ユーザーに確認してください。
関連スキル
langchain:エージェント、チェーン、RAG を備えた LLM 搭載アプリケーションを構築するフレームワーク。chroma:AI アプリケーション向けのオープンソース埋め込みデータベース。langsmith-observability:トレース、評価、モニタリングを行う LLM オブザーバビリティプラットフォーム。
コメント
Markdown 対応