Medical AI · Retrieval-augmented generation (RAG) · Lesson 2 of 7
Chunking clinical guidelines
Reviewed by Dr. Ram Kumar G, MBBS, MD (Internal Medicine), MPH (USA), on · Last updated
- Intermediate
- Technical focus
- About 30 minutes
- Includes exercise
Before this lesson: Why RAG? Grounding answers in trusted sources
In short
Chunking splits documents into the passages a RAG system retrieves. If chunks are cut at arbitrary word counts, a clinical rule can be split in half, so the retrieved passage says when not to start a medicine but not when to stop it. Chunking that follows the document's structure, keeps each chunk's heading with it, and adds overlap where needed produces passages that stand alone and can be cited.
You will learn to
- Explain how chunk size and boundaries affect retrieval and answers
- Implement fixed-size and section-aware chunking in Python
- Show how a fixed-size chunk can split a clinical rule
- Choose chunking settings and metadata for real guidelines
Why chunking matters
Retrieval returns whole chunks, so a chunk is the unit of evidence the model sees. Too large, and chunks mix several topics, dilute relevance and fill the context with irrelevant text. Too small, and they lose the context needed to be understood, such as which population or medicine a rule refers to.
Clinical guidelines make this harder: rules often depend on conditions in the next sentence ('…unless eGFR is below 30'), tables and footnotes carry essential detail, and headings say which population a section applies to.
The teaching document
Lessons in this track use the synthetic protocol below. Run this block first in each notebook.
PROTOCOL = """# Synthetic diabetes clinic protocol (teaching document, not clinical guidance)
## 1. Monitoring glucose control
Check HbA1c every 3 months after any change in treatment. Once targets are met and treatment is stable, check HbA1c every 6 months. A common target for many non-pregnant adults is below 7%, adjusted for the individual.
## 2. Kidney function and metformin
Check eGFR and urine albumin-to-creatinine ratio at least once a year. Metformin should not be started if eGFR is below 45. If eGFR falls below 30 during treatment, stop metformin.
## 3. Foot care
Examine both feet at every review. Test sensation with a 10 g monofilament at least once a year. Refer urgently if there is an ulcer with spreading redness, a suspected infection of the bone, or a cold, pale foot.
## 4. Low blood glucose
A glucose below 70 mg/dL is low. Treat with 15 g of fast-acting carbohydrate and recheck after 15 minutes. Repeat if glucose is still below 70 mg/dL. Review any medicine that may have caused the low glucose.
## 5. Eye screening
Arrange retinal screening at diagnosis of type 2 diabetes and then at the interval set by the local screening programme.
"""About the teaching document
- The protocol used in this track was written for teaching. Its statements are broadly in line with common practice, but it is not clinical guidance and must not be used for patient care.
- In a real system, the documents would be your organisation's approved guidelines, with version control and an owner responsible for keeping them current.
Fixed-size chunking
The simplest approach cuts the text every N words, ignoring structure.
def fixed_size_chunks(text, size=40):
words = text.split()
return [" ".join(words[i:i + size]) for i in range(0, len(words), size)]
chunks = fixed_size_chunks(PROTOCOL)
print(f"{len(chunks)} chunks of up to 40 words\n")
for i, c in enumerate(chunks[2:5], start=2):
print(f"[{i}] {c}\n")
# 5 chunks of up to 40 words
#
# [2] eGFR falls below 30 during treatment, stop metformin. ## 3. Foot care Examine both feet at every review. Test sensation with a 10 g monofilament at least once a year. Refer urgently if there is an ulcer with spreading redness,
#
# [3] a suspected infection of the bone, or a cold, pale foot. ## 4. Low blood glucose A glucose below 70 mg/dL is low. Treat with 15 g of fast-acting carbohydrate and recheck after 15 minutes. Repeat if glucose is still
#
# [4] below 70 mg/dL. Review any medicine that may have caused the low glucose. ## 5. Eye screening Arrange retinal screening at diagnosis of type 2 diabetes and then at the interval set by the local screening programme.- Chunk 2 starts mid-sentence ('eGFR falls below 30…') with no mention that it is about kidney function, and then runs into the foot-care section.
- Chunk 3 begins with the second half of the urgent-referral list. Retrieved alone, it would be impossible to interpret.
Section-aware chunking
Splitting on the document's own headings keeps each topic together. Adding the document title and heading to every chunk means a retrieved chunk says what it is about and where it came from.
import re
def section_chunks(text):
"""Split on '## ' headings; keep the heading with its text so each chunk stands alone."""
title = text.splitlines()[0].lstrip("# ").strip()
parts = re.split(r"\n(?=## )", text)[1:]
return [{"id": f"s{i + 1}", "text": f"{title} > {p.strip()}"} for i, p in enumerate(parts)]
sections = section_chunks(PROTOCOL)
print(f"{len(sections)} section chunks")
print(sections[1]["text"])
# 5 section chunks
# Synthetic diabetes clinic protocol (teaching document, not clinical guidance) > ## 2. Kidney function and metformin
# Check eGFR and urine albumin-to-creatinine ratio at least once a year. Metformin should not be started if eGFR is below 45. If eGFR falls below 30 during treatment, stop metformin.The difference at retrieval time
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
def top_chunk(chunk_texts, question):
vec = TfidfVectorizer(stop_words="english").fit(chunk_texts + [question])
scores = cosine_similarity(vec.transform([question]), vec.transform(chunk_texts))[0]
return chunk_texts[scores.argmax()]
question = "When should metformin be stopped because of kidney function?"
print("Fixed-size chunk retrieved:\n ", top_chunk(fixed_size_chunks(PROTOCOL), question))
print("\nSection chunk retrieved:\n ", top_chunk([s["text"] for s in section_chunks(PROTOCOL)], question))
# Fixed-size chunk retrieved:
# target for many non-pregnant adults is below 7%, adjusted for the individual. ## 2. Kidney function and metformin Check eGFR and urine albumin-to-creatinine ratio at least once a year. Metformin should not be started if eGFR is below 45. If
#
# Section chunk retrieved:
# Synthetic diabetes clinic protocol (teaching document, not clinical guidance) > ## 2. Kidney function and metformin
# Check eGFR and urine albumin-to-creatinine ratio at least once a year. Metformin should not be started if eGFR is below 45. If eGFR falls below 30 during treatment, stop metformin.- The fixed-size chunk ends at 'If', cutting off the stopping rule the question asks about. A model given only that chunk could answer with the starting threshold (45) instead of the stopping threshold (30), a clinically important error.
- The section chunk contains the full rule and its heading, so the answer and its citation are complete.
Practical chunking choices
| Choice | Recommendation | Why |
|---|---|---|
| Boundaries | Follow headings, numbered recommendations and paragraphs | Clinical rules and their conditions stay together |
| Size | A few hundred tokens is a common starting point; tune with evaluation | Balances focus and context |
| Overlap | Add some overlap when sections must be split | A sentence near a boundary appears in both chunks |
| Context | Prefix each chunk with document title, version and heading path | Retrieved chunks stand alone and can be cited |
| Tables | Keep each table row with its column headers, or convert rows to sentences | Numbers without headers are meaningless |
| Metadata | Store source, version, date, section and audience | Enables filtering, citations and retiring old versions |
Check the converted text
- Guidelines are often PDFs. Text extraction can scramble columns, drop table structure and lose superscripts or symbols such as '<' and '≥'. Inspect the extracted text before indexing; a lost '<' can reverse a rule.
Exercise
Compare chunking strategies on the synthetic protocol and measure which keeps clinical rules intact.
Data: Synthetic protocol in the notebook; optional openly licensed guideline excerpt (for example WHO publications under CC BY-NC-SA 3.0 IGO) (Created for this course; optional source under its own licence)
- Reproduce fixed-size and section-aware chunking.
- Add 10-word overlap to fixed-size chunking and check whether the metformin question now retrieves the full rule.
- Write five questions whose answers depend on a condition ('unless', 'if', 'below') and check which method keeps each rule whole.
- Add a small table (for example glucose thresholds) to the protocol and design a chunking rule that keeps headers with each row.
- Optional: chunk a short openly licensed guideline excerpt and review the extracted text for errors.
The runnable notebook and worked solution will be published soon. You can work through the steps with the code on this page in the meantime.
Key takeaways
- Chunks are the unit of evidence; bad boundaries produce incomplete or wrong answers.
- Follow the document's structure and keep headings with each chunk.
- Use overlap when splitting is unavoidable, and keep tables with their headers.
- Store version and source metadata, and check extracted text before indexing.
Terms used: Chunking, Embedding, RAG (retrieval-augmented generation)
Related: Why RAG?, Embeddings and vector stores, Data standards
FAQ
What is chunking in RAG?
Splitting documents into passages that can be indexed and retrieved. The retrieved chunks are what the language model sees when answering.
What chunk size should I use?
There is no universal answer. A few hundred tokens is a common starting point, but the right size depends on the documents and questions, and should be chosen by evaluating retrieval.
Should chunks overlap?
Overlap helps when text must be split mid-section, so sentences near a boundary appear with their context. It increases index size slightly.
How should tables in guidelines be handled?
Keep each row with its column headers, or convert rows into self-contained sentences, so that retrieved numbers keep their meaning.
Why add the heading to every chunk?
A chunk retrieved on its own needs to say what it is about, such as which condition, population or medicine, and where it came from for citation.
Sources
- Gao Y, et al. Retrieval-augmented generation for large language models: a survey. 2023. arXiv:2312.10997
- Liu NF, et al. Lost in the middle: how language models use long contexts. Transactions of the ACL 2024;12:157–173. doi:10.1162/tacl_a_00638
- Xiong G, et al. Benchmarking retrieval-augmented generation for medicine. Findings of ACL 2024. arXiv:2402.13178
- Manning CD, Raghavan P, Schütze H. Introduction to Information Retrieval. Cambridge University Press, 2008 (free online edition)
- World Health Organization. Publications licensing (CC BY-NC-SA 3.0 IGO)
Educational content only. This material teaches methods; it is not clinical advice. Code, models and examples here are not validated medical devices and must not be used to make decisions about real patients without proper clinical validation, governance and any required regulatory approval. Examples use synthetic or openly licensed de-identified data only. Never paste identifiable patient information into public AI tools. Mentions of models, tools or vendors are for identification, not endorsement.