AlgoViz

Choosing and annotating chunk boundaries

medium 6 min

Chunking selects the unit a retriever can return.

Video lesson · Chapter 1 of 4

The exception on the next strip

0:00 / 3:44

Theory

Read or listen first. About 2 min.

What it is

Chunking selects the unit a retriever can return. A boundary that respects a heading, definition or exception can matter more than a precisely fixed token count. Overlap, parent lookup and metadata provide different ways to restore missing context.

Why it exists

Test splitting against the questions the corpus must answer. Check whether the evidence set contains the entire supporting span, how much irrelevant text was added and how much duplication consumes the prompt budget.

Keep a rule and its holiday exception together

Policy paragraph → Chunk builder (select boundaries). Chunk builder → Holiday question (test evidence coverage)
Policy paragraph → Chunk builder (select boundaries). Chunk builder → Holiday question (test evidence coverage)

Inside this chapter

Chapter sources
The Philosophy of Chunking
Choose the smallest unit that can answer a question without losing essential context. Tiny chunks improve precision but can separate a rule from its exception. Large chunks preserve context while introducing unrelated text. Evaluate boundaries against real questions, including ones whose answers span adjacent paragraphs.

A chunk is the unit the retriever can hand back, so it sets both precision and context. Embeddings of very short chunks match queries sharply but often omit the qualifier that changes the answer. Long chunks dilute the embedding with unrelated subjects, so they score lower and consume prompt budget. There is no universally right size: pick by testing questions whose answers span sentence and paragraph boundaries.

Example. A short result says “returns are allowed.” Fetch the adjacent exception for customized goods and compare answers to the custom-item question.

Another example. In an HR handbook, "Parental leave is 16 weeks" and "for employees with over one year of service" sit in consecutive sentences. A sentence-level splitter returns the first without the second, and the bot tells a new starter they qualify.

Three chunk sizes on the custom-item question

Chunk sizeRetrieved textHas exception?Noise added
1 sentenceReturns are allowed within 30 days.NoLow
1 paragraphReturns allowed ... except customised goods.YesLow
Whole pageReturns ... shipping ... warranty ... gift cardsYesHigh
The paragraph is the smallest unit that answers correctly.
Recursive Character Splitting
Recursive splitting tries coarser separators first and falls back to finer ones when a segment exceeds the target. For prose this may mean paragraphs, then lines, then words. Count size in the same units used by the downstream budget and carry enough overlap to recover cut references.

The splitter tries to cut at the most meaningful separator available. Only a piece that is still too large gets cut again with the next, finer separator, so most paragraphs survive intact and only the occasional giant paragraph is broken mid-way. Overlap (repeating the last few sentences at the start of the next chunk) softens the damage at forced cuts, at the cost of duplicated text in the index and possibly in the prompt.

Example. A paragraph exceeds the target length even after splitting on paragraph separators. Descend to sentence or finer boundaries while retaining provenance.

Fall back to finer separators only when needed

Measure size in tokens of the embedding model, not characters, if the budget is in tokens.
Semantic Chunking
A semantic splitter estimates changes in subject between adjacent segments using embeddings or another similarity signal. A threshold controls when it cuts. A clean topic shift can be a good boundary, but a single sentence containing an exception may look dissimilar to the rule it qualifies.

The splitter embeds each sentence (or small window), measures similarity between neighbours and cuts where it drops below a threshold or a percentile. It works well on documents that drift between subjects. It struggles with short qualifying sentences, negations and exceptions, because they share few words or concepts with the rule. Guard against that with a minimum chunk size or by never cutting immediately after a sentence that ends with a rule.

Example. Place an exception sentence between two paragraphs on different products. Check that the similarity threshold attaches the exception to the rule it qualifies.

Similarity between neighbouring sentences, cut at 0.5

