Search Tutorials
--Ads--Structure-Aware Chunking
Split by Markdown headings, HTML sections and code functions instead of character counts.
Most documents already tell you where their natural chunks are: headings mark sections, HTML has <section> and <h2> elements, and source code is organised into functions and classes. Structure-aware chunking uses these boundaries instead of counting characters, which gives chunks that are self-contained and easy to cite.
Markdown: split by headings
The splitter below walks through a Markdown document, tracks the current heading path (for example Employee Handbook > Leave > Carry-over) and starts a new chunk at every heading. Sections that are still too long are split further with the recursive splitter from the previous lesson. The heading path is kept as metadata and also prepended to the chunk text, so the embedding knows what the section is about.
import re
from chunkers import recursive_split # from the fixed-size chunking lesson
HEADING = re.compile(r"^(#{1,6})\s+(.+?)\s*#*\s*$")
def split_markdown(text: str, max_chars: int = 1500) -> list[dict]:
sections, path, body = [], [], []
in_code = False
def flush():
content = "\n".join(body).strip()
if content:
sections.append({"headings": [h for _, h in path], "text": content})
body.clear()
for line in text.splitlines():
if line.strip().startswith("```"):
in_code = not in_code # never treat '#' inside code blocks as headings
match = None if in_code else HEADING.match(line)
if match:
flush()
level = len(match.group(1))
path[:] = [(l, h) for l, h in path if l < level] + [(level, match.group(2))]
else:
body.append(line)
flush()
chunks = []
for section in sections:
heading_path = " > ".join(section["headings"])
for piece in recursive_split(section["text"], max_chars):
chunks.append({
"text": f"{heading_path}\n\n{piece}" if heading_path else piece,
"metadata": {"section": heading_path},
})
return chunks
doc = """# Employee Handbook
## Leave
### Paid leave
Employees get 18 days in the first year and 24 days after that.
### Carry-over
Up to 5 unused days can be carried over to the next year.
## Expenses
Claims must be submitted within 30 days."""
for chunk in split_markdown(doc):
print(chunk["metadata"]["section"], "|", chunk["text"].splitlines()[-1])
Employee Handbook > Leave > Paid leave | Employees get 18 days in the first year and 24 days after that.
Employee Handbook > Leave > Carry-over | Up to 5 unused days can be carried over to the next year.
Employee Handbook > Expenses | Claims must be submitted within 30 days.
Notice that the chunk "Up to 5 unused days can be carried over" now carries the words "Leave" and "Carry-over". Without the heading path, its embedding would not even know it is about leave.
Small sections: merge them
Heading-based splitting can produce tiny chunks (a heading with one sentence). Merge neighbouring small sections that share a parent heading until they reach a minimum size, such as 300 characters. Very small chunks retrieve poorly because their embeddings carry little information.
HTML: split by section elements
from bs4 import BeautifulSoup
def split_html(html: str) -> list[dict]:
soup = BeautifulSoup(html, "html.parser")
for tag in soup(["script", "style", "nav", "footer"]):
tag.decompose()
chunks, heading, buffer = [], "", []
for el in soup.find_all(["h1", "h2", "h3", "p", "li", "pre", "table"]):
if el.name in ("h1", "h2", "h3"):
if buffer:
chunks.append({"text": f"{heading}\n\n" + "\n".join(buffer), "metadata": {"section": heading}})
buffer = []
heading = el.get_text(" ", strip=True)
else:
buffer.append(el.get_text(" ", strip=True))
if buffer:
chunks.append({"text": f"{heading}\n\n" + "\n".join(buffer), "metadata": {"section": heading}})
return chunks
A simpler alternative is to convert HTML to Markdown first (for example with the markdownify package) and reuse the Markdown splitter.
Source code: split by functions and classes
Code should never be split in the middle of a function. Python's built-in ast module gives the exact start and end line of every top-level function and class:
import ast
def split_python(source: str, file_name: str) -> list[dict]:
tree = ast.parse(source)
lines = source.splitlines()
chunks = []
for node in tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
start = node.lineno - 1
if node.decorator_list: # include decorators
start = node.decorator_list[0].lineno - 1
code = "\n".join(lines[start:node.end_lineno])
chunks.append({
"text": f"# File: {file_name}\n{code}",
"metadata": {"file": file_name, "symbol": node.name,
"start_line": start + 1, "end_line": node.end_lineno},
})
return chunks
For other languages, tree-sitter parsers do the same job. The lesson Code RAG builds a full code retrieval system.
Other structures worth using
- Legal documents: numbered clauses (1.1, 1.2, ...).
- FAQs: one question and its answer per chunk.
- Transcripts and chats: speaker turns or time windows.
- Slides: one slide per chunk, with the deck title.
- Emails: one message per chunk, with subject, sender and date.
Key takeaways
- Use the document's own structure (headings, sections, functions) as chunk boundaries.
- Prepend the heading path to each chunk so its embedding has context.
- Split oversized sections recursively and merge tiny ones.
- Never split code inside a function; use a parser such as
astor tree-sitter.