Where Blockchain Solutions for Digital Payments Are Technically Headed Over the Next Five Years
ZK rollups, MiCA compliance, and account abstraction are reshaping blockchain financial transactions. Here's the full 5-year...
Your RAG pipeline ran. No errors. Documents loaded. Query executed. The answer landed — and it had nothing to do with what the user actually asked.
A Python RAG application using LlamaIndex connects a document retrieval layer to an LLM — when that retrieval layer breaks, the model answers confidently from the wrong evidence. The failure is almost never random. It falls into predictable patterns, and most of them happen before the language model ever sees your data. The root causes almost always come down to three things: how you chunk your documents, which embedding model you’re using, and whether you’re reranking at all.
This post breaks down each failure mode at the code level — with working LlamaIndex fixes for each — using Ollama for local development and vLLM for production inference.
Before you can diagnose what’s broken, you need a clear picture of where things can go wrong.
The retrieval chain looks like this:
Documents → Chunk + Index → [Vector Store]
↑
User Query → Embed Query → Vector Search → Rerank → Synthesize → Answer
Three things happen at index time: chunking, embedding, and storage. Three things happen at query time: embedding (again), vector search, and synthesis. The failure surfaces map directly to that chain — chunking at index time, embedding at both times, and ranking at retrieval time.
Here’s the thing: most developers only look at the synthesis step when results are bad. The LLM gets blamed. But the LLM can only work with what retrieval hands it.
Fixed-size chunking is the default. It’s also the source of more retrieval failures than anything else.
When you split a document every 1,024 tokens without regard for sentence or paragraph boundaries, you end up with chunks that start mid-sentence, cut off explanations, and orphan context. A chunk that reads “…which is why the configuration flag must be set before initialization. The second approach involves…” is useless in isolation — neither half makes sense without the other.
Too-small chunks lose surrounding meaning. Too-large chunks dilute relevance scores so badly that a chunk containing your exact answer registers lower similarity than one that just mentions the same topic repeatedly. Either way, retrieval quietly degrades and the LLM takes the blame.
The fastest diagnostic is to read what the retriever actually returns:
retriever = index.as_retriever(similarity_top_k=5)
nodes = retriever.retrieve("your test query")
for i, node in enumerate(nodes):
print(f"--- Node {i+1} ---")
print(node.text)
print(f"Score: {node.score}")
If your retrieved text contains partial sentences, abrupt starts, or half-answered ideas — your chunking is the problem. The right answer might be on the correct page but in the wrong passage.
Replace the default splitter with SentenceWindowNodeParser. Instead of slicing at character counts, it indexes individual sentences but stores a configurable window of surrounding sentences as metadata. At query time, you swap the narrow indexed sentence back out for its full window — so the LLM sees context, not fragments.
from llama_index.core.node_parser import SentenceWindowNodeParser
from llama_index.core.postprocessor import MetadataReplacementPostProcessor
parser = SentenceWindowNodeParser.from_defaults(
window_size=3,
window_metadata_key="window",
original_text_metadata_key="original_text",
)
nodes = parser.get_nodes_from_documents(documents)
# At query time, replace indexed sentence with full window
postprocessor = MetadataReplacementPostProcessor(
target_metadata_key="window"
)
query_engine = index.as_query_engine(
node_postprocessors=[postprocessor]
)
For code files or technical documentation with rigid structure, swap to CodeSplitter instead — it respects function and class boundaries rather than sentence boundaries.
I’ve watched teams spend days tuning chunk sizes and top-k values, completely stuck, because they never questioned the default embedding model. The problem was that they were indexing medical documentation using a general-purpose embedding model that had never seen clinical language at meaningful density. Cosine similarity scores looked reasonable. The retrieved chunks were semantically adjacent but practically useless.
LlamaIndex defaults to OpenAI’s text-embedding-ada-002. For general English prose, it’s fine. For domain-specific corpora — code, legal text, scientific papers, internal documentation with proprietary terminology — it underperforms in ways that are easy to miss because the failure is gradual and the scores aren’t obviously wrong.
Compute cosine similarity manually between a known-good query and its expected node:
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
query_embedding = embed_model.get_query_embedding("your test query")
node_embedding = embed_model.get_text_embedding(expected_node_text)
similarity = cosine_similarity(
[query_embedding], [node_embedding]
)[0][0]
print(f"Similarity: {similarity:.4f}")
If similarity between a query and its obviously correct answer is below 0.70, the embedding space itself is misaligned. Also check that Settings.embed_model is identical between index build time and query time — a mismatch there causes silent, consistent degradation. This one trips up a surprising number of people who index with one model and query with another after a config change.
For local development with Ollama, nomic-embed-text is a strong general-purpose choice that keeps your entire stack offline and free:
from llama_index.embeddings.ollama import OllamaEmbedding
from llama_index.core import Settings
# Local development — fully offline
Settings.embed_model = OllamaEmbedding(model_name="nomic-embed-text")
For production, you can serve embedding models through vLLM’s OpenAI-compatible endpoint with GPU batching and much higher throughput than a local Ollama instance:
from llama_index.embeddings.openai import OpenAIEmbedding
# Production — vLLM-served embedding endpoint
Settings.embed_model = OpenAIEmbedding(
model="BAAI/bge-large-en-v1.5",
api_base="http://your-vllm-host:8000/v1",
api_key="not-needed",
)
The pattern here — Ollama locally, vLLM in production — keeps iteration fast without introducing dev/prod embedding drift. Use the same model name in both environments. Here’s how the two tools compare across the dimensions that matter most:
| Ollama | vLLM | |
|---|---|---|
| Best for | Local dev, rapid iteration | Production serving at scale |
| Hardware requirement | CPU or consumer GPU | Dedicated GPU strongly recommended |
| Setup | ollama pull <model> | Docker + GPU drivers + model weights |
| Request throughput | Single / low concurrency | Batched, high concurrency |
| Cost | Free | Infrastructure cost |
| LlamaIndex integration | OllamaEmbedding | OpenAIEmbedding (compatible API) |
Neither is strictly better — they serve different jobs. Ollama handles local development with zero friction; vLLM handles the production load that would crush it.
This is the one most teams skip, and the one that produces the most dramatic improvements when added.
Vector search is fast and approximate. It returns the chunks whose embeddings are closest to your query embedding in high-dimensional space. But “close in embedding space” isn’t the same as “actually answers the question.” A chunk that mentions your query terms in passing can outscore a chunk that directly answers the question, just because of how the embedding space is shaped.
The classic symptom: your correct answer is sitting at position 4 or 5 in the retrieved list, but your query engine only passes the top 3 to the LLM.
Bump similarity_top_k to 10, retrieve, and read the results in ranked order:
retriever = index.as_retriever(similarity_top_k=10)
nodes = retriever.retrieve("your diagnostic query")
for i, node in enumerate(nodes):
print(f"Rank {i+1} | Score: {node.score:.4f}")
print(node.text[:200])
print()
If the chunk that actually answers your query consistently shows up at rank 3–6 while less relevant chunks rank above it, reranking will fix this.
And raising top_k without reranking isn’t the answer — you’ll just give the LLM more noise and a longer context window to get lost in.
Cross-encoders score query-document pairs directly rather than comparing separate embeddings. They’re slower, which is why you don’t use them for the initial retrieval sweep — but applied to a small candidate set (say, top 10), the accuracy gain is significant.
from llama_index.core.postprocessor import SentenceTransformerRerank
reranker = SentenceTransformerRerank(
model="cross-encoder/ms-marco-MiniLM-L-2-v2",
top_n=3,
)
query_engine = index.as_query_engine(
similarity_top_k=10,
node_postprocessors=[reranker],
)
Watch the latency hit in production. The MiniLM cross-encoder adds roughly 50–100ms per query on CPU. If that’s acceptable, great. If not, cache reranked results for repeated queries, or gate reranking on queries above a certain complexity threshold.
Each fix above is independent. But they also compose cleanly, and the full stack is worth seeing in one place:
from llama_index.core import VectorStoreIndex, Settings
from llama_index.core.node_parser import SentenceWindowNodeParser
from llama_index.core.postprocessor import (
MetadataReplacementPostProcessor,
SentenceTransformerRerank,
)
from llama_index.embeddings.ollama import OllamaEmbedding
# Chunking
parser = SentenceWindowNodeParser.from_defaults(
window_size=3,
window_metadata_key="window",
original_text_metadata_key="original_text",
)
# Embeddings (swap OllamaEmbedding for OpenAIEmbedding + vLLM in prod)
Settings.embed_model = OllamaEmbedding(model_name="nomic-embed-text")
# Build index
nodes = parser.get_nodes_from_documents(documents)
index = VectorStoreIndex(nodes)
# Query engine with reranking + window replacement
query_engine = index.as_query_engine(
similarity_top_k=10,
node_postprocessors=[
MetadataReplacementPostProcessor(target_metadata_key="window"),
SentenceTransformerRerank(
model="cross-encoder/ms-marco-MiniLM-L-2-v2",
top_n=3,
),
],
)
For the generation step in production, Python LLM inference optimization with vLLM gives you batched requests, quantized model support, and tensor parallelism — wire it up through LlamaIndex’s OpenAILike LLM class pointing at your vLLM endpoint. The retrieval architecture above works regardless of which LLM you’re using for synthesis.
Inconsistent retrieval quality usually points to embedding variance or chunk boundary problems. Some queries happen to land close to well-formed chunks in embedding space; others don’t. Start by logging retrieved node scores across a range of test queries — if the variance in scores is high, your chunking strategy or embedding model alignment is likely the root cause rather than a query-specific issue.
Ollama is a tool for running LLMs locally with minimal setup — ideal for development iterations where you want zero API costs and offline capability. vLLM is built for serving models at scale with GPU optimization, continuous batching, and production-grade throughput. A practical workflow uses Ollama locally with the same model family you plan to deploy, then switches to a vLLM-served endpoint in production. The LlamaIndex integration for both uses the same interface, so switching is a one-line change.
Run an A/B comparison on a fixed set of test queries. Retrieve with similarity_top_k=10, record which rank contains the correct answer, then apply reranking and record the post-rerank position. If the correct answer moves from rank 4–6 to rank 1–2 consistently across your test set, reranking is worth the latency cost. LlamaIndex’s RetrieverEvaluator can automate this measurement with a labeled evaluation dataset.
Yes, and they’re additive rather than redundant — each addresses a different stage of the retrieval pipeline. Better chunking improves what gets indexed, better embeddings improve how queries map to those chunks, and reranking improves which of the retrieved candidates actually reaches the LLM. Apply them in that order when diagnosing, since a chunking problem can mask embedding issues and both can mask reranking value.
The fixes in this post aren’t theoretical. They’re the things that actually move the needle on a broken RAG pipeline — and each one is diagnosable with a few print statements before you write a single line of fix code.
Start by instrumenting your retrieval: log node text, scores, and ranks for a set of representative queries. That data will tell you which failure mode you’re dealing with. Then apply the corresponding fix, measure again, and move on. If you’re running a Python RAG application using LlamaIndex in production and haven’t added reranking yet, that’s where I’d start — it’s the most impactful change with the least code.
Tell us about your product, platform, or business software requirement. We will suggest the right team structure, roadmap, and engagement model within 48 hours.