RAG Context Window Management: Chunking to Reranking

How to control what a RAG pipeline puts in the prompt: chunk size and overlap, top-k, reranking, contextual retrieval, ordering and token budgets.

By AI Agents DirectoryLast checked
Abstract illustration of a humanoid robot face

In a RAG system the model only knows what you put in front of it, so most quality problems come down to a handful of choices: how documents are cut into chunks, how many chunks you pull back, which of those survive a second relevance pass, what order they appear in, and how many tokens you are willing to spend on them. This guide walks through each decision with the official documentation for LlamaIndex, LangChain, sentence-transformers and Cohere, plus Anthropic’s write-up on contextual retrieval and the “lost in the middle” paper.

General context-window techniques that are not specific to retrieval (token counting, prompt caching, compacting chat history) are covered in LLM context window optimization techniques. Narrowing the search space before retrieval is covered in metadata filtering in vector search.

The pipeline at a glance

StageDecisionTypical tool
IngestChunk size, overlap, split on structureLangChain text splitters, LlamaIndex node parsers
Ingest (optional)Add document context to each chunkContextual retrieval with an LLM
RetrieveHow many candidates (top-k), hybrid or dense onlyVector store, BM25
Post-processRerank, cut low scores, dedupe, compressCross-encoder, Cohere Rerank, LlamaIndex postprocessors
AssembleOrder and token budgetLongContextReorder, your own prompt builder

Chunking: size and overlap

LangChain’s docs describe the job of a text splitter plainly: produce pieces that can be retrieved on their own and that respect the model’s context limit. For general text they suggest starting with RecursiveCharacterTextSplitter. It works through a list of separators, by default blank lines, then newlines, then spaces, then individual characters, so paragraphs stay whole when they fit, and it only falls back to sentences and words when a paragraph is too long.

Two parameters matter most. chunk_size is the upper bound on a chunk, measured by whatever length function you pass in (LangChain also shows a tiktoken-based splitter that counts tokens instead of characters). chunk_overlap repeats a little text across neighbouring chunks so a fact that straddles a boundary is not lost.

LlamaIndex’s SentenceSplitter takes the same two settings, and the framework’s defaults are a chunk size of 1024 with an overlap of 20. Its tuning guide spells out the trade-off: smaller chunks give more precise embeddings, larger ones give more general embeddings that can skip fine detail. Changing either value means re-embedding the corpus. The guide also links chunk size to retrieval depth. If you halve chunk size, raise similarity_top_k so each query still pulls back roughly the same amount of text (its example moves from the default of 2 to 4).

Anthropic’s contextual retrieval post lists chunk size, boundaries and overlap among the factors that affect retrieval performance, and notes that RAG chunks are usually at most a few hundred tokens. None of these sources gives one correct number. Pick a starting point, then measure on your own queries.

Structure-aware splitting

Fixed-length splits ignore headings, lists and code. When documents carry structure, splitting along it usually keeps related text together, a point LangChain’s splitter overview makes for HTML, Markdown and JSON.

  • Markdown: LangChain’s MarkdownHeaderTextSplitter cuts at the headers you list and stores the header path (for example Header 1: Foo, Header 2: Bar) in each chunk’s metadata. You can then run a recursive splitter inside each section with split_documents; overlap is applied within a section and never crosses a section boundary.
  • HTML and code: LlamaIndex has an HTMLNodeParser that keeps text from chosen tags (paragraphs, headings, list items and a few others by default) and a CodeSplitter that splits source code according to its language, with a line-based overlap setting.
  • Semantic breakpoints: LlamaIndex’s SemanticSplitterNodeParser chooses split points between sentences by embedding similarity rather than a fixed length, so each chunk holds sentences that belong together. You may need to tune its breakpoint threshold.
  • Small to big: SentenceWindowNodeParser embeds single sentences but keeps neighbouring sentences in metadata. A MetadataReplacementPostProcessor then swaps in that wider window before the text reaches the LLM.

The header metadata produced by structure-aware splitters doubles as filter fields, which ties back to metadata filtering.

Contextual retrieval

Chunking strips a passage from its surroundings. Anthropic’s example is an SEC filing chunk that mentions revenue growth without saying which company or quarter it refers to. Such a chunk is hard to retrieve and hard to use.

Anthropic’s fix, published in September 2024, is to have an LLM write a short note for every chunk that places it within the whole document, then prepend that note before embedding the chunk and before building the BM25 keyword index. They call the two halves Contextual Embeddings and Contextual BM25. Their prompt passes the full document plus the chunk and asks only for the situating context, which typically comes out at 50 to 100 tokens. Because the same document is sent once per chunk, prompt caching keeps the cost down.

The post also explains why it pairs embeddings with BM25. Embeddings capture meaning but can miss exact strings such as an error code, while BM25 matches them; results from both are merged and deduplicated with rank fusion before the top chunks go into the prompt. Anthropic reports that adding context, combining it with BM25, and then reranking each reduced retrieval failures in their tests, and that the gains stacked. The size of those gains depends on their datasets and is best checked against your own.

