mcpField
L
llamaindex-development

llamaindex-development

github.com/mindrally開発287697 回インストール3 週間前に更新
リポジトリ

llamaindex-development について

LlamaIndexでPythonのRAGやLLMアプリを開発する人向けのスキルです。文書処理、インデックス作成、検索、クエリエンジン、エージェントの実装と開発上の指針を扱います。

主な機能

  1. 01文書の読み込みと分割
  2. 02ベクトルインデックスと永続化
  3. 03クエリエンジンとリトリーバー
  4. 04LLMと埋め込みの設定
  5. 05非同期処理とキャッシュ

活用シーン

  1. 01PythonでのRAGアプリ構築
  2. 02文書インデックスの保存と再読み込み
  3. 03キーワード検索とベクトル検索の併用

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/mindrally/skills --skill llamaindex-development

インストール後、Claude Code で/llamaindex-developmentを入力して読み込まれたか確認します。

詳細

LlamaIndex 開発

Python を使用した RAG(Retrieval-Augmented Generation)アプリケーション、データのインデックス作成、LLM を活用したアプリケーションの構築における LlamaIndex のエキスパートです。

主な原則

  • 正確な Python の例を用いて、簡潔で技術的な回答を作成します
  • 関数型で宣言的なプログラミングを使用し、可能な限りクラスを避けます
  • コードの品質、保守性、パフォーマンスを優先します
  • 目的を反映した分かりやすい変数名を使用します
  • PEP 8 のスタイルガイドラインに従います

コードの構成

ディレクトリ構造
project/
├── data/                 # Source documents and data
├── indexes/              # Persisted index storage
├── loaders/              # Custom document loaders
├── retrievers/           # Custom retriever implementations
├── query_engines/        # Query engine configurations
├── prompts/              # Custom prompt templates
├── transformations/      # Document transformations
├── callbacks/            # Custom callback handlers
├── utils/                # Utility functions
├── tests/                # Test files
└── config/               # Configuration files
命名規則
  • ファイル、関数、変数には snake_case を使用します
  • クラスには PascalCase を使用します
  • プライベート関数にはアンダースコアを付けます
  • 目的が分かりやすい名前を使用します(例:create_vector_index、build_query_engine)

ドキュメントの読み込み

ドキュメントローダーの使用
from llama_index.core import SimpleDirectoryReader
from llama_index.readers.file import PDFReader, DocxReader

# Load from directory
documents = SimpleDirectoryReader(
    input_dir="./data",
    recursive=True,
    required_exts=[".pdf", ".txt", ".md"]
).load_data()

# Load specific file types
pdf_reader = PDFReader()
documents = pdf_reader.load_data(file="document.pdf")
カスタムローダー
from llama_index.core.readers.base import BaseReader
from llama_index.core import Document

class CustomLoader(BaseReader):
    def load_data(self, file_path: str) -> list[Document]:
        # Custom loading logic
        with open(file_path, 'r') as f:
            content = f.read()

        return [Document(
            text=content,
            metadata={"source": file_path}
        )]

テキストの分割と処理

ノードの解析
from llama_index.core.node_parser import (
    SentenceSplitter,
    SemanticSplitterNodeParser,
    MarkdownNodeParser
)

# Simple sentence splitting
splitter = SentenceSplitter(
    chunk_size=1024,
    chunk_overlap=200
)
nodes = splitter.get_nodes_from_documents(documents)

# Semantic splitting (preserves meaning)
from llama_index.embeddings.openai import OpenAIEmbedding

semantic_splitter = SemanticSplitterNodeParser(
    embed_model=OpenAIEmbedding(),
    breakpoint_percentile_threshold=95
)

# Markdown-aware splitting
markdown_splitter = MarkdownNodeParser()
チャンク分割のベストプラクティス
  • 埋め込みモデルのコンテキストウィンドウに基づいてチャンクサイズを選択します
  • チャンク間のコンテキストを維持するためにオーバーラップを使用します
  • 可能な限りドキュメントの構造を保持します
  • フィルタリングと検索のためにメタデータを含めます
  • 一貫性を高めるためにセマンティック分割を使用します

ベクトルストアとインデックス作成

インデックスの作成
from llama_index.core import VectorStoreIndex, StorageContext
from llama_index.vector_stores.chroma import ChromaVectorStore
import chromadb

# In-memory index
index = VectorStoreIndex.from_documents(documents)

# With persistent vector store
chroma_client = chromadb.PersistentClient(path="./chroma_db")
chroma_collection = chroma_client.get_or_create_collection("my_collection")

vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
storage_context = StorageContext.from_defaults(vector_store=vector_store)

index = VectorStoreIndex.from_documents(
    documents,
    storage_context=storage_context
)
対応するベクトルストア
  • Chroma(ローカル開発)
  • Pinecone(本番環境、マネージド)
  • Weaviate(本番環境、セルフホストまたはマネージド)
  • Qdrant(本番環境、セルフホストまたはマネージド)
  • pgvector を使用した PostgreSQL
  • MongoDB Atlas Vector Search
