Skip to content
AgenticAIWiki
  1. Learn
  2. Part 4
  3. 27. Parsing complex documents
  4. 27.5

Lesson 27.5 · 5 of 5 · 8 min read · Reviewed 24 Nov 2026

Lab: parse a report with tables and cite pages

By the end, you can

  • Build a small pipeline that turns parsed elements into page-cited chunks.
  • Check automatically that every citation points at a page that supports the claim.

What you will build

A small pipeline over a parsed annual report: elements in, page-cited answers out, with a check that the citationsCitations: References in an answer that point to the exact source passages supporting each claim. are honest. In the Playground lab the parsed elements are given to you as Python data, so you can focus on the steps after parsing. On a real machine you would get the same shape from a layout-aware parser (27.2).

elements (type, text, page)
   -> clean: drop headers and footers
   -> chunk: heading path + text, tables whole, page kept
   -> retrieve: top chunks for a question
   -> answer: cite pages as [p. N]
   -> check: each cited page supports the claim

Step 1: clean

Drop element types you never want to retrieve: header, footer, page numbers. Keep heading, paragraph, table, caption. Remember the most recent heading as you go, so each later element knows its section.

Step 2: chunk with the page

Turn each paragraph or table into a chunkChunking: Splitting documents into smaller passages before embedding and indexing them. that carries its context:

{"id": "c7", "page": 7, "section": "3. Plans",
 "text": "3. Plans > Table 2: Plan limits\n| Plan | Monthly credits | Refund window |\n..."}

Tables stay whole and keep their header row (27.3). A paragraph that runs onto the next page can be split at the page boundary, so each piece has one page number.

Step 3: retrieve

For the lab, a simple word-overlap score is enough to rank chunks. In a real system this is your vector or hybrid searchHybrid search: Combining keyword search (such as BM25) with semantic vector search and merging the results. (chapter 22). Return the top two or three chunks, each with its page.

Step 4: answer with page citations

Put each chunk in the prompt with its page, and ask for citations:

<chunk page="7">...</chunk>
<chunk page="4">...</chunk>
Answer only from the chunks. After each claim, cite the page as [p. N].
If the chunks don't contain the answer, say so.

Some APIs have a built-in citations feature that returns exact source spans; where you have it, use it. The check below still helps.

Step 5: check the citations

For each sentence in the answer:

  1. Find every [p. N].
  2. Confirm page N was among the retrieved chunks.
  3. Confirm a key figure or phrase from the sentence (a number, a plan name) appears in that page’s text.

This is a code check, so it is fast and runs on every test question. It doesn’t prove the claim is fully supported, which is the faithfulnessFaithfulness: Whether every claim in an answer is supported by the retrieved context. graderGrader: The part of an eval that decides whether an output passes, using code, a model or a person.’s job (26.2), but it catches the common failure of a correct fact with the wrong page.

Score it

Run four or five questions and record a small table:

Question Expected page Retrieved? Citation valid?
Pro refund window? 7 (table) yes yes
How many tickets in June? 12 (figure) yes yes
Who is the CEO’s dentist? none n/a says not in report

A table question and an unanswerable question are the two most informative cases. If the table question fails, revisit how tables are chunked. If the unanswerable one gets a confident answer, tighten the prompt.

Common mistakes

  • Losing page numbers in the cleaning step, then having nothing to cite.
  • Checking only that a citation exists, not that it points at the right page.
  • Merging chunks across pages so one chunk has two page numbers and citations become vague.

Key points

  • Start from parsed elements with type and page, not raw text: drop noise, keep tables whole, attach the heading path.
  • Every chunk carries its page number, and the prompt asks for answers that cite pages.
  • A code check can confirm that each cited page exists and contains the key figure in the claim.
  • Score the pipeline on a handful of questions, including one about a table and one the report can't answer.
Hands-on labRuns in the Playground

Parse a report and cite pages

Build the full pipeline from parsed elements to page-cited answers, with a code check that every citation points at a page that supports it.

You will have: A pipeline that prints, for each test question, the answer with [p. N] citations and a citation check result, plus a summary table.

Steps

  1. Clean: drop header and footer elements, and remember the current heading for each element.
  2. Chunk: one chunk per paragraph or table, with the heading path in front and the page kept.
  3. Retrieve: rank chunks by shared words with the question and keep the best one if it shares at least two words.
  4. Answer: return the best matching line from the chunk with [p. N], or 'Not in the report.' when nothing is retrieved.
  5. Check: for each [p. N], confirm the page was retrieved and contains the answer's key figure; run it on a deliberately wrong citation too.

Done when

  • The Pro question is answered with 30 days [p. 7] and the check passes.
  • The unanswerable question returns 'Not in the report.'
  • The deliberately wrong citation to page 9 fails the check.

Open in the Playground No API key needed.

