Maintaining Context Across Chunks
Overlap, rolling context, and metadata injection for continuity.
Maintaining Context Across Chunks is a free AI Prompt Engineering lesson on CoddyKit — lesson 4 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.
The Cross-Chunk Context Problem
When a document is split into chunks, information from chunk N may be needed to correctly interpret chunk N+1. For example: a term defined in chunk 3 is used in chunk 7. Without context bridging, the model processing chunk 7 does not know that definition.
Four strategies address this: overlap, rolling summary injection, metadata tags, and page number references.
Strategy 1: Token Overlap
Overlap repeats the last N tokens of chunk N at the start of chunk N+1. This ensures that a sentence or argument spanning a boundary appears fully in at least one chunk.
Typical overlap: 100–200 tokens (roughly 75–150 words). Too much overlap increases redundancy and cost; too little leaves boundary gaps.
import tiktoken
enc = tiktoken.get_encoding('cl100k_base')
def chunk_with_overlap(text, max_tokens=1000, overlap=200):
tokens = enc.encode(text)
chunks = []
step = max_tokens - overlap
i = 0
while i < len(tokens):
chunk = tokens[i:i + max_tokens]
chunks.append(enc.decode(chunk))
i += step
return chunks
chunks = chunk_with_overlap(document, max_tokens=1000, overlap=200)
print(f'{len(chunks)} chunks with 200-token overlap')Overlap for Retrieval vs Summarization
Overlap behaves differently across tasks:
- Retrieval: overlap helps — a query matches the overlapping region in either adjacent chunk, improving recall. Use 10–20% overlap of chunk size.
- Summarization: overlap can cause repetition — the same sentence is summarized twice. Use smaller overlap (5–10%) or strip overlap before summarizing.
def strip_overlap(chunks, overlap_tokens=200):
'''Remove the leading overlap from each chunk (except the first).'''
cleaned = [chunks[0]]
for chunk in chunks[1:]:
tokens = enc.encode(chunk)
trimmed = enc.decode(tokens[overlap_tokens:])
cleaned.append(trimmed)
return cleanedStrategy 2: Rolling Summary Injection
A rolling summary is a running abstract of all chunks processed so far. Before processing chunk N, inject the rolling summary into the prompt as context. This gives the model knowledge of prior content without exceeding the context window.
import openai
client = openai.OpenAI(api_key='sk-...')
def process_with_rolling_summary(chunks):
rolling_summary = ''
results = []
for i, chunk in enumerate(chunks):
context = ''
if rolling_summary:
context = f'Summary of previous sections:\n{rolling_summary}\n\n'
prompt = context + f'Current section:\n{chunk}'
resp = client.chat.completions.create(
model='gpt-4o',
messages=[
{'role': 'system', 'content': 'Answer questions or summarize, using prior context.'},
{'role': 'user', 'content': prompt}
]
)
result = resp.choices[0].message.content
results.append(result)
# Update rolling summary
rolling_summary = update_rolling_summary(rolling_summary, chunk)
return resultsUpdating the Rolling Summary
The rolling summary should grow incrementally. After processing each chunk, ask the LLM to update the summary by incorporating the new information from that chunk. Keep the rolling summary short — 200–400 tokens — to leave room for the current chunk.
def update_rolling_summary(current_summary, new_chunk, max_words=150):
if not current_summary:
prompt = f'Summarize the following in under {max_words} words:\n\n{new_chunk}'
else:
prompt = (
f'Current running summary (under {max_words} words):\n{current_summary}\n\n'
f'New section to incorporate:\n{new_chunk}\n\n'
f'Update the summary to include the new section. Stay under {max_words} words.'
)
resp = client.chat.completions.create(
model='gpt-4o-mini',
messages=[{'role': 'user', 'content': prompt}]
)
return resp.choices[0].message.contentStrategy 3: Metadata Tags
Metadata tags attach structured information to each chunk so the LLM knows what it is processing and can maintain logical continuity.
Common tags: document_title, chapter, section, page, chunk_index, total_chunks. Inject these as a header in the prompt, not in the chunk text, to separate content from metadata.
def build_prompt_with_metadata(chunk, metadata):
header = (
f'Document: {metadata["title"]}\n'
f'Chapter: {metadata["chapter"]}\n'
f'Section: {metadata["section"]}\n'
f'Page: {metadata["page"]}\n'
f'Chunk: {metadata["chunk_index"] + 1} of {metadata["total_chunks"]}\n'
'---\n'
)
return header + chunk
prompt = build_prompt_with_metadata(
chunk=chunks[5],
metadata={
'title': 'Annual Report 2024',
'chapter': '3. Financial Results',
'section': '3.2 Revenue Breakdown',
'page': 42,
'chunk_index': 5,
'total_chunks': 120
}
)Strategy 4: Page Number References
When a chunk references something from a prior page, the model can cite it if page numbers are embedded. Inject page breaks as markers in the text before chunking, so they survive into the chunks:
def inject_page_markers(pages):
'''pages: list of strings, one per page.'''
marked = []
for i, page_text in enumerate(pages):
marked.append(f'[PAGE {i+1}]\n{page_text}')
return '\n\n'.join(marked)
# When the model sees [PAGE 12] in context, it can say
# 'As defined on page 12...' in its output, enabling traceability.
document_with_markers = inject_page_markers(pdf_pages)
chunks = chunk_with_overlap(document_with_markers)Combining Strategies
In production, combine all four strategies for maximum context fidelity:
- Add page markers before chunking
- Chunk with 200-token overlap
- Attach metadata header to each chunk prompt
- Inject rolling summary before each chunk
The combined approach ensures the model always knows: where in the document it is, what came before, and how the current chunk relates to the whole.
def process_document(pages, doc_metadata):
# Step 1: inject page markers
full_text = inject_page_markers(pages)
# Step 2: chunk with overlap
chunks = chunk_with_overlap(full_text, max_tokens=900, overlap=150)
total = len(chunks)
rolling_summary = ''
results = []
for i, chunk in enumerate(chunks):
meta = {**doc_metadata, 'chunk_index': i, 'total_chunks': total}
prompt = build_prompt_with_metadata(chunk, meta)
if rolling_summary:
prompt = 'Prior context:\n' + rolling_summary + '\n\n' + prompt
result = call_llm(prompt)
results.append(result)
rolling_summary = update_rolling_summary(rolling_summary, chunk)
return resultsEvaluating Context Retention
To verify your context strategy is working, create test questions that require information from multiple chunks:
- Define a term introduced in chunk 2, asked in chunk 8
- Compute a total that spans multiple pages
- Identify a contradiction between chapter 1 and chapter 5
Run the pipeline and check whether answers correctly reference prior content. If they fail, increase overlap or rolling summary size.
test_questions = [
{
'question': 'What is the definition of "net recurring revenue" used in this report?',
'defined_in_chunk': 2,
'asked_in_chunk': 9,
'expected_keywords': ['net recurring revenue', 'subscription', 'exclude']
}
]
def evaluate_context_retention(pipeline_results, test_questions):
for test in test_questions:
answer = pipeline_results[test['asked_in_chunk']]
for kw in test['expected_keywords']:
if kw.lower() not in answer.lower():
print(f'FAIL: missing "{kw}" in answer to chunk {test["asked_in_chunk"]}')Trade-offs Summary
Each strategy has costs and benefits:
- Overlap: simple, increases token count by overlap%, may cause summarization repetition
- Rolling summary: powerful, adds an LLM call per chunk, summary may drift or lose detail
- Metadata tags: free to add, helps model orientation, does not substitute for content
- Page markers: enables traceability, adds characters to text but minimal token overhead
Start with overlap + metadata. Add rolling summary only when cross-chunk context failures are observed in testing.
Real-World Sizing Guide
Practical sizes for a 100-page document (avg 500 tokens/page = 50,000 tokens total):
- Chunk size: 800 tokens, overlap 150 tokens → ~73 chunks
- Rolling summary: 200 tokens max (updated after each chunk)
- Metadata header: ~30 tokens per chunk
- Effective input per API call: 800 + 200 + 30 = 1030 tokens
- Map cost (gpt-4o-mini at $0.15/1M): 73 × 1030 × $0.15/1M ≈ $0.011
Context strategies add minimal cost while dramatically improving coherence.
Knowledge Check
What is the purpose of a rolling summary in chunk-by-chunk document processing?
Recap: Context Across Chunks
Four strategies to maintain context across chunks:
- Overlap: repeat last N tokens of chunk N at start of chunk N+1
- Rolling summary: inject a short running abstract before each chunk
- Metadata tags: header with document, chapter, section, page info
- Page markers: embed page numbers in text before chunking
Combine all four for production pipelines. Test cross-chunk context retention with multi-chunk questions. This concludes Course 16 on Long Document Handling Strategies.
Frequently asked questions
Is the “Maintaining Context Across Chunks” lesson free?
Yes — the full text of “Maintaining Context Across Chunks” 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 “Maintaining Context Across Chunks”?
Overlap, rolling context, and metadata injection for continuity. 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 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Maintaining Context Across Chunks” 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