インデックスの永続化
from llama_index.core import StorageContext, load_index_from_storage

# Persist index
index.storage_context.persist(persist_dir="./storage")

# Load index
storage_context = StorageContext.from_defaults(persist_dir="./storage")
index = load_index_from_storage(storage_context)

クエリエンジン

基本的なクエリエンジン
from llama_index.core import VectorStoreIndex

index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine(
    similarity_top_k=5,
    response_mode="compact"
)

response = query_engine.query("What is the main topic?")
print(response.response)
回答モード
  • refine:各ノードを通じて回答を反復的に改善します
  • compact:LLM に送信する前にチャンクを結合します
  • tree_summarize:ツリーを構築して要約します
  • simple_summarize:切り詰めて要約します
  • accumulate:各ノードからの回答を蓄積します
高度なクエリエンジン
from llama_index.core.query_engine import RetrieverQueryEngine
from llama_index.core.postprocessor import SimilarityPostprocessor

query_engine = RetrieverQueryEngine.from_args(
    retriever=index.as_retriever(similarity_top_k=10),
    node_postprocessors=[
        SimilarityPostprocessor(similarity_cutoff=0.7)
    ],
    response_mode="compact"
)

リトリーバー

カスタムリトリーバー
from llama_index.core.retrievers import VectorIndexRetriever

# Basic retriever
retriever = VectorIndexRetriever(
    index=index,
    similarity_top_k=10
)

# Retrieve nodes
nodes = retriever.retrieve("search query")
ハイブリッド検索
from llama_index.core.retrievers import QueryFusionRetriever

# Combine multiple retrieval strategies
retriever = QueryFusionRetriever(
    [
        index.as_retriever(similarity_top_k=5),
        bm25_retriever,  # Keyword-based
    ],
    num_queries=4,
    use_async=True
)

埋め込み

埋め込みモデル
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.core import Settings

# OpenAI embeddings
Settings.embed_model = OpenAIEmbedding(
    model="text-embedding-3-small",
    dimensions=512  # Optional dimension reduction
)

# Local embeddings
Settings.embed_model = HuggingFaceEmbedding(
    model_name="BAAI/bge-small-en-v1.5"
)

LLM の設定

LLM のセットアップ
from llama_index.llms.openai import OpenAI
from llama_index.llms.anthropic import Anthropic
from llama_index.core import Settings

# OpenAI
Settings.llm = OpenAI(
    model="gpt-4o",
    temperature=0.1
)

# Anthropic
Settings.llm = Anthropic(
    model="claude-sonnet-4-20250514",
    temperature=0.1
)

エージェント

エージェントの構築
from llama_index.core.agent import ReActAgent
from llama_index.core.tools import QueryEngineTool, ToolMetadata

# Create tools from query engines
tools = [
    QueryEngineTool(
        query_engine=documents_query_engine,
        metadata=ToolMetadata(
            name="documents",
            description="Search through documents"
        )
    ),
    QueryEngineTool(
        query_engine=code_query_engine,
        metadata=ToolMetadata(
            name="codebase",
            description="Search through code"
        )
    )
]

# Create agent
agent = ReActAgent.from_tools(
    tools,
    llm=llm,
    verbose=True
)

response = agent.chat("Find information about X")

パフォーマンスの最適化

キャッシュ
from llama_index.core import Settings
from llama_index.core.llms import LLMCache

# Enable LLM response caching
Settings.llm = OpenAI(model="gpt-4o")
Settings.llm_cache = LLMCache()
非同期処理
# Use async for better performance
response = await query_engine.aquery("question")

# Batch processing
responses = await asyncio.gather(*[
    query_engine.aquery(q) for q in questions
])
埋め込みの最適化
  • 可能な場合は埋め込みをバッチ処理します
  • 精度に問題がない場合は、埋め込みの次元数を小さくします
  • 繰り返し使用するドキュメントの埋め込みをキャッシュします
  • コストを重視するアプリケーションではローカルモデルを使用します

エラー処理

from llama_index.core.callbacks import CallbackManager, LlamaDebugHandler

# Debug handler for troubleshooting
debug_handler = LlamaDebugHandler()
callback_manager = CallbackManager([debug_handler])

Settings.callback_manager = callback_manager

テスト

  • ドキュメントローダーと変換処理を単体テストします
  • 既知のクエリを使用して検索品質をテストします
  • インデックスの永続化と読み込みを検証します
  • クエリエンジンの応答をテストします
  • 検索指標(適合率、再現率)を監視します

依存関係

  • llama-index
  • llama-index-embeddings-openai
  • llama-index-llms-openai
  • llama-index-vector-stores-chroma
  • chromadb
  • python-dotenv
  • pydantic

コメント