Why fixed-size chunking quietly destroys meaning
Every "split every 1,000 characters" pipeline fails in the same three places: it cuts a table in half, it separates a heading from the paragraph that explains it, and it starts a chunk mid-sentence so the model has no idea what "it" or "the above policy" refers to. The retrieval looks fine — you get chunks back — but the answers degrade and nobody can explain why.
The fix is not a bigger context window. It is choosing a split unit that matches what you are going to do with the chunk: retrieve it, summarize it, or reason across it. This guide walks through four strategies, with runnable code, and is honest about when each one is a waste of tokens.
Strategy 1: Split on document structure, not character count
Headings are the author's own chunk boundaries. Respect them first, then fall back to paragraph splitting only for sections that are still oversized. Two rules matter more than any size constant: never break inside a fenced code block, and never break a table row away from its header.
This splitter uses only the standard library. It keeps each heading attached to its body, treats fenced blocks as atomic, and caps sections at a character budget you choose.
import re
def blocks(text: str) -> list[str]:
"""Split into paragraph blocks, but never break inside a ``` fence."""
out, buf, in_fence = [], [], False
for line in text.splitlines():
if line.strip().startswith("```"):
in_fence = not in_fence
if not line.strip() and not in_fence:
if buf:
out.append("\n".join(buf))
buf = []
else:
buf.append(line)
if buf:
out.append("\n".join(buf))
return out
def split_markdown(doc: str, max_chars: int = 4000) -> list[dict]:
parts = re.split(r"(?m)^(#{1,3} .*)$", doc)
sections = []
if parts[0].strip():
sections.append({"heading": "(preamble)", "text": parts[0].strip()})
for i in range(1, len(parts), 2):
sections.append({
"heading": parts[i].lstrip("#").strip(),
"text": parts[i + 1].strip() if i + 1 < len(parts) else "",
})
chunks = []
for s in sections:
if len(s["text"]) <= max_chars:
chunks.append(s)
continue
buf = ""
for b in blocks(s["text"]):
if buf and len(buf) + len(b) + 2 > max_chars:
chunks.append({"heading": s["heading"], "text": buf.strip()})
buf = ""
buf += b + "\n\n"
if buf.strip():
chunks.append({"heading": s["heading"], "text": buf.strip()})
return chunks
Keep the heading in the chunk text, not just in metadata. The model needs it as much as your indexer does.
Prefer under-sized chunks over over-sized ones for retrieval; a 300–800 character chunk usually embeds more sharply than a 4,000 character one, because a long chunk averages several topics into one vector.
For summarization, go bigger — 3,000–6,000 characters per chunk is fine and cheaper, since you are not competing with other topics in a similarity search.
Treat tables as single blocks and, where you can, re-emit them as header-prefixed rows ("Region: EMEA | Q3 target: 1,200") so a row still makes sense when it stands alone.
Strategy 2: Give every chunk its own context header
A chunk that reads "The deadline is 30 days from signature" is ambiguous on its own — 30 days for what, under which agreement? The cheapest quality win in long-document handling is prepending a one-sentence, document-aware context line to each chunk before you index or summarize it.
Generate it with the fast model, once per chunk, and store both the raw chunk and the contextualized version. This is a good place for deepseek-v4-flash: short outputs, no reasoning depth required.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["AICREDITS_API_KEY"],
base_url="https://api.aicreditsapi.com/v1")
def ask(prompt: str, model: str = "deepseek-v4-flash", max_tokens: int = 600) -> str:
r = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
max_tokens=max_tokens,
)
return r.choices[0].message.content.strip()
def contextualize(doc_title: str, chunk: dict) -> str:
prompt = f'''Document: "{doc_title}". Section heading: "{chunk["heading"]}".
Write ONE sentence (max 25 words) stating what this section does in the context of the whole document. Do not restate its details. Output the sentence and nothing else.
Section:
{chunk["text"][:3000]}'''
return ask(prompt, max_tokens=80)
title = "Q3 Vendor Compliance Manual"
doc = open("manual.md", encoding="utf-8").read()
for c in split_markdown(doc, max_chars=4000):
c["index_text"] = f'{title} > {c["heading"]}. {contextualize(title, c)}\n\n{c["text"]}'
print(f"{len(doc)} chars -> chunks ready for embedding")
Two practical notes. First, cache the context lines alongside the chunk — regenerating them on every run is pure waste. Second, if you re-index the same corpus often, repeated identical prefixes benefit from prompt caching on the provider side, which makes stable, well-structured prompts cheaper than ad-hoc ones.
Strategy 3: Overlap only when you are retrieving
Overlap is the most cargo-culted setting in chunking. It helps when a single answer spans a boundary — a definition that starts in one paragraph and finishes in the next. It actively hurts summarization, because a fact that appears in two overlapping chunks gets counted twice in your map-reduce output.
A defensible default: no overlap for summarization or extraction; a modest overlap (roughly one sentence, not a percentage of the chunk) for retrieval over prose. Sliding windows by character count are the worst of both worlds — they overlap mid-word and mid-table.
| Strategy | Best for | Split unit | Overlap |
|---|---|---|---|
| Structure-aware | Manuals, contracts, specs, policies | Heading, then paragraph | None |
| Sentence-window | Transcripts, chat logs, interviews | N sentences | One sentence |
| Parent-child | RAG QA over long reports | Small child for search, parent for context | Handled by parent |
| Map-reduce | "Summarize this 300-page doc" | Section | None |
Strategy 4: Map-reduce that doesn't lose the thread
For whole-document tasks, run the map step on the fast model in parallel and reserve the stronger model for the final synthesis, where quality compounds across everything you gathered. Use deepseek-v4-flash for per-section summaries and deepseek-v4-pro for the single reduction that a human will actually read.
The loop below also handles the case where the combined summaries are still too long for one prompt: it groups them into batches, condenses each batch, and repeats until the payload fits.
from concurrent.futures import ThreadPoolExecutor
def summarize_section(doc_title: str, chunk: dict) -> dict:
prompt = f'''Document: "{doc_title}". Section: "{chunk["heading"]}".
Summarize this section in at most 120 words. Keep names, numbers, dates, obligations and decisions verbatim. If the section is boilerplate (license text, table of contents, headers), reply exactly: SKIP
---
{chunk["text"]}'''
return {"heading": chunk["heading"], "summary": ask(prompt, max_tokens=300)}
def brief(doc_title: str, chunks: list[dict], batch_chars: int = 12000) -> str:
with ThreadPoolExecutor(max_workers=6) as pool:
results = list(pool.map(lambda c: summarize_section(doc_title, c), chunks))
items = [f"### {r['heading']}\n{r['summary']}"
for r in results
if not r["summary"].upper().startswith("SKIP")]
for _ in range(6):
if len("\n\n".join(items)) <= batch_chars:
break
batches, buf = [], ""
for it in items:
if buf and len(buf) + len(it) + 2 > batch_chars:
batches.append(buf)
buf = ""
buf += it + "\n\n"
if buf:
batches.append(buf)
items = [ask("Condense these section summaries. Merge duplicates, keep every requirement, number and decision.\n\n" + b)
for b in batches]
return ask(
f'Write an executive brief for "{doc_title}" from the section summaries below. '
'Structure it as: key facts, obligations, open questions, and anything a reader must not miss.\n\n'
+ "\n\n".join(items),
model="deepseek-v4-pro",
max_tokens=1500,
)
print(brief("Q3 Vendor Compliance Manual", split_markdown(doc, max_chars=4000)))
Ask for
SKIPon boilerplate. Two words of prompt save you paying to summarize a table of contents.Keep the map step idempotent. Same chunk, same summary, so you can cache results and re-run only what changed.
Read the reduce output, not the map output. If the final brief is wrong, the bug is almost always in chunk boundaries (a decision split across two sections), not in the model.
Cost and throughput, qualitatively
Chunking decisions change your bill more than your model choice does. Smaller chunks mean more requests and more repeated prompt overhead; larger chunks mean fewer requests but coarser retrieval. Flash handles the high-volume map step well, and pro is worth its higher cost only for the final synthesis or for judgment-heavy extraction. Prompt caching makes repeated stable prefixes cheaper, and off-peak usage costs less than peak — so batch re-indexing jobs are a good candidate for scheduling. For current rates, see aicreditsapi.com/deepseek-prices rather than trusting a number from any blog post, including this one.
Frequently asked questions
Match the unit to the task: a few hundred to ~800 characters for embedding and retrieval, 3,000–6,000 characters for summarization, and never larger than the point where a chunk contains two unrelated topics. Measure by characters unless you have a tokenizer handy; English averages roughly four characters per token, and CJK text is far denser, so leave headroom.
Only for genuinely unstructured input — raw logs, scraped text with no headings. Even then, split on sentence boundaries and keep code fences and tables atomic. Structure-aware splitting beats fixed windows on any document a human wrote with headings.
No. Overlap duplicates facts and inflates counts in map-reduce output. Use a one-sentence overlap for retrieval over prose, and none for extraction or summarization.
Keep the header row and re-emit each data row as a header-prefixed sentence, then chunk by row groups. A row that reads "Region: EMEA | Q3 target: 1,200" carries its own meaning; a bare row of numbers does not.
The best chunking test is embarrassingly simple: pick ten random chunks, read them cold, and ask whether you could answer a question from each one without seeing the rest of the document. If not, your boundaries — not your model — are the problem.