Retrieval depth and reranking

Top-k is a tension. More chunks raise the odds that the answer is somewhere in the prompt, but Anthropic notes that extra material can also distract the model. In their experiments 20 chunks beat 10 and 5, yet they still tell readers to experiment.

Reranking resolves much of that tension. The sentence-transformers docs describe a two-stage pattern: a fast retriever (a bi-encoder or lexical search) gathers a broad candidate set, around 100 in their example, and a cross-encoder then scores each query and passage pair together. Cross-encoders are generally more accurate than bi-encoders because they attend across query and document at once, but they are slower since every pair needs its own forward pass. That is why they are used on a short candidate list rather than the whole corpus. Anthropic ran the same pattern at a larger scale, reranking 150 candidates down to 20 with Cohere’s reranker.

LlamaIndex’s optimisation guide calls reranking one of the most effective settings for RAG quality. Its recipe, using a local cross-encoder with no API key:

from llama_index.core.postprocessor import SentenceTransformerRerank

reranker = SentenceTransformerRerank(
    model="cross-encoder/ms-marco-MiniLM-L6-v2", top_n=3
)
query_engine = index.as_query_engine(
    similarity_top_k=10,
    node_postprocessors=[reranker],
)

The retriever fetches 10 nodes, the cross-encoder reorders them, and only the best 3 reach the prompt. LlamaIndex warns that SentenceTransformerRerank’s default model was trained for sentence similarity rather than passage ranking, so pass an MS MARCO model explicitly as above. For a hosted option, its docs list CohereRerank, JinaRerank and VoyageAIRerank; LLM-based rerankers can be stronger when latency matters less.

If you use Cohere Rerank directly, two details from its best-practices page help. Relevance scores fall between 0 and 1 and are useful for ordering, but they are not proportional, so a score twice as high does not mean twice as relevant. To pick a cut-off, Cohere suggests scoring a set of borderline query and document pairs from your domain (30 to 50 queries) and using their average as a reference threshold. For structured records, it recommends sending YAML strings and keeping key order, because long documents are truncated.

Trimming and compressing what survives

A few more postprocessors keep the prompt lean.

  • Score cut-off: LlamaIndex’s SimilarityPostprocessor drops nodes below a similarity threshold, so weak matches never enter the prompt even when top-k would include them.
  • Deduplication: when you merge dense and keyword results, deduplicate before reranking, as in Anthropic’s pipeline. For time-sensitive corpora, LlamaIndex’s embedding recency postprocessor sorts by date and removes older nodes that are too similar to newer ones.
  • Sentence-level compression: SentenceEmbeddingOptimizer removes sentences inside each node that are not relevant to the query, using embeddings, with either a percentile or a raw similarity cut-off.

Ordering and the “lost in the middle” effect

Liu and colleagues tested how language models use long inputs on multi-document question answering and key-value retrieval (arXiv 2307.03172, published in TACL). Accuracy was usually best when the relevant passage sat at the start or end of the context and dropped when it was buried in the middle, even for models built for long contexts.

Two practical responses follow. First, send fewer, better chunks, which is what reranking does. Second, when you do need a large top-k, LlamaIndex’s LongContextReorder postprocessor rearranges retrieved nodes so the strongest ones land at the edges of the context rather than in the middle. Where to place the question relative to long documents is covered in the context window optimization guide.

Setting a token budget

Retrieved text competes with the system prompt, the chat history, the question and the room the model needs to answer. A workable approach:

  1. Count the fixed parts of the prompt with your provider’s tokenizer or token-counting endpoint.
  2. Reserve space for the expected output.
  3. Give retrieval a ceiling for what remains, then fill it in reranked order until the next chunk would not fit.
  4. Remember the reranker has limits of its own. Cohere’s newer rerank models share a 32,768-token context between query and document and truncate long documents (to 4,096 tokens per document by default on v5.0), so chunk long files yourself if you want control over what gets scored.

If the whole corpus fits comfortably in the window, consider skipping retrieval. Anthropic’s guidance is that a knowledge base under about 200,000 tokens can simply be included in the prompt, with caching to manage cost.

Where to start

Begin with a recursive or structure-aware splitter at your framework’s defaults, retrieve a generous candidate set, rerank down to a small top-n with a cross-encoder, and drop anything below a calibrated score. Add contextual retrieval and hybrid BM25 search when evaluation shows relevant chunks are being missed. Frameworks such as LlamaIndex ship most of these pieces as node parsers and postprocessors. Whatever you change, rerun the same set of test queries before and after, because every source above stresses that the right settings depend on your data.

#RAG#chunking#reranking#context window#retrieval
AI

Written by AI Agents Directory

Editorial team

Facts in this guide are checked against official documentation and repositories, which are linked in the article.