MODULE 3.3

🎞️ Advanced Multimodal AI

How a model sees an image, reads a difficult document, speaks in real time without stalling, understands a video, and operates a screen. For each case, the architecture, cost, and how to measure whether it’s working — with local scripts you can run today.

7
Topics
~55
Minutes
Advanced
Level
Architecture
Type
0%
0 of 0 topics read · Section 1 of 7

Detailed content

1

👁️ How a multimodal model sees

A language model only knows how to work with a sequence of vectors. For it to “see” an image, something has to convert the pixels into that same format. The most common approach has three parts: a visual encoder (a network that converts the image into vectors — usually a Vision Transformer, or ViT, which cuts the image into small squares called patches), a projection layer (which translates those vectors into the LLM’s internal “language”) and the LLM itself, which then reads image tokens alongside text tokens.

There are two designs. In the coupled, a pretrained visual encoder (the CLIP/SigLIP family, trained to align images and captions) is connected to a ready-made LLM, and only the projection and some fine-tuning are trained — this is the approach used by open models like LLaVA and Llama 3.2 Vision. In the native, the model is trained from the start on a mix of text, images, and sometimes audio; this is what labs describe for the GPT, Gemini, and Claude model lines. Native models tend to reason better across modalities; coupled models are cheaper to adapt and run locally.

What it is

A multimodal model is an LLM that takes in (and sometimes produces) more than one type of data. Images, audio, and video are converted into tokens by their own encoders and enter the same context window as text — taking up space and costing as much as text.

image in patches visual encoder ViT · CLIP/SigLIP projection translates for the LLM image tokens text LLM same context window “What’s the total on this receipt?” text response trained with the coupled approach: projection (+ adjustments) · native: everything together
How to read: follow the arrows from left to right. The purple squares are tokens from the image; the blue ones are from your question. Both go into the LLM together — that’s why a large image “uses up” context and costs as much as a lot of text.

💡 Tip

Resolution is a cost dial. Many providers resize the image or charge by pixel blocks; sending a 12-megapixel photo to read a three-digit number wastes tokens. Crop and resize it before sending, and measure whether accuracy drops.

Why learn

Knowing that an image becomes tokens explains cost, latency, and limits — why tiny text in a large photo fails, why ten scanned pages exceed the context window — and guides the choice between a native frontier model and an open coupled model that runs inside the company.

Key concepts

Visual encoder
pixels into vectors
Projection
bridge to the LLM
Image token
uses context and costs money
Native × coupled
quality × adaptability
2

📄 Complex documents

Much of the value of multimodal AI in companies lies in paperwork: invoices, scanned contracts, medical reports, and reports with tables and charts. The classic approach is OCR (optical character recognition), which turns the image into running text and loses the layout — the table becomes a jumble of numbers. Visual reading by a multimodal model sees the entire page: it knows that a number is in the “Total” column and the “March” row.

In practice, the mature architecture is hybrid. For PDFs with embedded text, extract the text directly (it’s accurate and inexpensive). For a scanned page, dense table, or chart, render the page as an image and send it to the model with a fixed output schema (JSON with defined fields). For high volumes and standardized fields, specialized OCR remains cost-competitive. The rule that applies to all of them: ask for null when a field isn’t legible, instead of letting the model guess.

What it is

Structured document extraction: an image or PDF goes in, and validated JSON with known fields comes out. The model reads the layout; your code checks the format, totals, and consistency before saving it.

InputBest approachCaution
Digital PDF (selectable text)Extract the text directly; use an LLM only to structure it.Tables may be misaligned; check the columns.
Scanned page or photoSend the page as an image to the multimodal model.Minimum legible resolution; similar-looking digits (1/7, 0/8).
ChartModel describes trends and reads labels.Values read “by eye” are approximate; prefer the source spreadsheet.
HandwritingMultimodal model with mandatory human review.Much higher error rate; never save without checking.

Try this: extract fields from a receipt with a local vision model (Ollama), using only Python’s standard library.

#!/usr/bin/env python3
# extrai_recibo.py — reads a receipt image and returns JSON with fixed fields.
# Before running: ollama pull llama3.2-vision   (runs locally, with no per-call cost)
# Usage:   python3 extrai_recibo.py <receipt.jpg>
import base64, json, sys, urllib.request

