Chapter 3 · Templates, Multimodal and Settings
Multimodal Prompt Design: Images, Scans, Tables and Long Documents
- Page 11 of 24
- 20 min read
So far every prompt in this tutorial has been text. Real work often starts as a photo of a receipt, a scanned contract or a 200-page report. The prompt design principles stay the same (clear task, fixed output, checks in code), but new failure modes appear: the model may misread a blurry digit, point at the wrong part of a page, or drop a deadline from page 140 when it summarises. This page shows how to design prompts for these inputs and, more importantly, how to write code that checks what comes back.
There are two common designs: the model looks at the image directly, or an OCR or vision step turns the image into text first and a second prompt works on that text. This page has no images. It models the second design: the data is "what the OCR or vision step returned", written as text with deliberate slips (a letter O instead of a zero). You need Python 3.12 or newer and promptlab.py; the blocks share variables, so type them in order. Where we need a "summariser" we use a toy stand-in that demonstrates the method; it is not model behaviour, and the page says so each time.
What you will learn
- How to write an image question with an answer contract, ask for evidence from regions, and check that the evidence exists.
- How to tell an OCR error from a reasoning error, and how to extract a scanned table with digit and arithmetic checks.
- How to point a prompt at specific pages, check long answers against section references, and split a large input into units.
- How to summarise in levels without losing critical details, and how to compare whole-document and chunked summaries.
Image questions with an answer contract
Design prompts for image question answering like any extraction task: say what the image is, restrict the model to what is visible, give it a permitted way to say "I cannot tell", and fix the output format. Label each input ("Image 1") and put the question last.
Weak prompt:
Read this invoice and tell me the total.Better prompt:
Image 1 is a photo of a paper invoice. It may be slightly rotated or have small print.
Use only what you can read in Image 1. Do not use outside knowledge.
If the digits are too small, blurred or cut off, set certainty to cannot_tell and answer to null.
Reply with JSON only, with the keys answer, evidence and certainty.
evidence: the exact characters you read and where they are (for example "bottom right, Total").
certainty: clear, unclear or cannot_tell.
Question: what is the total due?What changed: the image has a label and a description; outside knowledge is excluded; the model has an honest exit (cannot_tell); and the evidence must be exact characters, so a person can compare them with the image. Providers differ on where the image goes relative to the text, so try both orders on your own examples.
Provider note (as of 2026-10-12): OpenAI and Anthropic document that image models can struggle with small, rotated or blurred text, precise spatial localisation and exact counting; Anthropic adds that heavy JPEG compression can make text unreadable and that image metadata is not read; Google advises checking rotation and says higher media resolution improves fine-text recognition at a higher token cost. Both OpenAI and Anthropic say their image features are not suitable for medical diagnosis. Anthropic's guide says images work best before text and suggests labelling multiple images; Google's example puts the text before a single image. Supported formats, size limits and token accounting differ and change, so check the current documentation.
A reply is only a draft until the contract is checked. The function below enforces the contract in plain Python. The four replies are invented, only to test the checker.
import json, re
KINDS = {"clear", "unclear", "cannot_tell"}
def check_image_answer(raw):
"""The answer contract for an image question. Returns a list of problems (empty means it passed)."""
try:
data = json.loads(raw)
except json.JSONDecodeError:
return ["not JSON"]
if not isinstance(data, dict) or set(data) != {"answer", "evidence", "certainty"}:
return ["keys must be answer, evidence, certainty"]
problems = []
if data["certainty"] not in KINDS:
problems.append(f"certainty must be one of {sorted(KINDS)}")
if data["certainty"] == "cannot_tell" and data["answer"] is not None:
problems.append("cannot_tell needs answer null")
if data["certainty"] != "cannot_tell" and not data["evidence"]:
problems.append("an answer needs evidence")
return problems
REPLIES = { # invented replies, used only to test the checker
"complete": '{"answer": "75.00", "evidence": "R3: Total due", "certainty": "clear"}',
"no evidence": '{"answer": "75.00", "evidence": "", "certainty": "clear"}',
"guess": '{"answer": "75.00", "evidence": null, "certainty": "cannot_tell"}',
"prose": "The total is 75.00.",
}
for name, raw in REPLIES.items():
print(f"{name:12}", check_image_answer(raw) or "ok")complete ok
no evidence ['an answer needs evidence']
guess ['cannot_tell needs answer null']
prose ['not JSON']Here is a typical failure pattern, shown as an invented reply:
Example reply (illustrative; yours will differ):
{"answer": "75.00", "evidence": "Total due: 75.00, bottom right", "certainty": "clear"}It passes the contract. The next section shows why a passing contract is not enough.
Evidence from specific regions
Ask for evidence from specific image regions. A bare answer cannot be checked; an answer with a region and a quote can. Models are approximate at pointing (see the provider note), so ask for coarse regions ("bottom right", or an id from your own layout step) and verify them. Below, the OCR step returned three regions with ids. The prompt asks the model to cite a region id and quote the characters exactly; the code checks both. The scan has deliberate slips (04l7, 2026-O3-02, 7S.00).
SCAN = { # what the OCR step returned for one scanned invoice (invented); the slips are deliberate
"R1": "lnvoice 04l7 | Rivera Tools | 2026-O3-02",
"R2": "Bolts x 12 @ 3.50 = 42.00\nGloves x 4 @ 8.25 = 33.00",
"R3": "Total due: 7S.00",
}
def check_evidence(items, scan=SCAN):
"""Every cited region must exist and the quote must appear in it, character for character."""
problems = []
for item in items:
region, quote = item["region"], item["quote"]
if region not in scan:
problems.append(f"{region}: no such region")
elif quote not in scan[region]:
problems.append(f"{region}: quote not found {quote!r}")
return problems or ["all evidence found"]
print(check_evidence([{"region": "R3", "quote": "Total due: 7S.00"}]))
print(check_evidence([{"region": "R3", "quote": "Total due: 75.00"}]))
print(check_evidence([{"region": "R4", "quote": "Total"}, {"region": "R2", "quote": "Gloves x 4"}]))['all evidence found']
["R3: quote not found 'Total due: 75.00'"]
['R4: no such region']The first quote matches the scan, slips included: that is a faithful copy. The second is the dangerous one: the answer quoted "Total due: 75.00", which is not what the scan says. The model (or a person) silently corrected the text. It may even be right, but you can no longer tell whether the model read the image or guessed, so the check fails it. Tell the model to copy exactly and not to correct, then check that it did.
OCR errors versus reasoning errors
Distinguish OCR errors from reasoning errors. A wrong answer has two possible causes, and the fixes differ. If the scan already says 7S.00, no prompt about arithmetic will help: improve the image (crop, enlarge, fix rotation), the OCR step, or ask a person. If the scan is right and the answer is wrong, the prompt or the task design needs work. To tell them apart you need three things: a reference that a person checked against the original, the text the OCR step returned, and the model's answer. Real work uses a small hand-checked sample for this.
TRUTH = {"R1": "Invoice 0417 | Rivera Tools | 2026-03-02", "R2": SCAN["R2"], "R3": "Total due: 75.00"} # checked by a person
SLIP = re.compile(r"\b(?=\w*\d)(?=\w*[OolISB])[\dOolISB.,]+\b") # digits mixed with look-alike letters
print(SLIP.findall(" ".join(SCAN.values())))
def diagnose(region, answer):
seen, want = (re.search(r"\S+$", d[region]).group() for d in (SCAN, TRUTH))
if seen != want:
return "OCR error, answer copied it" if answer == seen else "OCR error; answer differs from the scan"
return "ok" if answer == want else f"reasoning error: scan is right ({seen}), answer is {answer}"
for region, answer in [("R3", "7S.00"), ("R3", "75.00"), ("R2", "8.25"), ("R2", "33.00")]:
print(region, answer, "->", diagnose(region, answer))['04l7', 'O3', '7S.00']
R3 7S.00 -> OCR error, answer copied it
R3 75.00 -> OCR error; answer differs from the scan
R2 8.25 -> reasoning error: scan is right (33.00), answer is 8.25
R2 33.00 -> okThe digit check at the top is a cheap alarm for look-alike slips: it flags tokens that mix digits with letters such as O, l, I, S, B. The four cases show the possible verdicts. Case 2 deserves care: the answer is correct but differs from the scan, so you cannot know how it got there.
Tables from scanned documents
Prompt for table extraction from scanned documents with a fixed schema, an exact-copy rule and a permitted empty value:
Prompt:
<scan_text>
(table text from the OCR step goes here)
</scan_text>
Task: the text above is OCR output of a scanned table and may contain recognition slips.
Copy each cell exactly as written. Do not correct, round or fill in anything.
If a cell is empty or unreadable, use null.
Reply with JSON only: a list of rows with the keys item, qty, unit, amount. Keep the total row.The checks matter more than the prompt. Below, a stand-in parser splits the cells exactly as read (so we can test the checks), then three independent checks run: each numeric cell is a plain number, each row satisfies quantity times unit price equals amount, and the rows add up to the stated total. A slip such as 33.OO or l0 is reported, not silently repaired. The last step shows a candidate repair that the arithmetic supports; a person still confirms it against the image.
from decimal import Decimal as D
TABLE = """Item | Qty | Unit | Amount
Bolts | 12 | 3.50 | 42.00
Gloves | 4 | 8.25 | 33.OO
Tape | l0 | 1.20 | 12.00
Total | | | 87.00""" # OCR output (invented); the letters O and l are slips for 0 and 1
def parse_table(text):
"""Stand-in for the model's extraction: split cells exactly as read, never correct them."""
head, *rows = [[cell.strip() for cell in line.split("|")] for line in text.splitlines()]
return [dict(zip([h.lower() for h in head], row)) for row in rows]
NUM = re.compile(r"\d+(\.\d{2})?")
def check_table(rows):
problems, total = [], D(0)
for i, row in enumerate(rows[:-1], 1):
bad = [c for c in ("qty", "unit", "amount") if not NUM.fullmatch(row[c])]
problems += [f"row {i} {c}: {row[c]!r} is not a plain number" for c in bad]
if not bad:
if D(row["qty"]) * D(row["unit"]) != D(row["amount"]):
problems.append(f"row {i}: qty x unit is not amount")
total += D(row["amount"])
if not problems and total != D(rows[-1]["amount"]):
problems.append(f"rows add up to {total}, total says {rows[-1]['amount']}")
return problems or ["table passes"]
rows = parse_table(TABLE)
print(check_table(rows))
FIX = str.maketrans("OolISB", "001158") # a SUGGESTION, to be confirmed by a person
candidate = [{k: v.translate(FIX) if k != "item" else v for k, v in row.items()} for row in rows]
print(check_table(candidate))["row 2 amount: '33.OO' is not a plain number", "row 3 qty: 'l0' is not a plain number"]
['table passes']Long documents: pages, sections and units
Specify the relevant pages of a long document. Do not paste 200 pages and hope. Select the pages, label each one, put the document first and the question last, and say what to do when the pages do not answer. The invented four-page agreement below stands in for a long contract; its OCR version has slips on pages 3 and 4.
from promptlab import render
PAGES = {
1: "Service agreement between Kestrel Logistics (supplier) and Harbour Foods (customer). Start date: 2026-03-01. "
"The initial term is 24 months. Renewal is automatic for 12 months unless notice is given.",
2: "Monthly fee is EUR 4,200.00. A late payment fee of 1.5% applies after 15 days. "
"Fees rise by 3% each 1 January. Invoices are issued on the 5th.",
3: "Either party may end this agreement with 90 days written notice. The customer may end it at once "
"if uptime is below 99.0% in two months in a row. Notices go to [email protected].",
4: "Service credits depend on monthly uptime. Uptime 99.0 to 99.5%: credit 5%. "
"Uptime 98.0 to 99.0%: credit 10%. Uptime below 98.0%: credit 25%.",
}
SLIPS = {3: ("90 days", "9O days"), 4: ("98.0 to", "98.O to")} # deliberate OCR slips
OCR_PAGES = {n: t.replace(*SLIPS[n]) if n in SLIPS else t for n, t in PAGES.items()}
ASK = """{document}
Question: {question}
Answer only from the pages above. After each claim cite the page like [p3] and quote the words you used.
If the pages do not say, answer NOT FOUND."""
def page_prompt(pages, question, source=OCR_PAGES):
document = "\n".join(f'<page n="{n}">\n{source[n].replace("<", "<")}\n</page>' for n in pages)
return render(ASK, document=document, question=question)
print(page_prompt([3], "How long is the notice period?"))<page n="3">
Either party may end this agreement with 9O days written notice. The customer may end it at once if uptime is below 99.0% in two months in a row. Notices go to [email protected].
</page>
Question: How long is the notice period?
Answer only from the pages above. After each claim cite the page like [p3] and quote the words you used.
If the pages do not say, answer NOT FOUND.Provider note (as of 2026-10-12): Anthropic's guidance puts long documents near the top and the query after them, and suggests asking the model to quote the relevant parts first; Google puts the question at the end, after the context; OpenAI advises putting reusable content at the start of a prompt for caching. Providers agree on "long material first, question last". Context limits and per-page costs differ by provider and model; check the current documentation.
Use section references to check long-document answers. The prompt asks for a page reference and a quote after each claim. That turns "does this sound right?" into questions your code can answer: does the page exist, and does the quoted text really appear in it? A fluent citation is not evidence, because models can invent references, so the code looks for the quote. A near match often means an OCR slip rather than a made-up quote, so that case is reported separately. The five claims are invented.
from difflib import SequenceMatcher
def best_ratio(quote, text):
return max(SequenceMatcher(None, quote, text[i:i + len(quote)]).ratio() for i in range(len(text) - len(quote) + 1))
def verify(answer, source=OCR_PAGES):
"""One claim per line. Check the page exists and that each quote appears in the cited page."""
for line in answer.strip().splitlines():
pages = [int(n) for n in re.findall(r"\[p(\d+)\]", line)]
quotes = re.findall(r'"([^"]+)"', line)
if not pages:
status = "no page reference"
elif any(n not in source for n in pages):
status = "cites a page that does not exist"
elif not quotes:
status = "reference, but no quote to check"
else:
text = " ".join(" ".join(source[n].split()) for n in pages)
score = best_ratio(quotes[0], text)
status = "quote found" if quotes[0] in text else "near match: OCR slip? compare with the image" if score >= 0.9 else "QUOTE NOT FOUND"
print(f"{status:46} | {line[:44]}")
verify('''The notice period is 90 days [p3]: "90 days written notice"
Monthly fee is EUR 4,200.00 [p2]: "Monthly fee is EUR 4,200.00"
The customer may leave after six months [p1]: "end at any time after six months"
Credits go up to 25% [p4]
The contract starts in March 2026.''')near match: OCR slip? compare with the image | The notice period is 90 days [p3]: "90 days
quote found | Monthly fee is EUR 4,200.00 [p2]: "Monthly f
QUOTE NOT FOUND | The customer may leave after six months [p1]
reference, but no quote to check | Credits go up to 25% [p4]
no page reference | The contract starts in March 2026.Line 1 is a near match: the quote has 90, the scan 9O. Line 3 quotes words that are not on page 1, so it needs rejecting or investigating. Lines 4 and 5 cannot be verified at all. None of this proves a claim true; it removes the claims that have no support in the text you supplied.
Split a large input into defined processing units. When the input is too large for one call or too long to check, cut it into units with ids, along natural boundaries (whole pages or sections, never mid-sentence or mid-table), and process each unit with the same prompt. Then test the split itself:
def pack(pages, limit):
"""Group whole pages into units of at most `limit` characters; a page is never split."""
units, current = [], []
for n in sorted(pages):
if current and sum(len(pages[m]) for m in current) + len(pages[n]) > limit:
units.append(current)
current = []
current.append(n)
return units + [current]
units = pack(PAGES, 330)
print({f"U{i}": u for i, u in enumerate(units, 1)})
print("every page once, in order:", [n for u in units for n in u] == sorted(PAGES))
print("sizes:", [sum(len(PAGES[n]) for n in u) for u in units]){'U1': [1], 'U2': [2, 3], 'U3': [4]}
every page once, in order: True
sizes: [198, 324, 140]Summaries in levels
Summarise sections before creating a global summary. Summarise each unit with the same prompt, then summarise the summaries. This keeps each call small and every section represented. The cost is that every level can drop details, and a detail dropped at level 1 can never come back at level 2.
Preserve critical details during hierarchical summarisation. Decide what must never be lost (amounts, dates, deadlines, names, contact addresses) and say so in the section prompt. Better, do not rely on the summary at all for those: collect critical facts with an extraction step and a pattern check, carry them in a separate list, and attach them to the final summary in code.
Prompt:
Summarise the section below in at most two sentences.
Keep every amount, date, deadline, percentage, name and e-mail address exactly as written.
Do not round numbers. If the section has none of these, say so.Compare whole-document and chunked summaries. The code below does this comparison with a toy summariser that simply keeps the first sentences. It is a stand-in that demonstrates the method and the lost-detail effect, not how a model summarises: real models keep and drop different things, less predictably, which is why you must measure. The measurement is recall of critical details: how many items of a hand-written must-keep list survive.
MUST = ["2026-03-01", "24 months", "4,200.00", "1.5%", "90 days", "99.0%", "25%", "[email protected]"]
FACT = re.compile(r"\d{4}-\d{2}-\d{2}|EUR [\d,]+\.\d{2}|\d+(?:\.\d+)?%|\d+ (?:days|months)|[\w.]+@[\w.]+\w")
def toy_summary(text, k):
"""Stand-in summariser: keeps the first k sentences. It demonstrates the method, not model behaviour."""
return " ".join(re.split(r"(?<=\.)\s+", " ".join(text.split()))[:k])
def summaries(pages):
chunked = toy_summary(" ".join(toy_summary(p, 1) for p in pages.values()), 3)
facts = list(dict.fromkeys(f for p in pages.values() for f in FACT.findall(p))) # collected by code
return {"whole document": toy_summary(" ".join(pages.values()), 3), "chunked": chunked,
"chunked + carried facts": chunked + " Key facts: " + "; ".join(facts)}
def compare(pages, must):
for name, text in summaries(pages).items():
lost = [m for m in must if m not in text]
print(f"{name:24} kept {len(must) - len(lost)}/{len(must)}, {len(text):4} chars, lost {lost}")
compare(PAGES, MUST)whole document kept 2/8, 139 chars, lost ['4,200.00', '1.5%', '90 days', '99.0%', '25%', '[email protected]']
chunked kept 2/8, 178 chars, lost ['2026-03-01', '24 months', '1.5%', '99.0%', '25%', '[email protected]']
chunked + carried facts kept 8/8, 322 chars, lost []Neither plain version keeps more than 2 of 8, and they lose different details: where a method looks decides what survives. Carrying the collected facts beside the summary keeps all 8. The carried list also has its own limit: it holds only what the patterns recognise, so review the patterns on your documents. Measuring this on a real model, with positions and sizes varied, is the topic of Long-Context Evaluation: Chunking, Position Tests and Lost Details.
Where this shows up at work
Accounts teams read invoices from photos; legal teams ask questions of long contracts; analysts pull tables out of scanned reports. In all of them the working pattern is the same: a fixed output, evidence the code can look up, checks on digits and totals, and a person confirming whatever the checks flag.
Common mistakes
- Trusting a clean-looking number. A model can quietly fix a slip, or invent a digit. Ask for exact copies and check digits and totals.
- Debugging the prompt when the scan is wrong. Check the OCR text first; a prompt cannot fix a misread digit.
- Accepting fluent references. A page number and a quote that is not on the page is a made-up citation. Look the quote up.
- Splitting in the middle of a table or sentence. Cut on page or section boundaries and test that every page appears once.
- Letting a summary carry critical facts. Each level drops detail. Carry the facts separately and measure recall.
Try it yourself
Use the blocks above in the same Python session.
- Easy. Run the slip detector on the OCR text
"Due 3O days, ref 1l42, 25 items"and say which tokens it flags and why. - Medium. Write
outside(answer, allowed)that returns the pages cited in an answer that were not in the prompt, and test it on two answers. - Hard. Add a fifth page about insurance to the agreement and show that the chunked summary loses its amount and deadline while the carried-facts version keeps them.
Answers
Easy.
print(SLIP.findall("Due 3O days, ref 1l42, 25 items"))['3O', '1l42']Pass checklist: 3O and 1l42 are flagged because they mix digits with look-alike letters; 25 is not, because it is plain digits. A flag means "look at the image", not "the value is wrong".
Medium.
def outside(answer, allowed):
"""Pages cited in the answer that were not in the prompt."""
return sorted({int(n) for n in re.findall(r"\[p(\d+)\]", answer)} - set(allowed))
print(outside("Notice is 90 days [p3]. Fees are EUR 4,200.00 [p2].", [3]))
print(outside("Notice is 90 days [p3].", [3]))[2]
[]Pass checklist: the function returns a sorted list; it finds a page the prompt never contained (page 2 here); it returns an empty list when all citations are inside the selection. This is the same idea as validating a stage's output before the next stage, from Prompt Chaining: Stages, Fixed Schemas and the promptlab Helper.
Hard. The new page has an amount and a deadline; extend the must-keep list and rerun the comparison.
PAGES5 = {**PAGES, 5: "Kestrel keeps liability cover of EUR 2,000,000.00. Claims must be reported within 14 days."}
compare(PAGES5, MUST + ["2,000,000.00", "14 days"])whole document kept 2/10, 139 chars, lost ['4,200.00', '1.5%', '90 days', '99.0%', '25%', '[email protected]', '2,000,000.00', '14 days']
chunked kept 2/10, 178 chars, lost ['2026-03-01', '24 months', '1.5%', '99.0%', '25%', '[email protected]', '2,000,000.00', '14 days']
chunked + carried facts kept 10/10, 349 chars, lost []Pass checklist: the new items are in the must-keep list; the plain versions still keep only 2 of 10; the carried-facts version keeps all 10; you can say what the fact patterns would miss (for example an amount written in words).
Summary
- For images and scans, fix the output format, give the model an honest exit, ask for evidence, and check the evidence in code.
- Separate OCR errors from reasoning errors with a hand-checked reference; flag look-alike digits and reconcile tables with arithmetic.
- Select and label pages, put the document first and the question last, and check page references and quotes against the source.
- Split on natural boundaries with ids, and test the split. Carry critical facts beside hierarchical summaries and measure recall.
Next: Long-Context Evaluation: Chunking, Position Tests and Lost Details, where you test how well a prompt keeps early, middle and late facts in long inputs.