PairSentencesSimilarityDecision
1→2Kettle warranty is 2 years · Covers heating element0.81Keep together
2→3Covers heating element · Except damage from limescale0.44Cut (wrong)
3→4Except damage from limescale · Toasters ship in 3 days0.22Cut
Illustrative scores. The exception looks dissimilar to the rule it qualifies, so a plain threshold separates them.
Agentic Chunking
Agentic chunking asks a model to identify coherent units or decide how to group passages. This can preserve structure in irregular documents at the cost of extra latency, expense and variability. Record the splitter version and verify that repeated indexing preserves coverage and traceable source positions.

A model reads the document and proposes boundaries or groupings, sometimes with a summary title for each chunk. Treat its output like any other non-deterministic component: pin the model and prompt version, store the output, and diff runs. The model should point at source offsets rather than rewrite text, otherwise citations no longer match the original and coverage gaps go unnoticed.

Example. Run the model-guided splitter twice on one policy. Compare coverage, source offsets and cost with a deterministic heading-based split.

Model-guided split

  • Follows irregular structure such as FAQs and memos
  • Can group a rule with a distant exception
  • Produces readable chunk titles

What to watch

  • Extra latency and cost per document
  • Two runs can produce different boundaries
  • Must still emit exact source offsets
Metadata Injection
Attach metadata such as document ID, heading path, effective date, tenant and offsets to every chunk. Keep authorization fields machine-readable. Adding a heading to the text can improve retrieval, but an access label embedded in prose cannot enforce who may read the chunk.

There are two places to put context: inside the text that gets embedded, and in structured fields beside it. Headings and titles help similarity when prepended to the text. Anything that must be enforced or filtered (tenant, permissions, effective date, product) belongs in a typed field that the search engine applies before ranking. Offsets and revision let the interface render a precise citation later.

Example. Attach tenant, revision and heading to a chunk. Verify tenant restriction before retrieval and use heading and revision when rendering the citation.

JSON
{  "chunk_id": "policy-7#s2-c1",  "text": "Returns > Holidays\nItems bought 1-24 Dec may be returned until 31 Jan.",  "metadata": {    "tenant": "acme",    "doc_id": "policy-7",    "revision": 7,    "heading_path": [      "Returns",      "Holidays"    ],    "effective_from": "2026-11-01",    "offset": [      1820,      1904    ]  }}
The heading is prepended to the text to help matching. The tenant is a filterable field, because a label inside prose cannot block anyone.

How it works

Step through the idea, or press Play.

Step 1 of 3

Policy paragraph. Two sentences · one exception

Understand it

Worked example

Keep a rule and its holiday exception together

  1. 1

    Two sentences · one exception

    The first sentence gives a standard 30-day rule. The second starts “except during holidays.” The correct answer depends on both sentences.

  2. 2

    Heading + rule + exception

    Try structural boundaries and then a measured overlap. Preserve source offsets so neighboring material can be fetched when a boundary is unavoidable.

  3. 3

    Check both supporting spans

    Measure whether the evidence set contains both spans. A top-ranked generic rule alone is an incomplete retrieval even if it shares the query’s terms.

Follow the handoffs

Test splitting against the questions the corpus must answer. Check whether the evidence set contains the entire supporting span, how much irrelevant text was added and how much duplication consumes the prompt budget.

Three ways to split the holiday paragraph

StrategyChunk containing ruleContains exception?Holiday question
Fixed 20 tokens30-day rule ... except durPartlyIncomplete
Sentence split30-day rule onlyNoWrong
Heading + paragraphReturns: 30-day rule, except during holidaysYesCorrect
Score the split by evidence coverage on the questions that need the exception.

Summary

The whole topic in one minute.

Similarity measures a candidate, while the task requires two linked facts. A split that hides the qualification fails the end-to-end question.

Test splitting against the questions the corpus must answer. Check whether the evidence set contains the entire supporting span, how much irrelevant text was added and how much duplication consumes the prompt budget.

Sources