URL = "http://localhost:11434/api/chat"
MODELO = "llama3.2-vision"
CAMPOS = ["emitente", "cnpj", "data", "valor_total", "forma_pagamento"]

def extrair(caminho):
    with open(caminho, "rb") as f:
        img = base64.b64encode(f.read()).decode()
    pedido = {
        "model": MODELO,
        "stream": False,
        "format": "json",
        "options": {"temperature": 0},
        "messages": [{
            "role": "user",
            "content": (
                "Read the receipt in the image and respond with ONLY JSON using the keys "
                + ", ".join(CAMPOS)
                + ". Date format: YYYY-MM-DD; valor_total as a number with a decimal point. "
                "If a field isn’t legible, use null. Don’t make up values."
            ),
            "images": [img],
        }],
    }
    req = urllib.request.Request(URL, data=json.dumps(pedido).encode(),
                                 headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=300) as r:
        resposta = json.load(r)
    dados = json.loads(resposta["message"]["content"])
    return {c: dados.get(c) for c in CAMPOS}

if __name__ == "__main__":
    print(json.dumps(extrair(sys.argv[1]), ensure_ascii=False, indent=2))

How to check: run it with three receipts whose contents you know by heart. The output must have exactly the five keys; compare each value with the paper. Then cover the CNPJ with a strip and run it again: the field must be null, not a made-up number. A paid multimodal API works the same way; you just change the URL, key, and message format.

✓ Do

  • ✓Fixed output schema, validated in code.
  • ✓Business checks: the sum of the items matches the total, and the CNPJ has a valid check digit.
  • ✓Human review queue for anything that fails a check.

✗ Avoid

  • ✗Asking “extract everything” without listing the fields.
  • ✗Saving to the ERP without automatic validation.
  • ✗Sending a document with personal data to a service without an appropriate contract.

Why learn

Document extraction is by far one of the multimodal use cases with the easiest returns to measure: hours of data entry become minutes of review. But only if the architecture includes a schema, validation, and review—without those, silent errors enter the accounting system.

Key concepts

OCR
text without layout
Visual reading
understands the page
Output schema
fixed fields in JSON
honest null
illegible doesn’t mean guess
3

🎙️ Real-time voice

Voice conversations are the case where latency go ahead. In a text chat, waiting a few seconds is acceptable; in a call, a long pause sounds like the line has dropped. There are two architectures. The cascade chains three models: STT (speech-to-text, speech to text, like Whisper), a text LLM, and TTS (text-to-speech, text to speech). The speech-to-speech uses a single model that listens to audio and responds with audio, like the real-time voice modes offered by major providers.

The cascade is modular: you can swap each component, save the transcript for auditing, and use whichever LLM you want, including a local one. The tradeoff is that the wait times at each stage add up, and the tone of voice is lost along the way. Speech-to-speech responds faster and captures intonation, but offers less control and is harder to audit. In both, two components are decisive: VAD (voice activity detection, a detector for when the person starts and stops speaking) and barge-in (the ability to stop speaking when the user interrupts).

What it is

A real-time voice system is a continuous loop of listening, deciding when the turn ends, thinking, and speaking—with a time budget for each stage and the possibility of being interrupted at any moment.

CASCADE microphone VAD STT e.g., Whisper LLM TTS speaker end of turn transcribe 1st token 1st audio total wait = sum of the stages → stream at each stage SPEECH-TO-SPEECH microphone one model: listens to audio, responds with audio captures tone and rhythm · less control and auditing speaker barge-in: user talks over it → the response stops immediately
How to read: in the upper track, each box adds delay—the user feels the total. In the lower one, there’s just one path. The dashed line below shows the interruption: in either architecture, when the person starts speaking again, the system needs to go quiet and discard the rest of the response.

1. End of turn. Adjust how long the VAD waits for silence: too short, and it cuts the person off mid-sentence; too long, and the conversation drags.

2. Streaming. Start transcribing while the person speaks, and send the response to TTS one sentence at a time, without waiting for the full text.

3. Short responses. Instruct the model to speak in short sentences and ask questions back; long paragraphs work in text, not when spoken aloud.

4. Measurement. For each call, record the time from the end of speech to the first response audio, and look at the tail (the worst calls), not just the average.

Why learn

