Sub topic 10
Working with images, audio, and documents
This chapter covers multimodal features: applications where the model reads or produces something other than plain text. It assumes you can write basic Python, call a model API, and read JSON. You should also be comfortable with the prompting and structured-output ideas from earlier chapters.
What "multimodal" means in practice
A modality is a kind of data, such as text, images, or audio. A multimodal model accepts more than one kind as input, produces more than one kind as output, or does both. Most products use only a few combinations:
| Input | Output | Typical use |
|---|---|---|
| Image + text question | Text | Describe a photo, read a chart, check a screenshot |
| Scanned page or PDF | Text or JSON | Invoice extraction, form reading |
| Audio | Text | Meeting transcripts, voice commands |
| Text | Audio | Spoken replies, narration |
| Text | Image | Illustrations, mockups |
Many services handle these with separate components rather than one model. A speech-to-text model produces a transcript, and a text model works on the transcript. Both designs are common, and the choice affects cost, latency, and where errors enter.
How non-text input reaches the model
A language model works on tokens. Non-text input is converted into a form it can use.
- Images are split into patches and encoded into vectors that sit in the prompt next to text tokens. The model has no separate "eyes". It reads the image through this encoding.
- Audio is usually turned into text first by a speech recognition model. Some models take audio directly, which keeps tone and pauses but costs more.
- Documents are either converted to text by a parser, or rendered as page images and read visually.
Because images become tokens, they count against the context limit and the bill. A high-resolution image can cost as much as several paragraphs of text. Many APIs resize large images, so small print can become unreadable before the model sees it.
Reading images
Typical image tasks are captioning, answering questions about a picture, reading text in a picture (OCR, short for optical character recognition), and interpreting charts or screenshots.
Strengths and limits to plan for:
- Models read clear printed text well. Handwriting, low contrast, and skewed photos lower accuracy.
- Models are weak at precise counting, exact positions, and fine spatial reasoning. "How many bolts are in this photo?" is risky.
- Charts are read approximately. A model may state a bar's value from its visual height and be off. If you have the underlying data, send the data instead.
- Models can describe things that are not there, the same hallucination problem as in text.
Most APIs accept an image as a URL or as base64 text inside a JSON message. The exact field names differ by provider, so the sketch below wraps the call in a complete_with_image function you supply, in the same way earlier chapters used complete.
import base64
import json
def encode_image(path: str) -> str:
with open(path, "rb") as f:
return base64.b64encode(f.read()).decode("ascii")
def read_receipt(path: str, complete_with_image) -> dict:
prompt = (
"Read this receipt. Reply with JSON only, using the keys "
'"merchant" (string) and "total" (number). '
"Use null for any value you cannot read."
)
raw = complete_with_image(prompt, encode_image(path))
data = json.loads(raw)
if not isinstance(data, dict):
raise ValueError("expected a JSON object")
return dataThe instruction "use null for any value you cannot read" matters. Without it, the model tends to guess, and a guessed total looks the same as a real one.
Working with audio
Audio features come in two parts: transcription and speech synthesis.
Transcription converts speech to text. Things that affect quality:
- Background noise, accents, and several people talking at once.
- Domain vocabulary, such as drug names or product codes. Many services let you supply a word list.
- Speaker labels (diarization), which say who spoke each segment. Not every service provides them, and they are often wrong when voices overlap.
- Timestamps, which you need if users must jump to the moment in the recording.
A common pipeline transcribes first, then asks a text model to summarize or extract action items. Errors compound: a misheard name in the transcript becomes a wrong name in the summary. Keep the raw transcript so a person can check.
Speech synthesis converts text to audio. For voice assistants, latency dominates. Streaming the reply to the speech component sentence by sentence makes the assistant start speaking sooner than waiting for the full answer.
Working with documents
Documents are the most common multimodal workload in business. The first decision is whether the file has a text layer.
- A digital PDF usually contains real text. A parser can extract it quickly and exactly, with no recognition errors.
- A scanned PDF is only pictures of pages. It needs OCR or a vision model.
- Many files mix both, so check page by page.
Layout is the hard part. Tables, multi-column pages, headers, footers, and footnotes can come out of a parser in the wrong reading order. A table flattened into lines of text loses which number belongs to which column. Options are to use a parser that outputs tables as Markdown or CSV, or to send the page as an image so the model sees the layout.
Long documents need splitting. A hundred-page report may exceed the context window, and even when it fits, accuracy on details in the middle can drop. Split by section or page, process each part, then combine. For question answering over many documents, split into chunks and use retrieval, as covered in the embeddings and retrieval chapters.
Validate and keep a human in the loop
Extraction from images and scans fails more quietly than extraction from clean text. A misread digit still produces valid JSON. Add checks that do not depend on the model:
def check_receipt(data: dict) -> list[str]:
problems = []
if not isinstance(data.get("merchant"), str):
problems.append("merchant missing")
total = data.get("total")
if not isinstance(total, (int, float)):
problems.append("total missing or not a number")
elif total <= 0 or total > 10000:
problems.append("total outside expected range")
return problems
print(check_receipt({"merchant": "Acme", "total": 129.5}))
print(check_receipt({"merchant": None, "total": -4}))Other useful checks:
- Line items should add up to the stated total.
- Dates should parse and fall in a plausible range.
- Ask the model for the same field twice by two routes (for example, parsed text and page image) and flag disagreements.
- Send low-confidence or failed items to a person for review.
Privacy and cost
Images and audio often contain more than you intend: faces, license plates, background voices, metadata such as GPS coordinates in photos. Check what your provider stores and for how long, and strip metadata you do not need. Audio recordings of people may also require consent under local law.
On cost, an image or a minute of audio is usually more expensive than the equivalent text. Reduce it by cropping to the relevant region, lowering resolution when the content is large and clear, and using a parser instead of vision for digital PDFs.
Common mistakes
- Sending a scan at low resolution and expecting small print to be read.
- Using vision for a digital PDF that has a perfectly good text layer.
- Trusting counts, measurements, or chart values.
- Discarding the raw transcript or page text, which removes the way to audit results.
- Skipping validation because the output "looks like" valid JSON.
Exercise
A company wants to extract the total from thousands of PDF invoices. Some PDFs were exported from accounting software, and others are phone photos saved as PDFs. Describe the pipeline you would build and name two checks that do not rely on the model.
Show answer
Check each page for a text layer. Pages with one go through a text parser, which is cheaper and exact. Pages without one go through OCR or a vision model, with a resolution high enough to read small print. Both routes send the content to a model with a prompt requesting JSON, using null for unreadable fields. Validate the JSON. Two checks that do not use the model: the line items must sum to the stated total, and the total must fall within a plausible range. Items that fail go to human review.
Exercise
A meeting summarizer lists "Maria Kowalski" as an action-item owner, but nobody by that name attended. Where in the pipeline could the error have started, and what design choice helps you find it?
Show answer
The speech-to-text step most likely misheard a name, and the summarizing model then repeated it. The summarizer could also have invented the name. Keeping the raw transcript, ideally with timestamps, lets a person compare the summary to what the transcript says and see which step introduced the error. A supplied vocabulary list of attendee names can reduce the misrecognition.