Hierarchical Summarization
Progressive compression: chapters → sections → document summary.
Hierarchical Summarization is a free AI Prompt Engineering lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Prompt Engineering learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is Hierarchical Summarization?
Hierarchical summarization mirrors the structure of the document itself. Rather than treating all chunks equally, it compresses content level by level:
- Pages → section summaries
- Sections → chapter summaries
- Chapters → document summary
Each level is a compressed representation of the level below. This is how humans summarize books — reading chapters, forming mental summaries, then integrating.
When to Use Hierarchical Summarization
Hierarchical summarization is the right choice for:
- Books: 200+ pages with clear chapter structure
- Research papers: abstract, introduction, methods, results, discussion
- Legal contracts: sections with defined headings (definitions, obligations, termination)
- Technical reports: executive summary → findings → appendices
It is overkill for short articles. It shines when the document has a natural tree structure.
Document Tree Structure
Model the document as a tree:
- Root: final summary
- Level 1 nodes: chapter summaries
- Level 2 nodes: section summaries
- Leaves: raw page or chunk text
Summarization proceeds bottom-up: leaves → level 2 → level 1 → root. Each node's summary is derived only from its children's summaries.
from dataclasses import dataclass, field
from typing import List, Optional
@dataclass
class DocNode:
title: str
content: str = ''
summary: str = ''
children: List['DocNode'] = field(default_factory=list)
# Example: book with 3 chapters, each with 3 sections
book = DocNode(
title='My Book',
children=[
DocNode('Chapter 1', children=[
DocNode('Section 1.1', content='...raw text...'),
DocNode('Section 1.2', content='...raw text...'),
]),
DocNode('Chapter 2', children=[
DocNode('Section 2.1', content='...raw text...'),
])
]
)Bottom-Up Summarization
Traverse the tree bottom-up. Leaf nodes are summarized from their raw content. Internal nodes are summarized from their children's summaries.
import openai
client = openai.OpenAI(api_key='sk-...')
def summarize_text(text, role='section'):
resp = client.chat.completions.create(
model='gpt-4o',
messages=[
{'role': 'system',
'content': f'Summarize this {role} in 3-5 sentences.'},
{'role': 'user', 'content': text}
]
)
return resp.choices[0].message.content
def summarize_tree(node, depth=0):
role = ['document', 'chapter', 'section', 'page'][min(depth, 3)]
if not node.children:
node.summary = summarize_text(node.content, role)
else:
for child in node.children:
summarize_tree(child, depth + 1)
combined = '\n\n'.join(
f'{c.title}:\n{c.summary}' for c in node.children
)
node.summary = summarize_text(combined, role)
return node.summaryProgressive Compression
Progressive compression means each level reduces information density. A good rule of thumb:
- Page (2000 tokens) → section summary (200 tokens) — 10x compression
- Section summary (200 tokens) → chapter summary (100 tokens) — 2x compression
- Chapter summaries (5 × 100 tokens) → document (150 tokens) — 3x compression
Total: a 10,000-token document compressed to ~150 tokens while preserving the main argument. Prompt each level to maintain compression ratio.
PAGE_PROMPT = 'Summarize this page in 2-3 sentences (under 80 words).'
SECTION_PROMPT = 'Given these page summaries, write a section summary in 3-4 sentences (under 120 words).'
CHAPTER_PROMPT = 'Given these section summaries, write a chapter summary in 4-5 sentences (under 150 words).'
DOC_PROMPT = 'Given these chapter summaries, write an executive summary of the entire document (under 200 words).'Maintaining Coherence Across Levels
A risk of hierarchical summarization: summaries at one level may contradict or repeat each other, and these errors compound upward. Strategies to maintain coherence:
- Include the parent section heading in the prompt so the model knows the context
- Ask the model to avoid repeating facts already stated in prior section summaries
- At the final reduce step, explicitly ask the model to resolve any contradictions
def summarize_sections_for_chapter(chapter_title, section_summaries):
content = '\n\n'.join(
f'Section: {s["title"]}\n{s["summary"]}'
for s in section_summaries
)
prompt = (
f'Chapter: {chapter_title}\n\n'
'Below are summaries of each section. '
'Write a unified chapter summary without repeating '
'the same facts from multiple sections.\n\n' + content
)
resp = client.chat.completions.create(
model='gpt-4o',
messages=[{'role': 'user', 'content': prompt}]
)
return resp.choices[0].message.contentResearch Paper Hierarchy
Research papers have a natural hierarchy: Abstract → Introduction → Methods → Results → Discussion → Conclusion. Each section has a distinct role, so use section-specific prompts:
SECTION_PROMPTS = {
'abstract': 'Summarize the paper abstract: what problem, method, and result?',
'introduction': 'Summarize the introduction: what gap does the paper address?',
'methods': 'Summarize the methods: what approach was used?',
'results': 'Summarize the results: what were the key findings and metrics?',
'discussion': 'Summarize the discussion: what do the results mean?',
'conclusion': 'Summarize the conclusion and future work.'
}
def summarize_paper(sections_dict):
section_summaries = {}
for section, text in sections_dict.items():
prompt = SECTION_PROMPTS.get(section, 'Summarize this section.')
section_summaries[section] = call_llm(prompt, text)
return section_summariesLegal Contract Hierarchy
Legal contracts follow a clause hierarchy: definitions → obligations → remedies → termination → governing law. Hierarchical summarization must preserve:
- Exact figures (payment amounts, deadlines)
- Party names (client, vendor, licensor)
- Conditional language (unless, except when, provided that)
Prompt the model to flag any clause with a numeric amount or conditional that it is summarizing, so it is not accidentally dropped.
LEGAL_PROMPT = '''Summarize this contract clause in plain English.
Preserve: all monetary amounts, dates, party names, and conditionals.
Flag any obligation with [OBLIGATION] and any amount with [AMOUNT].'''
def summarize_clause(clause_text):
resp = client.chat.completions.create(
model='gpt-4o',
messages=[
{'role': 'system', 'content': LEGAL_PROMPT},
{'role': 'user', 'content': clause_text}
]
)
return resp.choices[0].message.contentStoring Hierarchical Summaries
Store the entire summary tree, not just the root summary. This enables:
- Drilling down — show chapter summary, then section summary on demand
- Retrieval — match a user query against section summaries, not just the full document
- Update — when one section changes, only re-summarize that branch of the tree
import json
def tree_to_dict(node):
return {
'title': node.title,
'summary': node.summary,
'children': [tree_to_dict(c) for c in node.children]
}
def save_tree(node, path):
with open(path, 'w') as f:
json.dump(tree_to_dict(node), f, indent=2)
print(f'Saved summary tree to {path}')Incremental Updates
When a document is updated, hierarchical structure enables incremental re-summarization. Only re-summarize the modified node and its ancestors — all sibling branches remain valid.
For a 10-chapter book where chapter 3 is revised: re-summarize chapter 3's sections, then chapter 3, then the book. Re-compute 3 nodes instead of all nodes.
def update_node(node, updated_child_title):
# Re-summarize the changed child
for child in node.children:
if child.title == updated_child_title:
summarize_tree(child) # re-summarize from leaves
break
# Re-summarize current node from updated children
combined = '\n\n'.join(
f'{c.title}:\n{c.summary}' for c in node.children
)
node.summary = summarize_text(combined)
return node.summaryComparing Flat vs Hierarchical
Flat map-reduce vs hierarchical summarization:
- Flat: simpler, ignores document structure, better for uniform documents (news articles)
- Hierarchical: respects structure, enables drill-down, better coherence for structured documents
In practice, combine both: use flat map-reduce within each chapter (many pages), then hierarchical across chapters. This is the most robust approach for real-world documents.
Knowledge Check
In hierarchical summarization, which direction does the summarization process proceed through the document tree?
Recap: Hierarchical Summarization
Hierarchical summarization mirrors document structure for superior results:
- Model the document as a tree: pages → sections → chapters → document
- Summarize bottom-up: leaves first, root last
- Each level applies progressive compression to maintain coherence
- Best for books, research papers, legal contracts with clear hierarchical structure
- Store the full tree to enable drill-down retrieval and incremental updates
Next lesson: maintaining context across chunks with overlap and rolling summaries.
Frequently asked questions
Is the “Hierarchical Summarization” lesson free?
Yes — the full text of “Hierarchical Summarization” is free to read here on the web, and the AI Prompt Engineering course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Prompt Engineering course, upgrade to CoddyKit PRO.
What will I learn in “Hierarchical Summarization”?
Progressive compression: chapters → sections → document summary. You practise AI Prompt Engineering with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Prompt Engineering?
No prior experience is required. AI Prompt Engineering on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Hierarchical Summarization” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Prompt Engineering lesson?
Yes. Every AI Prompt Engineering lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Chunking Strategies for Long Texts
- Map-Reduce Summarization Pattern
- Hierarchical Summarization
- Maintaining Context Across Chunks