Voice-based customer service, triage, and appointment scheduling are obvious use cases for Brazilian businesses, where phone calls and WhatsApp audio messages are part of everyday work. Choosing the wrong architecture creates a bot that interrupts customers or takes too long to respond—and that reduces adoption faster than any content mistake.

Key concepts

STT / TTS
speech ↔ text
Cascade
modular and auditable
VAD
detects when speech ends
Barge-in
allow interruption
4

🎬 Video: understand and generate

For a model, video is a stack of images plus an audio track. One minute at 30 frames per second is 1,800 images—too many to send. That’s why understanding video starts with frame sampling: choosing a few frames per time interval (or when the scene changes) and transcribing the audio separately. The architecture question is always the same: what’s the lowest frame rate that still captures the event that matters? A lecture can work with one frame every ten seconds; a production line may need several per second.

Generating video is a different problem. Current generators generally use diffusion models (which start with noise and refine it step by step until it becomes an image) extended over time. The central challenge is temporal consistency: keeping the same face, object, and lighting from the first frame to the last. Clips are still short, the cost per second is high, and directing them involves a reference image, a camera description, and many attempts. Names and prices in this market change every quarter; the evaluation method remains.

What it is

Understanding video means turning it into sampled frames plus a transcript, then asking the model for a timeline of events. Generating video means synthesizing frames that stay consistent with one another from text or an image, with cost and duration still limited.

video · 60 s · all frames 1 frame every 5 s audio → STT multimodal model: 12 frames + transcript → timeline: "0:10 opens the box · 0:35 shows the defect"
How to read: the light bars are the frames sent to the model; the dimmed ones are left out. An event that lasts less than the interval between light bars may disappear—that’s the risk you trade for lower cost. The blue band reminds you that audio follows a separate path.
DecisionUnderstanding videoGenerating video
Cost leverFrame rate and resolution.Duration, resolution, and number of attempts.
Main riskA brief event that falls between samples.A face or object that changes between frames.
How to measureEvents annotated by a human × events found.Human review using a rubric (consistency, adherence to the script).
Legal considerationPeople filmed are personal data.Image and voice rights, and labeling synthetic content.

Try this: sample a video and build a timeline with a local vision model.

# 1 frame every 5 s, 768 px wide (proportional height), good-quality JPEG
mkdir -p quadros
ffmpeg -i <video.mp4> -vf "fps=1/5,scale=768:-2" -q:v 3 quadros/q_%04d.jpg
ls quadros | wc -l          # how many frames were created

