RAG with LlamaIndex

Index documents and query them with LlamaIndex's high-level and low-level APIs.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 17 · Lesson 2 of 4 · Intermediate

RAG with LlamaIndex

Index documents and query them with LlamaIndex's high-level and low-level APIs.

LlamaIndex is a framework built specifically around connecting LLMs to data. Where LangChain is a general toolkit for LLM applications, LlamaIndex focuses on ingestion, indexing and querying, with many ready-made retrieval strategies. This lesson builds the basic pipeline with its high-level API, then customises it with the lower-level components.

pip install llama-index-core llama-index-llms-anthropic llama-index-embeddings-huggingface llama-index-postprocessor-sbert-rerank

RAG in a few lines

li_rag.py
from llama_index.core import Settings, SimpleDirectoryReader, VectorStoreIndex
from llama_index.core.node_parser import SentenceSplitter
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.anthropic import Anthropic

# Global defaults used by every index and query engine
Settings.llm = Anthropic(model="claude-opus-5-5", max_tokens=2000)
Settings.embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")
Settings.node_parser = SentenceSplitter(chunk_size=512, chunk_overlap=64)

documents = SimpleDirectoryReader("docs").load_data()     # PDFs, DOCX, TXT, MD and more
index = VectorStoreIndex.from_documents(documents)
index.storage_context.persist(persist_dir="li_storage")     # save to disk

query_engine = index.as_query_engine(similarity_top_k=4)
response = query_engine.query("How many days of sick leave do employees get?")
print(response)
for source in response.source_nodes:
    print(f"  {source.score:.3f}  {source.node.metadata.get('file_name')}")

Reload a persisted index later without re-embedding:

from llama_index.core import StorageContext, load_index_from_storage

index = load_index_from_storage(StorageContext.from_defaults(persist_dir="li_storage"))

Key concepts

LlamaIndex termMeaning in this tutorial
DocumentA loaded source file with metadata
NodeA chunk, with links to its document and neighbours
Node parserA chunker (sentence, semantic, Markdown, hierarchical)
IndexA searchable structure over nodes (vector, keyword, summary, property graph)
RetrieverReturns nodes for a query
Node postprocessorReranking, filtering and reordering after retrieval
Response synthesizerBuilds the prompt and generates the answer
Query engineRetriever + postprocessors + synthesizer

Customising: retriever, reranker and synthesizer

The high-level as_query_engine() is built from components you can configure individually. Here, retrieval fetches 20 candidates, a cross-encoder reranks them to 4 (see Reranking), and a custom prompt template controls the answer.

from llama_index.core import PromptTemplate
from llama_index.core.query_engine import RetrieverQueryEngine
from llama_index.core.response_synthesizers import get_response_synthesizer
from llama_index.core.retrievers import VectorIndexRetriever
from llama_index.postprocessor.sbert_rerank import SentenceTransformerRerank

qa_template = PromptTemplate(
    "Sources:\n{context_str}\n\n"
    "Answer the question using only the sources, and name the file you used. "
    "If the sources do not contain the answer, say you don't know.\n"
    "Question: {query_str}\nAnswer: "
)

engine = RetrieverQueryEngine(
    retriever=VectorIndexRetriever(index=index, similarity_top_k=20),
    node_postprocessors=[SentenceTransformerRerank(model="BAAI/bge-reranker-base", top_n=4)],
    response_synthesizer=get_response_synthesizer(text_qa_template=qa_template),
)
print(engine.query("Is a medical certificate needed for two days of sick leave?"))

Built-in advanced techniques

Many techniques from this tutorial are available as components:

  • Hierarchical / parent-child chunking: HierarchicalNodeParser with AutoMergingRetriever.
  • Sentence-window retrieval: SentenceWindowNodeParser with MetadataReplacementPostProcessor.
  • Semantic chunking: SemanticSplitterNodeParser.
  • Hybrid and fusion retrieval: QueryFusionRetriever (multi-query with reciprocal rank fusion) and BM25 retrievers.
  • Routing: RouterQueryEngine to pick between indexes.
  • Sub-question decomposition: SubQuestionQueryEngine.
  • Knowledge graphs: PropertyGraphIndex.
  • Agents and workflows: agent classes that use query engines as tools, and an event-driven Workflow API for custom multi-step pipelines.
Model support and parameters

Framework integrations keep internal tables of model names and send default generation settings. Use a recent version of llama-index-llms-anthropic so newer model IDs are recognised. Current Claude models reject temperature, top_p and top_k; if you get an error about one of them, upgrade the integration or configure it not to send that parameter.

Key takeaways

  • LlamaIndex is data-focused: documents become nodes, nodes go into indexes, and query engines answer questions.
  • The high-level API builds a working pipeline in a few lines; persist the index to avoid re-embedding.
  • Customise with retrievers, node postprocessors (rerankers) and prompt templates.
  • Many advanced RAG techniques are available as ready-made components.