Starter code (Python)
# Parsed elements from a short annual report, as a layout-aware parser would return them.
ELEMENTS = [
    {"type": "header", "text": "Acme annual report 2025", "page": 4},
    {"type": "heading", "text": "2. Support", "page": 4},
    {"type": "paragraph", "text": "Support tickets rose from 1,200 in January to 2,000 in June.", "page": 4},
    {"type": "footer", "text": "Page 4", "page": 4},
    {"type": "heading", "text": "3. Plans", "page": 7},
    {"type": "table", "text": "Table 2: Plan limits\n| Plan | Refund window |\n|---|---|\n| Basic | 14 days |\n| Pro | 30 days |", "page": 7},
    {"type": "footer", "text": "Page 7", "page": 7},
    {"type": "heading", "text": "4. Delivery", "page": 9},
    {"type": "paragraph", "text": "Standard delivery takes three to five working days.", "page": 9},
]
QUESTIONS = ["What is the refund window on the Pro plan?", "How many support tickets were there in June?", "Who audits the accounts?"]
STOP = {"the", "is", "on", "what", "how", "many", "were", "there", "in", "who", "a", "to"}

def words(t):
    return {w.strip(".,?:|").lower() for w in t.split()} - STOP

import re

def clean_and_chunk(elements):
    # TODO: drop header/footer; prefix each paragraph/table with its heading; keep the page
    return []

def retrieve(question, chunks):
    # TODO: best chunk by word overlap, or None if it shares fewer than 2 words
    return None

def answer(question, chunk):
    # TODO: best matching line of the chunk + f" [p. {chunk['page']}]"
    return "Not in the report."

def check(ans, retrieved):
    # TODO: every cited page must be retrieved and contain the answer's key figure
    return True

chunks = clean_and_chunk(ELEMENTS)
for q in QUESTIONS:
    hit = retrieve(q, chunks)
    a = answer(q, hit)
    print(q, "->", a, "| check:", check(a, [hit] if hit else []))
Show a solution
# Parsed elements from a short annual report, as a layout-aware parser would return them.
ELEMENTS = [
    {"type": "header", "text": "Acme annual report 2025", "page": 4},
    {"type": "heading", "text": "2. Support", "page": 4},
    {"type": "paragraph", "text": "Support tickets rose from 1,200 in January to 2,000 in June.", "page": 4},
    {"type": "footer", "text": "Page 4", "page": 4},
    {"type": "heading", "text": "3. Plans", "page": 7},
    {"type": "table", "text": "Table 2: Plan limits\n| Plan | Refund window |\n|---|---|\n| Basic | 14 days |\n| Pro | 30 days |", "page": 7},
    {"type": "footer", "text": "Page 7", "page": 7},
    {"type": "heading", "text": "4. Delivery", "page": 9},
    {"type": "paragraph", "text": "Standard delivery takes three to five working days.", "page": 9},
]
QUESTIONS = ["What is the refund window on the Pro plan?", "How many support tickets were there in June?", "Who audits the accounts?"]
STOP = {"the", "is", "on", "what", "how", "many", "were", "there", "in", "who", "a", "to"}

def words(t):
    return {w.strip(".,?:|").lower() for w in t.split()} - STOP

import re

def clean_and_chunk(elements):
    chunks, heading = [], ""
    for e in elements:
        if e["type"] in ("header", "footer"):
            continue
        if e["type"] == "heading":
            heading = e["text"]
            continue
        chunks.append({"id": f"c{len(chunks) + 1}", "page": e["page"], "text": f"{heading} > {e['text']}"})
    return chunks

def retrieve(question, chunks):
    score, best = max((len(words(question) & words(c["text"])), i) for i, c in enumerate(chunks))
    return chunks[best] if score >= 2 else None

def answer(question, chunk):
    if not chunk:
        return "Not in the report."
    lines = chunk["text"].split("\n")
    rows = [l for l in lines if l.startswith("|")][2:]  # skip the header row and separator
    if rows:
        lines = rows
    line = max(lines, key=lambda l: len(words(question) & words(l)))
    if line.startswith("|"):
        cells = [c.strip() for c in line.strip("|").split("|")]
        line = f"The {cells[0]} plan's refund window is {cells[1]}"
    else:
        line = line.split(" > ")[-1]
    return f"{line} [p. {chunk['page']}]"

def key_figure(sentence):
    m = re.search(r"\d[\d,]* (?:days|in June)|\d[\d,]*", sentence)
    return m.group(0) if m else None

def check(ans, retrieved, pages_text):
    cited = [int(n) for n in re.findall(r"\[p\. (\d+)\]", ans)]
    if not cited:
        return "no citation" if ans != "Not in the report." else "pass (refusal)"
    fig = key_figure(ans.split("[p.")[0])
    for n in cited:
        if n not in {c["page"] for c in retrieved}:
            return f"FAIL: page {n} was not retrieved"
        if fig and fig not in pages_text.get(n, ""):
            return f"FAIL: '{fig}' is not on page {n}"
    return "pass"

chunks = clean_and_chunk(ELEMENTS)
pages_text = {}
for c in chunks:
    pages_text[c["page"]] = pages_text.get(c["page"], "") + c["text"] + "\n"
print(f"{len(chunks)} chunks after cleaning")
for q in QUESTIONS:
    hit = retrieve(q, chunks)
    a = answer(q, hit)
    print(f"Q: {q}\nA: {a}\n   citation check: {check(a, [hit] if hit else [], pages_text)}")
wrong = "The Pro plan's refund window is 30 days [p. 9]"
print("wrong citation check:", check(wrong, chunks, pages_text))
Quick checkYour pipeline answers "The Pro refund window is 30 days [p. 9]", but the plan table is on page 7. Which check catches this automatically?
How sure are you?
Pick an answer and how sure you are

Finished the chapter? Take the chapter check.