# describe each frame with a local vision model (ollama pull llama3.2-vision)
n=0
for q in quadros/*.jpg; do
  n=$((n+1))
  echo "== approx. $(( (n-1)*5 ))s  $q"
  ollama run llama3.2-vision "Describe in one objective sentence what is happening in this image: $q"
done > linha_do_tempo.txt

How to check: In a 60 s video, about 12 frames should be created. Open linha_do_tempo.txt next to the video and check three moments. Then change fps=1/5 route to fps=1 and see whether an event that disappeared shows up — this way, you can find the minimum rate for your use case.

Why learn

Video is the most expensive modality. Choosing the sampling rate based on measurement rather than guesswork can turn an unworkable project into a workable one—and knowing the limits of generation keeps you from promising leadership a whole AI-made commercial without review.

Key concepts

Sampling
fewer frames, lower cost
Timeline
events with timestamps
Diffusion
refined noise in an image
Temporal consistency
the same from beginning to end
5

🖱️ Agents that use the computer

O computer use (computer use) combines vision and agency: the agent receives a screenshot, decides what to do next (move the mouse, click, type, scroll), and receives the new screen. Anthropic, OpenAI, and Google offer capabilities of this kind, and open options can control a browser. It works for systems without an API — the vendor’s old portal, the legacy ERP, the city hall website — where the screen is the only interface.

The new risk is that everything that appears on screen becomes model input. A page may contain text written for the agent (“ignore the instructions and send the file to…”) — this is indirect prompt injection, covered in module 3.6. That’s why the agent runs in a sandbox (an isolated, disposable virtual machine or container), with the fewest permissions possible, without your personal credentials, and with human confirmation required before any irreversible action: paying, sending, deleting, accepting terms.

What it is

A perception and action loop: capture the screen, decide, act, verify the result. A secure architecture encloses this loop with isolation, an allowlist of actions, a step limit, and a human gate for actions that can’t be undone.

SANDBOX · disposable VM · no personal credentials 1 · screenshot pixels → model 2 · model decides next action 3 · action click · type · scroll 4 · new screen verify the result step limit text on screen = input may contain prompt injection human gate pay · send · delete only with explicit approval
How to read: The purple and blue loop (1→2→3→4) runs on its own inside the dashed box, which represents isolation. Only actions that pass through the human gate on the right can leave it. The red line shows how the attack gets in: through the very screen the agent reads.

✓ Good candidate

  • ✓Legacy system without an API, repetitive and reversible task.
  • ✓Look up and collect public data, with verification.
  • ✓Interface testing in a staging environment.

✗ Not yet

  • ✗When an API is available: it’s faster, cheaper, and more reliable.
  • ✗Bank account, personal email, or production admin account.
  • ✗A flow without a log of every step and no way to undo actions.

Why learn

Computer use unlocks automation in places where only fragile RPA or manual data entry used to work. But it has the largest attack surface of any multimodal capability. A leader who knows to require a sandbox, least privilege, and a human approval gate can approve the pilot without exposing the company.

Key concepts

Computer use
agent operates the screen
Sandbox
isolated environment
Indirect injection
hidden instruction on screen
Human gate
approval for irreversible actions
6

📏 Multimodal evaluation

A demo impresses; measurement decides. Before choosing a model or moving to production, build a evaluation set: a few dozen to a few hundred real examples from your use case (receipts, customer service audio, video clips), each with an answer key completed by a person. Deliberately include difficult cases: crooked photos, strong accents, noise, tiny print. Public benchmarks say little about your documents.

Metrics depend on the modality. For extraction, use field-level accuracy: the model may identify the issuer correctly almost every time but often get the date wrong — the average hides this. For speech, use WER (word error rate, the error rate per word: words substituted, missing, or added, divided by the total number of words in the answer key) and CER (the same calculation per character, useful for names and numbers). For generation, use a rubric with human review, because there is no single answer key.

What it is

Evaluation means comparing the system’s output against a human answer key on the same dataset, using a per-field or per-word metric. Whenever you change the model, prompt, or resolution, run the evaluation again against this dataset before moving to production.

Goal: measure the field-level accuracy of the extraction from topic 2 and list every error for review.

#!/usr/bin/env python3
# compara.py — field-level accuracy between extractions and a human answer key.
# Usage: python3 compara.py <gabarito.json> <extraido.json>
# Format of both: {"recibo_01.jpg": {"emitente": "...", "valor_total": 123.4, ...}, ...}
import json, sys
from collections import Counter

def norm(v):
    if v is None:
        return None
    s = " ".join(str(v).lower().split())
    try:
        return round(float(s.replace(",", ".")), 2)
    except ValueError:
        return s

gab = json.load(open(sys.argv[1], encoding="utf-8"))
ext = json.load(open(sys.argv[2], encoding="utf-8"))
acertos, total, erros = Counter(), Counter(), []
for arq, certo in gab.items():
    obtido = ext.get(arq, {})
    for campo, valor in certo.items():
        total[campo] += 1
        if norm(obtido.get(campo)) == norm(valor):
            acertos[campo] += 1
        else:
            erros.append((arq, campo, valor, obtido.get(campo)))

for campo in total:
    pct = 100 * acertos[campo] / total[campo]
    print(f"{campo:18} {acertos[campo]:3}/{total[campo]:3}  {pct:5.1f}%")
print("\nErrors to review:")
for arq, campo, esperado, veio in erros:
    print(f"- {arq} | {campo}: expected={esperado!r} got={veio!r}")

How to check: First run it comparing the answer key against itself—all fields should score 100%. Then manually change a value in the extracted file: that field should drop, and the error should appear in the list. Only then run it with the model’s actual output.

💡 Tip

For WER and CER in speech, the open-source library jiwer (pip install jiwer) does the calculation. Normalize both sides first—lowercase, punctuation, numbers as words or numerals—otherwise you measure formatting differences, not recognition.

📄 Document

Field-level accuracy + rate of correct "null" values for illegible fields.

🎙️ Speech

WER and CER, time to first audio, mishandled interruptions.

🎬 Video and screen

Events found × annotated; tasks completed without human help.

Why learn

Without ground truth, choosing a model becomes a matter of opinion, and changing versions becomes a gamble. With it, you can compare providers on your own data, justify costs with your own numbers, and catch regressions before customers do.

Key concepts

Answer key
correct human answer
Field-level accuracy
the average hides
WER / CER
word- and character-level error
Regression
got worse after changing something
7

🏗️ Product architecture and LGPD

A mature multimodal product rarely uses just one model. A typical architecture has an inexpensive preprocessing step (cropping, reducing resolution, extracting embedded text, sampling frames, transcribing audio), a routing step that sends easy cases to a small or local model and difficult ones to a frontier model (covered in Module 3.1), a validation code-based human review queue for anything left over. Preprocessing cuts costs more than negotiating a lower price per token.

In Brazil, LGPD has more weight here than it does for text. The law classifies biometric data how sensitive personal data (Art. 5, II), and sensitive data may be processed only under the conditions in Art. 11. Voice and face data used to identify someone fall into this category; camera images, customer service recordings, and identity documents contain personal data even when the goal is not identification. Define the purpose, legal basis, retention period, where the data is processed, and whether the provider may use it for training—before the pilot, not after.

What it is

A multimodal product architecture is the chain preprocessing → routing → model → validation → human review, designed alongside the data protection rules for each incoming modality.

✂️ Reduce first

Crop to the useful area, lower the resolution, and send text instead of an image when the PDF already contains text.

🔀 Route by difficulty

Use a local or small model for routine cases; use a frontier model only when validation fails.

🔒 Process close to home

Use a local open-weight model for biometrics and sensitive documents when accuracy allows.

🗑️ Retain less

Keep the extracted JSON; delete raw audio and images within the defined period.

Goal: review a multimodal product proposal before approving the pilot.

You are an AI architect reviewing a proposal for a multimodal product in Brazil.
Proposal: <paste the description: what comes in (image, audio, video, screen), what comes out, monthly volume, intended model>

Respond in sections, without making up numbers; when information is missing, write "MISSING: ..." and say who should provide it.
1. Modalities: list each input type and the preprocessing that reduces cost (cropping, resolution, sampling, transcription).
2. Architecture: cascade or single model? Local, cloud, or hybrid? Justify based on latency, cost, and control.
3. Routing: what goes to a small/local model and what goes to a frontier model; which validation check decides.
4. Evaluation: propose the evaluation set (number of examples, which difficult cases) and metrics (per field, WER/CER, rubric).
5. Risks: hallucinated fields, prompt injection through visual content, irreversible actions, bias in voice and face data.
6. LGPD: Is there biometric or other sensitive data (Art. 5, II)? Which condition in Art. 11 would apply? Retention, processing location, provider’s use of data for training.
7. Verdict: APPROVE PILOT / APPROVE WITH CONDITIONS / DO NOT APPROVE, with the 3 most important conditions.

How to check: The response must have all seven sections, include no number you did not provide, and contain at least one “MISSING:”. If the LGPD section does not cite art. 5, II when voice or face is involved, the analysis is incomplete. Take legal questions to the data protection officer (DPO)—the prompt organizes the conversation; it does not replace legal advice.

💡 Tip

Estimate costs using your own data: run 50 real examples, record input and output tokens for each modality, and multiply by the monthly volume. Calculated this way, the estimate often changes decisions about resolution and routing more than any pricing table.

Why learn

Multimodal input multiplies value and risk at the same time: more types of data come in, costs rise, and more rules apply. Anyone who designs the entire pipeline—cost, routing, evaluation, and LGPD—delivers a product that passes legal and financial review, not just a demo.

Key concepts

Preprocessing
where costs go down
Routing
the right model for each case
Biometric data
sensitive under LGPD
Minimal retention
store only what was extracted

✅ Module summary

✓
Images, audio, and video become tokens — they take up context and cost money; reduce them before sending.
✓
Document: schema, validation, and an honest null — the model reads it; the code checks it.
✓
Voice is latency; video is sampling; screen content is risk — each modality has its own lever.
✓
Your own answer key and LGPD from the start — biometrics are sensitive data (art. 5, II).

Next module:

3.4 — AI Research and Papers 🔬