agentsope/agentsop-llamaindex
| Operating-system distillation of LlamaIndex — the leading RAG / document-agent framework. Activate when the calling agent must build, debug, harden, or evaluate a Retrieval-Augmented Generation pipeline over unstructured/private data, decide between RAG primitives (Index types, retrievers, query engines, routers, agents), or pick LlamaIndex vs LangChain / Haystack / raw vector store for a coding task. Encodes the 5-layer mental model (Documents → Nodes → Indices → Retrievers → Query Engines / Response Synthesizers), the canonical RAG bootstrap SOP from baseline `VectorStoreIndex` through hybrid + reranker + eval-loop hardening, the official 13-failure-mode checklist, and 5 dilemma cases distilled from docs, GitHub issues, and 2025 production post-mortems.
npx skills add https://github.com/agentsope/SkillAlchemy --skill agentsop-llamaindex
> Third-person analytical view of how LlamaIndex *thinks* about turning private
> documents into a grounded answering system. The skill is for an LLM agent that
> writes / reviews / debugs RAG code — not for an end user reading docs.
Activate this skill when any of the following holds:
from llama_index...), LlamaParse, LlamaCloud, or a LlamaIndex-style primitive (VectorStoreIndex, SummaryIndex, IngestionPipeline, QueryEngine, SubQuestionQueryEngine, RouterQueryEngine, Settings, Workflows).Do not activate when:
LlamaIndex's design rests on three principles that distinguish it from "vector DB SDK + custom glue":
> In LangChain, "indexing" is something you do to a vector store. In LlamaIndex, an Index is a first-class typed object with its own retrieval semantics. Picking the right Index is half the architecture decision.
The 5-layer pipeline:
Documents → Nodes → Index → Retriever → Query Engine → Response
↓ ↓ ↓ ↓ ↓
parsing chunking storage filters synthesis
metadata graph primitive rerank (refine/tree_sum/compact)
Each layer has a distinct failure mode and a distinct optimization knob. See references/R1-architecture.md for the layer-failure-knob mapping.
A Node carries: text, metadata, embedding, relationships (PREV/NEXT/PARENT/CHILD links), and lifecycle ids. The relationships field is what enables Hierarchical, Auto-Merging, and Sentence-Window retrieval. The mental flip: don't think "split into chunks", think "build a chunk-graph".
| Index | Pick when |
|---|---|
| VectorStoreIndex | Default; semantic Q&A over chunks; ~90% of RAG cases |
| SummaryIndex | "Summarize this whole doc" — small, fan-out synthesis |
| TreeIndex | Hierarchical content with progressive zoom-in |
| KeywordTableIndex | Keyword-heavy queries, no embeddings budget |
| PropertyGraphIndex | Multi-hop reasoning over entities |
| DocumentSummaryIndex | Mixed corpora needing document-level routing first |
A RouterQueryEngine over multiple per-task indices is often the correct top-level shape, not a single monolithic VectorStoreIndex.
LlamaIndex now positions as "the leading document agent and OCR platform" (README). LlamaParse v2 + Workflows 1.0 (June 2025) + LlamaCloud mark a strategic move from "RAG framework" to "platform between messy documents and document-grounded agents". For a coder agent: assume Workflows for any new agentic code (QueryPipeline is deprecated).
The protocol every RAG implementation must walk through. Each stage gates on the next.
Before code, answer:
R4 boundaries; LlamaIndex may be the wrong tool.from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings
from llama_index.core.node_parser import SentenceSplitter
Settings.llm = OpenAI(model="gpt-4o-mini")
Settings.embed_model = OpenAIEmbedding(model="text-embedding-3-small")
Settings.node_parser = SentenceSplitter(chunk_size=1024, chunk_overlap=20)
docs = SimpleDirectoryReader("./data").load_data()
index = VectorStoreIndex.from_documents(docs)
qe = index.as_query_engine(similarity_top_k=4)
Pin Settings once at app boot, never inline. This eliminates the entire embedding-mismatch failure class (failure #4).
from llama_index.core.evaluation import (
DatasetGenerator, FaithfulnessEvaluator,
RelevancyEvaluator, RetrieverEvaluator,
)
qa = DatasetGenerator.from_documents(docs).generate_dataset_from_nodes(num=50)
Track {MRR, hit-rate, faithfulness, relevancy, p95 latency}. Every subsequent change must be gated on these numbers.
> Most RAG failures in production trace to weak retrieval or sloppy ingestion — not the LLM. The eval loop is what surfaces them.
From the official basic_strategies guide:
HierarchicalNodeParser+AutoMergingRetriever *or* SentenceWindowNodeParserNote the order: prompts first, reranking last. Reranking is high-impact but expensive — exhaust cheap knobs first.
| Query shape | Right primitive |
|---|---|
| "Summarize doc X" | SummaryIndex per doc, routed |
| "Find the clause about X" | VectorStoreIndex + metadata filters |
| "Compare X and Y across docs" | SubQuestionQueryEngine |
| "What entities relate to X?" | PropertyGraphIndex |
| Mixed | RouterQueryEngine over per-task engines |
Apply the failure-mode checklist (R4). Top 5 non-negotiables:
IngestionPipeline with docstore + UPSERTS_AND_DELETE for any live corpus.Settings.embed_model pinned at boot; embedding model name in index metadata.tree_summarize synthesizer when packing many chunks (mitigates lost-in-the-middle).query + retrieved_nodes + scores + index_id + LLM prompt for every failure.Escalate when at least one of:
Use Workflows 1.0 (event-driven), not deprecated QueryPipeline. Wrap query engines as QueryEngineTools and tune the description= carefully — it is the only signal the router/agent reads.
Each operation: Trigger / Action / Output / Evidence.
VectorStoreIndex.from_documents() with SentenceSplitter(1024, 20), top_k=4, default synthesizer. Ship to eval bench *before* tuning.developers.llamaindex.ai/python/framework/optimizing/basic_strategies/basic_strategies/chunk_size ∈ {256, 512, 1024, 2048} with overlap at ~10-20%; re-evaluate faithfulness + relevancy + latency. Default land: 1024 for prose, 80-160 for code.chunk_size pinned + embedding model version locked in index metadata.llamaindex.ai/blog/evaluating-the-ideal-chunk-size-for-a-rag-system-using-llamaindex-6207e5d3fec5 (faithfulness peaked at 1024 in LlamaIndex's own eval on Uber 10-K).CohereRerank or SentenceTransformerRerank as a NodePostprocessor; widen retrieval top_k to 20-50, narrow to top_n=3-5 after rerank.developers.llamaindex.ai/python/framework/optimizing/rag_failure_mode_checklist/ (#1, #10).QueryFusionRetriever([vector_retriever, BM25Retriever]) *or* vendor hybrid (Qdrant/Milvus alpha). Tune alpha per query type, not globally.llamaindex.ai/blog/llamaindex-enhancing-retrieval-performance-with-alpha-tuning-in-hybrid-search-in-rag-135d0c9b8a00; BM25Retriever docs.HierarchicalNodeParser + AutoMergingRetriever (for structured docs) *or* SentenceWindowNodeParser + MetadataReplacementPostProcessor (for flat prose). Embed small, return large.developers.llamaindex.ai.QueryEngines (SummaryIndex for digest, VectorStoreIndex for lookup, SubQuestionQueryEngine for compare) + a RouterQueryEngine with LLM or Pydantic selector. Carefully author each QueryEngineTool.description.SubQuestionQueryEngine decomposes query → dispatches sub-questions to sub-engines → synthesizes.developers.llamaindex.ai sub-question query engine docs.IngestionPipeline(transformations=..., docstore=..., vector_store=..., docstore_strategy=UPSERTS_AND_DELETE). Run on a schedule, not manually.developers.llamaindex.ai/python/framework/module_guides/loading/ingestion_pipeline/; failure #3.tenant, doc_type, date); apply MetadataFilters at query time OR enable auto-retrieval to let an LLM emit filters.basic_strategies metadata filters section.DatasetGenerator → labeled QA pairs; run FaithfulnessEvaluator + RelevancyEvaluator + RetrieverEvaluator(["mrr","hit_rate"]). Gate every change.developers.llamaindex.ai/python/framework-api-reference/evaluation/; cookbook.openai.com/examples/evaluation/evaluate_rag_with_llamaindex.Settings.llm and Settings.embed_model once in app bootstrap. Forbid inline overrides in PR review.docs.llamaindex.ai/en/stable/module_guides/supporting_modules/service_context_migration/.FunctionAgent/ReActAgent with QueryEngineTools. Do NOT use the deprecated QueryPipeline.llamaindex.ai/blog/announcing-workflows-1-0-a-lightweight-framework-for-agentic-systems.(Full text in references/R3-dilemma-cases.md. Summarized here.)
困境: Small chunks → precise embeddings, fragmented context for the LLM. Large chunks → rich context, embeddings become "topic averages", recall on specific queries drops. Failure modes #2 and #6 are the two poles.
约束: Embedding model has a fixed input window; metadata is propagated into payload (so very small chunks become all-metadata — GitHub #12200, #13792); token budget caps how many chunks fit downstream.
决策步骤:
chunk_size ∈ {128, 256, 512, 1024, 2048} with overlap = 10-20%.结果: LlamaIndex's own published study (Uber 10-K) peaked at 1024 on both faithfulness and relevancy → 1024 became the framework default for prose. For code: 80-160 tokens. When the eval doesn't converge, decoupling wins; never average two bad chunk_sizes.
可提取的操作: OP-02 TuneChunkSize, OP-05 DecoupleChunkScope. Anti-pattern A1.
困境: Adding hybrid doubles index footprint, requires per-query-type alpha tuning, complicates the pipeline. Worth it?
约束: Dense embeddings *silently fail* on identifiers, error strings, code, SKUs — they "destroy lexical identity by pooling token representations" (TianPan, 2026). BM25 scores against an inverted token index.
决策步骤:
结果: Hybrid lifts the lexical slice without hurting the semantic slice — *if alpha is tuned per type*. A single global alpha often underperforms dense, which is why some teams wrongly conclude "hybrid didn't help".
可提取的操作: OP-04 AddHybridBM25. Decision is traffic-driven, not theoretical.
困境: User adds compare/summary/lookup queries to a basic RAG. Three options:
RouterQueryEngine over per-task engines.FunctionAgent/ReActAgent with engines as tools.SubQuestionQueryEngine to decompose.约束: Agents add ≥1 LLM round-trip per step (latency); introduce planning errors a router cannot make; harder to debug (failure #12); most queries aren't multi-hop in practice.
决策步骤:
QueryEngineTool.description — it's the only signal the router/agent sees.结果: DeepLearning.AI's official course ladder is Router → Agent. Production guidance consistently warns against premature agentization. Workflows 1.0 (2025) signals: when you need agency, use the agentic primitive, don't fake it with DAG pipelines.
可提取的操作: OP-06 RouteByQueryType, OP-07 DecomposeMultiHop, OP-12 AgenticWorkflow. Anti-pattern A9.
困境: Does a 1M-token context window eliminate the need for RAG?
约束 (from llamaindex.ai/blog/towards-long-context-rag): 1M tokens ~60s latency + $0.50-$20/query; 10M tokens still doesn't cover large corpora; "lost in the middle" degrades quality by ~30%.
决策步骤:
结果: Long context does not replace RAG; it changes what RAG looks like. The bottleneck shifts from "fitting context" to "feeding right context in the right position" — making rerank + position-aware synthesis (tree_summarize) more important, not less.
可提取的操作: For any corpus >500k tokens or latency <5s: keep RAG. Use long-context as synthesis-stage capacity.
困境: Both implement "embed small, return large". Not interchangeable.
决策步骤:
结果: Both beat naive top-k on faithfulness. Match parser/retriever pair to document structure, not theoretical elegance. Always pair SentenceWindowNodeParser with MetadataReplacementPostProcessor.
references/R4-anti-patterns.md)| # | Anti-pattern | Correct move |
|---|---|---|
| A1 | Bump chunk_size when answers feel incomplete | Decouple embed-scope from synthesis-scope (Hierarchical / SentenceWindow) |
| A2 | Swap embedding model without re-embed | Rebuild index; tag artifact with embed model name+version |
| A3 | No eval loop; debug by anecdote | Stand up RetrieverEvaluator + FaithfulnessEvaluator + RelevancyEvaluator first |
| A4 | ServiceContext + manual config in every module | Pin Settings.llm and Settings.embed_model once at boot |
| A5 | QueryPipeline DAG for agentic logic | Use Workflows 1.0 (event-driven, supports cycles) |
| A6 | Naive top_k=N, no reranker | Widen top_k + add CohereRerank / SentenceTransformerRerank |
| A7 | Metadata not propagated to chunks; or metadata > 50% of chunk_size | Design metadata schema before ingestion; budget metadata tokens |
| A8 | Multi-modal RAG by base64-stuffing images into text | Use LlamaParse + multi-modal retrieval primitives |
| A9 | Wrap retrieval in a custom agent when a Router suffices | Default to RouterQueryEngine; escalate to Agent only with justification |
| A10 | Ingest once at deploy, never reconcile | IngestionPipeline + docstore + UPSERTS_AND_DELETE |
from llama_index import ServiceContext → A4.index.as_query_engine(similarity_top_k=20) without a rerank postprocessor → A6.SentenceSplitter(chunk_size=4096) → likely A1.Settings.embed_model = ... in >1 file → A4 drift.IngestionPipeline(...) without docstore= → A10.Workflow with no events or loops → over-engineered; should be a QueryEngine.Q1. Primarily extracting from messy documents (PDFs, slides, tables, scans)?
YES → LlamaIndex (+ LlamaParse) leads.
Q2. Primary challenge is multi-step agentic orchestration with many non-retrieval tools?
YES → LangGraph / CrewAI leads; use LlamaIndex retrievers as tools.
Q3. Corpus small (<100k tokens) and static?
YES → No framework; prompt-stuff with caching.
Q4. Pure structured/tabular data?
YES → SQL/DuckDB/BI. Use LlamaIndex only for hybrid NL2SQL+RAG.
DEFAULT → LlamaIndex remains lead; layer LangGraph only if agentic logic emerges.
| Vs | LlamaIndex wins when | Other wins when |
|---|---|---|
| LangChain | Retrieval quality and ingestion are the bottleneck; document-heavy | Orchestration is complex; many non-retrieval tools |
| Haystack | Modern LLM-centric docs; multi-modal; broader index taxonomy | YAML-configurable pipelines; classical IR feel |
| Raw vector store | Need >2 of {SentenceSplitter, IngestionPipeline, Reranker, Eval, Synthesizer} | Truly minimal RAG; team wants no framework |
| DSPy | Want structured retrieval infrastructure | Want automatic prompt optimization |
| LangGraph (for agents) | Retrieval-heavy with light agency (Workflows ergonomic here) | Many states, complex multi-agent state machines |
| CrewAI / AutoGen | (different category) | Multi-agent collaboration is the goal |
> Most production teams converge on: LlamaIndex for retrieval & ingestion; LangGraph (or LlamaIndex Workflows) for orchestration; LangSmith / Phoenix for observability.
references/R1-architecture.md — 5-layer model deep dive, Index taxonomy, Settings/Workflowsreferences/R2-sop-workflow.md — full 8-stage RAG bootstrap protocolreferences/R3-dilemma-cases.md — 5 dilemma cases in fullreferences/R4-anti-patterns.md — 13 official failure modes + 10 anti-patterns + boundariesreferences/R5-ecosystem-context.md — comparison matrix, hybrid patternsintermediate/operation_candidates.json — machine-readable operation listdevelopers.llamaindex.ai/python/framework/ (architecture homepage)developers.llamaindex.ai/python/framework/optimizing/basic_strategies/basic_strategies/developers.llamaindex.ai/python/framework/optimizing/rag_failure_mode_checklist/ (official 13 failure modes)developers.llamaindex.ai/python/framework/module_guides/indexing/index_guide/developers.llamaindex.ai/python/framework/module_guides/loading/ingestion_pipeline/llamaindex.ai/blog/evaluating-the-ideal-chunk-size-for-a-rag-system-using-llamaindex-6207e5d3fec5llamaindex.ai/blog/llamaindex-enhancing-retrieval-performance-with-alpha-tuning-in-hybrid-search-in-rag-135d0c9b8a00llamaindex.ai/blog/towards-long-context-ragllamaindex.ai/blog/announcing-workflows-1-0-a-lightweight-framework-for-agentic-systemsdocs.llamaindex.ai/en/stable/module_guides/supporting_modules/service_context_migration/github.com/run-llama/llama_index (README, issues #12200, #13792, #6465)cookbook.openai.com/examples/evaluation/evaluate_rag_with_llamaindexlearn.deeplearning.ai/courses/building-agentic-rag-with-llamaindex/ibm.com/think/topics/llamaindex-vs-langchainstatsig.com/perspectives/llamaindex-rag-retrievaltianpan.co/blog/2026-04-12-hybrid-search-production-bm25-dense-embeddingsTake agentsope/agentsop-llamaindex from the repository into ~/.claude/skills for personal
use, or into .claude/skills inside a project.
The agent identifies a skill by the name field in its header. Two skills with the
same name cannot sit side by side — one of them will be ignored.