Sub topic 9
LlamaIndex: data-centric retrieval
This chapter covers what LlamaIndex does, how its pieces map to the hand-written retrieval pipeline from the earlier chapter, and where it saves code or gets in the way.
Prerequisites. You should know basic Python and what embeddings and retrieval-augmented generation (RAG) are. You should also have read the chapter on building RAG by hand, because this chapter maps LlamaIndex's pieces onto the steps you wrote there.
The design focus: data first
LangChain centers on composing components. PydanticAI centers on typed agents. LlamaIndex centers on your data. Its core job is to get documents from many sources into a form a model can search, and then to answer questions over them.
A hand-written RAG pipeline has these stages:
- Load files or records.
- Split them into chunks.
- Embed each chunk.
- Store the vectors.
- Embed the question, find similar chunks, and build a prompt.
- Call the model.
LlamaIndex has an object for each stage. That is why a full pipeline fits in a few lines.
The five-line pipeline
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex
documents = SimpleDirectoryReader("data").load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()
print(query_engine.query("What does the onboarding guide say about access requests?"))To run this, install llama-index, put some files in a data folder, and set OPENAI_API_KEY. The default settings use OpenAI models for both embeddings and answer generation. Without a key, the call fails.
Each line hides a stage:
| Line | What it does | Stage in a manual pipeline |
|---|---|---|
| `SimpleDirectoryReader("data").load_data()` | Reads files such as text, PDF, and Markdown into `Document` objects | Loading |
| `VectorStoreIndex.from_documents(documents)` | Splits documents into nodes, embeds them, and stores the vectors in memory | Chunking, embedding, storing |
| `index.as_query_engine()` | Wraps a retriever and a response synthesizer | Retrieval and prompt building |
| `query_engine.query(...)` | Embeds the question, retrieves chunks, and calls the model | Search and generation |
The vocabulary
LlamaIndex uses its own names. Knowing them makes the documentation and error messages readable.
- Document: a whole source item, such as one PDF, with its text and metadata.
- Node: a chunk of a document. Nodes keep a link to their source document and to neighboring nodes. This is the unit that gets embedded and retrieved.
- Index: a structure built over nodes so they can be searched.
VectorStoreIndexis the most common. - Retriever: takes a query and returns the most relevant nodes.
- Response synthesizer: takes the query and retrieved nodes and produces the final answer, usually through one or more model calls.
- Query engine: a retriever plus a synthesizer behind one
query()method. - Settings: a global object that holds the default model, embedding model, and chunking parameters.
Taking control of each stage
The short version uses defaults. In real projects the defaults are the first thing you change. The same pipeline with explicit settings looks like this:
from llama_index.core import Settings, SimpleDirectoryReader, VectorStoreIndex
from llama_index.core.node_parser import SentenceSplitter
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.llms.openai import OpenAI
Settings.llm = OpenAI(model="gpt-4o-mini", temperature=0)
Settings.embed_model = OpenAIEmbedding(model="text-embedding-3-small")
Settings.node_parser = SentenceSplitter(chunk_size=512, chunk_overlap=64)
documents = SimpleDirectoryReader("data").load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine(similarity_top_k=4)
response = query_engine.query("What does the onboarding guide say about access requests?")
print(response)
for item in response.source_nodes:
print(item.score, item.node.metadata.get("file_name"))The source_nodes loop is one of the most useful features. The response object carries the chunks that were used and their similarity scores, so you can check what the model saw without extra code. In a hand-written pipeline you would have to return these yourself.
Notes on the parameters:
chunk_sizeandchunk_overlapare measured in tokens, not characters. Smaller chunks give more precise matches but less context per chunk.similarity_top_ksets how many nodes are retrieved. The default is 2, which is often too low for questions that span several passages.- Provider integrations are separate packages, such as
llama-index-llms-openaiandllama-index-embeddings-openai. Swapping providers means installing a different package and changing the class inSettings.
Persisting the index
VectorStoreIndex.from_documents embeds everything on every run, which costs time and money. An in-memory index disappears when the process ends. You can save it to disk and reload it:
from llama_index.core import StorageContext, load_index_from_storage
index.storage_context.persist(persist_dir="storage")
storage_context = StorageContext.from_defaults(persist_dir="storage")
index = load_index_from_storage(storage_context)For larger data, you would plug in an external vector database such as Qdrant, Chroma, or pgvector through a vector store integration. The query code stays the same. Only the storage context changes.
A common error is changing the embedding model after you built the index. Vectors from different models are not comparable, so retrieval quality collapses without raising an error. If you change the embedding model, rebuild the index.
Where LlamaIndex saves the most work
Compared with the manual pipeline, the largest savings are in the parts that are tedious rather than conceptually hard:
- Loaders. Hundreds of connectors exist for PDFs, web pages, databases, Notion, Google Drive, and more. Writing and maintaining parsers yourself is slow.
- Chunking. Sentence-aware splitters, Markdown and code splitters, and hierarchical splitters are ready to use.
- Metadata. Source file names, page numbers, and custom fields travel with each node, and you can filter on them at query time.
- Retrieval variants. Hybrid search, re-ranking, and auto-merging retrieval are built in or available as add-ons.
- Response modes. The synthesizer can refine an answer across chunks or summarize them as a tree, which matters when retrieved text exceeds the context window.
Where it costs you
- Hidden prompts. The synthesizer uses default prompt templates that you did not write. Answers can differ from what you expect until you read them. You can inspect them with
query_engine.get_prompts()and replace them withupdate_prompts. - Hidden model calls. Some response modes make several LLM calls per query. The
refinemode, for example, calls the model once per chunk. Cost and latency grow withsimilarity_top_k. - Package sprawl. The core package is separate from each integration. Version mismatches between them are a common source of import errors.
- Churn. Import paths changed significantly between early versions and the
llama_index.corelayout. Older tutorials often fail to run. Pin versions in your requirements file. - Fit. If your problem is not retrieval over documents, such as a pure tool-calling agent, LlamaIndex adds concepts you do not need. It does have agent and workflow features, but its strength is data handling.
Using it with other approaches
LlamaIndex does not require you to adopt it for everything. A common pattern is to use only the retriever and keep your own generation code:
retriever = index.as_retriever(similarity_top_k=4)
nodes = retriever.retrieve("What does the onboarding guide say about access requests?")
context = "\n\n".join(item.node.get_content() for item in nodes)You then build the prompt and call the provider SDK yourself. This keeps full control of the prompt and the model call while borrowing the loaders, chunkers, and vector store handling. It is also a low-risk first step if you are migrating from a hand-written pipeline.
When to choose LlamaIndex
Choose it when:
- Your sources are varied, such as PDFs, wikis, and databases, and writing loaders would dominate your effort.
- Retrieval quality is the main problem, and you want to try different chunking, re-ranking, or hybrid search quickly.
- You want source tracking without writing it yourself.
Avoid it, or use only part of it, when:
- Your data is a small set of clean text files, where a manual pipeline is short and fully visible.
- You need exact control over every prompt and every model call.
- You cannot accept the dependency footprint.
Exercise
A team builds an index with text-embedding-3-small. Later they change Settings.embed_model to a different embedding model and keep querying the saved index. What happens, and what should they do?
Show answer
Queries are embedded with the new model, but the stored vectors came from the old one. The two sets of vectors are not comparable, so retrieval returns poor matches, usually without an error. They should rebuild the index with the new embedding model, which means re-embedding all documents.
Exercise
You already have a tested prompt and call the provider SDK directly. You want LlamaIndex's PDF loading and chunking but nothing else. Which LlamaIndex objects do you use, and which do you skip?
Show answer
Use SimpleDirectoryReader (or another reader), a node parser such as SentenceSplitter, and a VectorStoreIndex with as_retriever. Skip as_query_engine and the response synthesizer. Build the context string from the retrieved nodes and send it to the provider SDK with your own prompt.