Notes
All notes

Multimodal AI (AI Engg #14)

A customer uploads a photo of a damaged product and a voice note. Your assistant should read the image, transcribe the audio, understand the complaint, and draft a reply — in one flow. That is multimodal AI: models and pipelines that handle text, images, audio, and video together.

This chapter maps the modalities, shows where each is useful, gives runnable examples for the main APIs (vision, image generation, speech-to-text, text-to-speech), and shows how to compose them into a single experience. The engineering concerns from earlier chapters — context budgeting, evals, cost — all apply, with new wrinkles per modality.

The modality map

Modality Direction Typical task Representative tools
Image in understanding, OCR, classification GPT vision, Claude, Gemini, LLaVA
Image out generation, editing DALL·E, NanoBanana, Stable Diffusion
Audio in transcription, understanding Whisper, Gemini audio
Audio out text-to-speech, voice OpenAI TTS, ElevenLabs
Video in summarization, scene search Gemini video, frame sampling
Any both unified assistants Gemini, GPT-4o-class

Two architectures exist and you should know which you are building:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.0cm, minimum height=0.7cm, font=\rmfamily\small, align=center},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (img) at (-3.4,1.1) {image};
  \node[b, fill=blue!10] (aud) at (-3.4,-1.1) {audio};
  \node[b, fill=orange!16] (mod) at (0,0) {model /\\pipeline};
  \node[b, fill=green!12] (txt) at (3.4,1.1) {text answer};
  \node[b, fill=green!12] (sp) at (3.4,-1.1) {speech / image};
  \draw[a] (img) -- (mod); \draw[a] (aud) -- (mod);
  \draw[a] (mod) -- (txt); \draw[a] (mod) -- (sp);
\end{tikzpicture}

Image understanding (vision input)

Give a capable model an image and ask. Useful for OCR, defect detection, chart reading, UI review, and “what is in this photo.”

from openai import OpenAI
import base64
client = OpenAI()

def describe(path, prompt="What is damaged in this product photo? Be specific."):
    b64 = base64.b64encode(open(path, "rb").read()).decode()
    r = client.chat.completions.create(
        model="gpt-4o", temperature=0, max_tokens=300,
        messages=[{"role": "user", "content": [
            {"type": "text", "text": prompt},
            {"type": "image_url",
             "image_url": {"url": f"data:image/jpeg;base64,{b64}"}},
        ]}])
    return r.choices[0].message.content

print(describe("damage.jpg"))

Notes: image tokens are expensive and depend on resolution; downscale before sending if detail is not needed. For OCR at scale, a dedicated OCR model or a vision model with a strict schema works better than free-form description. And remember Chapter 13: any text inside an uploaded image is untrusted input and can carry injection.

Image generation

Text-to-image via an API — useful for placeholder assets, marketing drafts, and product mockups.

r = client.images.generate(
    model="gpt-image-1", prompt="A clean isometric icon of a refund arrow, flat vector style",
    size="1024x1024", n=1)
url = r.data[0].url

By 2026 the practical choices are OpenAI’s image models, Google’s image APIs (NanoBanana-style editing), and open models (Stable Diffusion family) for self-hosting. For editing, prefer models that accept an input image and a mask rather than regenerating from scratch.

Speech: transcription and synthesis

Speech-to-text turns audio into text you can feed the LLM. Whisper is the workhorse; API and open weights both exist.

def transcribe(path):
    with open(path, "rb") as f:
        r = client.audio.transcriptions.create(model="whisper-1", file=f)
    return r.text

Text-to-speech closes the loop for voice interfaces.

with client.audio.speech.with_streaming_response.create(
        model="gpt-4o-mini-tts", voice="alloy", input="Your refund has been processed.") as resp:
    resp.stream_to_file("reply.mp3")

Two engineering notes: audio is long — one minute of speech is hundreds of tokens once transcribed, so budget for it; and streaming matters for voice UX — you want to start speaking while the model is still generating.

Video: sample, do not swallow

Video is the hardest modality because it is images plus time plus audio. Two strategies:

For most product needs, frame sampling plus a text LLM gives 80% of the value at a fraction of the cost. Keep timestamps in the metadata so answers can cite “at 02:14.”

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, minimum width=0.95cm, minimum height=0.75cm, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!12] (f1) at (0,0) {0:00};
  \node[b, fill=blue!12] (f2) at (1.2,0) {0:01};
  \node[b, fill=blue!12] (f3) at (2.4,0) {0:02};
  \node[b, fill=orange!16] (v) at (4.4,0) {vision\\describe};
  \node[b, fill=green!12] (s) at (6.4,0) {summary};
  \draw[a] (f3) -- (v); \draw[a] (v) -- (s);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (1.2,-0.6) {sample keyframes};
\end{tikzpicture}

Composing a multimodal product

Back to the damaged-product scenario, assembled as a pipeline:

def handle_claim(image_path, audio_path):
    image_summary = describe(image_path, "Describe damage precisely, list visible part numbers.")
    transcript     = transcribe(audio_path)
    context        = retrieve_policy("damage claims")        # Chapter 10
    reply = client.chat.completions.create(
        model="gpt-4o", temperature=0.2,
        messages=[{"role": "system", "content": "Draft a support reply. Be concise; cite policy."},
                  {"role": "user", "content":
                   f"Image: {image_summary}\nVoice note: {transcript}\nPolicy: {context}"}]
    ).choices[0].message.content
    return reply

Notice this is just RAG with extra inputs. The image and audio are converted to text summaries, scoped by policy retrieval, and the LLM generates the reply. You can swap in native multimodal calls, but the pipeline shape — normalize inputs to text, retrieve, generate — stays stable and easy to evaluate.

Costs, evals, and gotchas

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.15cm, minimum height=0.66cm, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (n) at (-3.2,0) {normalize\\to text};
  \node[b, fill=orange!16] (r) at (-0.9,0) {retrieve};
  \node[b, fill=green!12] (g) at (1.6,0) {generate};
  \node[b, fill=gray!12] (e) at (4.0,0) {evaluate};
  \draw[a] (n) -- (r); \draw[a] (r) -- (g); \draw[a] (g) -- (e);
\end{tikzpicture}

Pitfalls

QQuestionSelf-check

When do you choose a native multimodal model versus a composed pipeline? What stays the same across modalities?

ASolution

Choose native when cross-modal reasoning in one shot matters and cost is acceptable; choose a composed pipeline when you need to swap/evaluate parts, control cost, or self-host pieces. What stays the same is the shape: normalize inputs (to text or embeddings), retrieve relevant context, generate under a constrained format, then evaluate — with moderation and tenancy applied to every input.

Next: Dev Tools and Capstone (AI Engg #15) — coding assistants, vibing with care, and the capstone that ties it all together.