Building an Image-Question-Answering Application

Ma Mahalakshmi V Updated 16 Sep 2026
6 min read ·Lesson 100 of 224

From Single Requests to a Reusable Application

The previous lessons sent one image and one question in isolated scripts. A real application needs more structure: a reusable function that accepts any image and any question, sensible error handling when something goes wrong, and — ideally — the ability to ask multiple follow-up questions about the same image without re-uploading it every time. This lesson builds that application step by step.

Step 1: A Reusable Core Function

import base64
import os
from openai import OpenAI

client = OpenAI()


def encode_image(path: str) -> str:
    with open(path, "rb") as f:
        return base64.b64encode(f.read()).decode("utf-8")


def guess_mime_type(path: str) -> str:
    extension = os.path.splitext(path)[1].lower()
    mime_map = {
        ".jpg": "image/jpeg",
        ".jpeg": "image/jpeg",
        ".png": "image/png",
        ".webp": "image/webp",
        ".gif": "image/gif",
    }
    if extension not in mime_map:
        raise ValueError(f"Unsupported image extension: {extension}")
    return mime_map[extension]


def ask_about_image(image_path: str, question: str) -> str:
    mime_type = guess_mime_type(image_path)
    encoded = encode_image(image_path)

    response = client.responses.create(
        model="gpt-5.6-terra",
        input=[
            {
                "role": "user",
                "content": [
                    {"type": "input_text", "text": question},
                    {
                        "type": "input_image",
                        "image_url": f"data:{mime_type};base64,{encoded}",
                        "detail": "high",
                    },
                ],
            }
        ],
    )
    return response.output_text

This splits responsibility across three small functions rather than one large one:

  • encode_image handles the pure byte-to-base64 conversion, as in earlier lessons.
  • guess_mime_type inspects the file extension and raises a clear ValueError for unsupported formats, rather than silently sending an incorrect or missing MIME type and getting a confusing failure later from the API.
  • ask_about_image composes the two helpers into the actual request, keeping the request-building logic focused and easy to read.

Separating these concerns makes the code easier to test and easier to extend — for example, if you later want to support fetching images from a URL as well as from disk, you only need to add a new encoding path, not rewrite the whole function.

Step 2: Validating Input Before Spending an API Call

A production application should not send a request to the API only to discover the file doesn't exist or the question is empty. Catch these problems early:

def ask_about_image_safe(image_path: str, question: str) -> str:
    if not question or not question.strip():
        raise ValueError("Question must not be empty.")
    if not os.path.isfile(image_path):
        raise FileNotFoundError(f"No such image file: {image_path}")

    return ask_about_image(image_path, question)

Why check question.strip() rather than just question? Because a string containing only whitespace is truthy in Python (bool(" ") is True), so a bare if not question check would let a meaningless whitespace-only question through undetected. Stripping first ensures an empty-looking question is actually treated as empty. Checking os.path.isfile before attempting to open the file lets you raise a clear, specific error (FileNotFoundError with the actual path) rather than letting a low-level open() failure surface with a less helpful message deep inside encode_image.

Step 3: A Simple Interactive Loop

With the core function in place, wrapping it in an interactive command-line loop is straightforward:

def run_interactive_session(image_path: str) -> None:
    print(f"Ask questions about {image_path}. Type 'quit' to exit.")
    while True:
        question = input("> ").strip()
        if question.lower() in ("quit", "exit"):
            break
        if not question:
            continue
        try:
            answer = ask_about_image_safe(image_path, question)
            print(answer)
        except Exception as error:
            print(f"Could not process the request: {error}")


if __name__ == "__main__":
    run_interactive_session("photos/kitchen_layout.jpg")

Each part of this loop earns its place:

  • The while True loop keeps asking for input until the user explicitly quits, which is the expected behavior for an interactive Q&A tool over a single fixed image.
  • Checking for "quit" or "exit" (case-insensitively, via .lower()) gives the user a predictable way to end the session.
  • The empty-question check (if not question: continue) silently skips blank input rather than sending a wasted, invalid request.
  • The try/except around the actual API call ensures that a single failed request — a network hiccup, an invalid file, a transient API error — doesn't crash the entire session. The user sees a clear message and can simply try again.

Note that catching a bare Exception here is a deliberate, narrow choice appropriate for a top-level interactive loop whose job is to stay alive and keep prompting the user; it would be too broad inside library code that other functions call, where callers need to know specifically what went wrong.

Step 4: Testing the Logic Without Calling the Real API

You should not call the live API inside a test — it costs money, requires network access, and makes tests non-deterministic. Instead, test the validation logic directly, and use a fake stand-in for anything that would otherwise reach the network:

def fake_ask_about_image(image_path: str, question: str) -> str:
    return f"FAKE ANSWER for '{question}' about {image_path}"


def test_empty_question_is_rejected():
    try:
        ask_about_image_safe("photos/kitchen_layout.jpg", "   ")
        assert False, "Expected a ValueError for an empty question"
    except ValueError:
        pass
    print("PASS: empty question is rejected")


def test_missing_file_is_rejected():
    try:
        ask_about_image_safe("photos/does_not_exist.jpg", "What is this?")
        assert False, "Expected a FileNotFoundError for a missing file"
    except FileNotFoundError:
        pass
    print("PASS: missing file is rejected")


def test_guess_mime_type_rejects_unknown_extension():
    try:
        guess_mime_type("document.txt")
        assert False, "Expected a ValueError for an unsupported extension"
    except ValueError:
        pass
    print("PASS: unsupported extension is rejected")


if __name__ == "__main__":
    test_empty_question_is_rejected()
    test_missing_file_is_rejected()
    test_guess_mime_type_rejects_unknown_extension()

These tests exercise ask_about_image_safe and guess_mime_type directly, both of which fail fast on bad input before ever reaching the network call inside ask_about_image. Because the validation happens first, these tests never actually trigger an API request — there's nothing to fake at the network layer for these particular cases. When you do need to test code that depends on the API's response (for example, code that parses response.output_text into a specific shape), the right approach is dependency injection: pass in a fake client or a fake function like fake_ask_about_image above instead of the real one, so your test exercises your logic without ever making a real network call.

Common Mistakes

Sending a request before validating that the file exists, which produces a confusing low-level file error deep inside the encoding step instead of a clear, actionable message at the point where the mistake actually originated.

Catching exceptions too broadly inside reusable library functions, which hides the specific cause of a failure from the calling code. Broad except Exception blocks belong at the outermost layer of an application (like the interactive loop above), not buried inside functions other code depends on.

Writing tests that call the real API, which makes the test suite slow, costly, and flaky due to network variability. Always isolate the parts of your logic that don't require the network and test those directly, using fakes for anything that would otherwise reach out to the API.

Best Practices

Separate encoding, validation, and request-building into distinct functions, so each piece can be tested, reused, and modified independently.

Fail fast with specific exception types (ValueError, FileNotFoundError) rather than generic ones, so calling code can distinguish between different failure causes and react appropriately.

Keep the interactive or user-facing loop resilient to individual request failures, using a narrow, well-placed try/except so one bad question or transient error doesn't end the entire session.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Building an Image-Question-Answering Application and get answers drawn from it.

Signed-in readers only.