Learn/LangChain Mastery/Part 4 · 3. Data Ingestion & Preparation
Lesson 27 of 68
SyllabusLangChain Mastery · Part 4

Markdown & Code Splitting

Preserving structure. Why headers should stick to their content.

Course outline & contents
LangChain Mastery
The Document Object & MetadataLoaders: PDF, HTML, Text, WebCleaning & NormalizationChunking: Why It ExistsRecursiveCharacterTextSplitterToken-Aware & Syntax-Aware SplittingMarkdown & Code SplittingMetadata Enrichment StrategiesDeduplication via Content HashingLazy Loading & Generators

Imagine this markdown:

Markdown
# Pricing
The cost is $10.

# Refund Policy
No refunds allowed.

If you split blindly in the middle, a chunk might just say "No refunds allowed." When retrieved, the LLM doesn't know what has no refunds. Is it the product? The shipping? It lost the header.

We want to attach the header to the content. Chunk 1: Header: Pricing | Content: The cost is $10. Chunk 2: Header: Refund Policy | Content: No refunds allowed.

markdown_split.py
from langchain_text_splitters import MarkdownHeaderTextSplitter

headers_to_split_on = [
  ("#", "H1"),
  ("##", "H2"),
  ("###", "H3"),
]

markdown_splitter = MarkdownHeaderTextSplitter(
  headers_to_split_on=headers_to_split_on
)

docs = markdown_splitter.split_text(markdown_text)
# Result: metadata={'H1': 'Pricing'} content='The cost is $10.'

By moving stricture into metadata, the LLM always knows the "Parent Context" of any snippet. You eliminate "orphan chunks."

Flat text is bad. Structured text is good. Leverage syntax (Markdown, HTML, Code) to keep context attached to data.

Key Intuition: "Headings are not text; they are metadata."

Track your progressSign in and your progress follows you across devices.
Sign in to track progress Next lesson
← Previous lessonToken-Aware & Syntax-Aware SplittingNext lesson →Metadata Enrichment Strategies