Skip to content
AgenticAIWiki
  1. Learn
  2. Part 11
  3. 62. Long documents and large codebases
  4. 62.1

Lesson 62.1 · 1 of 3 · 5 min read · Reviewed 24 Nov 2026

Long documents: chunk, summarize, cite

By the end, you can

  • Process documents longer than the useful context.
  • Chunk, summarise and keep citations.

Even when a document fits the window, one giant pass can miss details. For exhaustive tasks, map and reduce.

Chunk sensibly

Split on natural boundaries: chapters, sections, articles, pages. Overlap chunksChunking: Splitting documents into smaller passages before embedding and indexing them. slightly if ideas cross boundaries. Keep metadata with each chunk: document, section, page.

Map

Run the same focused prompt on each chunk: “List every penalty clause in this section, quoting it exactly, with the section number.” Chunks can run in parallel, or in a batch (14.5).

Reduce

Combine results: remove duplicates, sort, resolve conflicts. A final pass can check for cross-references, such as a clause in section 4 that modifies one in section 12.

Cite everything

Each extracted item carries its source. Then the final answer can say “Section 12.3, page 418” and a person can check it. Uncited claims are hard to trust.

Key points

  • Split long documents into chunks along natural boundaries such as sections.
  • Process chunks separately (map), then combine the results (reduce).
  • Keep source references on every extracted fact so answers can cite pages or sections.
Hands-on labRuns in the Playground

Map and reduce a long contract

Extract every penalty clause from a sectioned contract with a citation on each one.

You will have: A map step, a reduce step and a cited list of unique penalty clauses.

Steps

  1. Read the nine sections; treat each one as a chunk.
  2. Write map_section() to return each 'Penalty:' sentence with its section id.
  3. Write reduce_results() to merge duplicates while keeping every source, then sort.
  4. List sections that refer to other sections, for a final cross-reference pass.

Done when

  • The output shows 4 raw hits and 3 unique penalty clauses.
  • The duplicated late-payment clause cites both s3 and s6.
  • Section s4 is flagged for its reference to s9.

Open in the Playground No API key needed.

Starter code (Python)
CONTRACT = {
    "s1": "Scope. The supplier provides cleaning services to all sites.",
    "s2": "Fees. Invoices are due within 30 days of receipt.",
    "s3": "Penalty: late payment adds 2% per month to the unpaid amount.",
    "s4": "Service levels. Penalty: each missed visit costs 50 credits. See s9 for caps.",
    "s5": "Staff. The supplier vets all staff.",
    "s6": "Penalty: late payment adds 2% per month to the unpaid amount.",
    "s7": "Insurance. The supplier holds public liability cover.",
    "s8": "Termination. Either side may end the contract with 90 days notice. Penalty: early exit costs 3 months of fees.",
    "s9": "Caps. Total penalties in a year may not exceed 10% of annual fees.",
}

def map_section(sid, text):
    # A stand-in for a focused model call on one chunk: "list every penalty clause, quoted, with the section".
    # TODO: return a list of {"quote": ..., "source": sid} for each sentence that starts with "Penalty:"
    return []

def reduce_results(results):
    # TODO: drop duplicate quotes (keep every source), then sort by first source
    return results

found = []
for sid, text in CONTRACT.items():
    found += map_section(sid, text)
final = reduce_results(found)
print("penalty clauses:", len(final))
for item in final:
    print(item)
Show a solution
CONTRACT = {
    "s1": "Scope. The supplier provides cleaning services to all sites.",
    "s2": "Fees. Invoices are due within 30 days of receipt.",
    "s3": "Penalty: late payment adds 2% per month to the unpaid amount.",
    "s4": "Service levels. Penalty: each missed visit costs 50 credits. See s9 for caps.",
    "s5": "Staff. The supplier vets all staff.",
    "s6": "Penalty: late payment adds 2% per month to the unpaid amount.",
    "s7": "Insurance. The supplier holds public liability cover.",
    "s8": "Termination. Either side may end the contract with 90 days notice. Penalty: early exit costs 3 months of fees.",
    "s9": "Caps. Total penalties in a year may not exceed 10% of annual fees.",
}
import re

def map_section(sid, text):
    sentences = re.split(r"(?<=\.)\s+", text)
    return [{"quote": s, "source": sid} for s in sentences if s.startswith("Penalty:")]

def reduce_results(results):
    merged = {}
    for r in results:
        merged.setdefault(r["quote"], []).append(r["source"])
    out = [{"quote": q, "sources": srcs} for q, srcs in merged.items()]
    return sorted(out, key=lambda r: int(r["sources"][0][1:]))

found = []
for sid, text in CONTRACT.items():
    found += map_section(sid, text)
final = reduce_results(found)
print("raw hits:", len(found))
print("penalty clauses:", len(final))
for item in final:
    print(f"[{', '.join(item['sources'])}] {item['quote']}")
refs = [sid for sid, t in CONTRACT.items() if re.search(r"\bs\d+\b", t)]
print("cross-references to check in a final pass:", refs)
Quick checkYou must list every penalty clause in a 900-page contract. What's a reliable approach?
How sure are you?
Pick an answer and how sure you are