Sending Images to a Model

Ma Mahalakshmi V Updated 16 Sep 2026
5 min read ·Lesson 97 of 224

The Basic Shape of an Image-Carrying Request

Sending an image to the model always follows the same pattern you saw in Lesson 1: build a list of messages, give the user message a content list, and include one input_image part alongside any input_text parts. This lesson focuses specifically on the input_image part itself — its required fields, its optional fields, and the mistakes developers make most often when constructing it.

from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-5.6-terra",
    input=[
        {
            "role": "user",
            "content": [
                {"type": "input_text", "text": "Describe this image in one sentence."},
                {
                    "type": "input_image",
                    "image_url": "https://images.example.com/dog-park.jpg",
                },
            ],
        }
    ],
)

print(response.output_text)

The input_image content part has one required field for a URL-based image: image_url, a string pointing at a publicly reachable image. The model's provider fetches that URL server-side and passes the decoded image into the vision encoder. Nothing in your local Python process ever reads the image bytes in this flow — you are only passing a reference.

Why the URL Must Be Publicly Reachable

This point trips up a lot of developers building internal tools. If your image lives behind a corporate VPN, requires an authentication cookie, or is a file:// path on your own machine, a URL-based input_image will fail, because the request to fetch that URL is made from OpenAI's infrastructure, not from yours. Their servers have no access to your VPN, your session cookies, or your local filesystem.

This is precisely why the SDK also supports sending image bytes directly as base64 data instead of a URL — that path is covered in Lesson 3, and it is the one you need whenever the image is not already sitting at a public, unauthenticated URL.

Adding a detail Level

The input_image part accepts an optional detail field that controls how much visual resolution the model processes:

response = client.responses.create(
    model="gpt-5.6-terra",
    input=[
        {
            "role": "user",
            "content": [
                {"type": "input_text", "text": "What text appears in the top banner?"},
                {
                    "type": "input_image",
                    "image_url": "https://images.example.com/webpage-screenshot.png",
                    "detail": "high",
                },
            ],
        }
    ],
)

print(response.output_text)

Here, detail="high" asks the model to process the image at a finer resolution, which matters when the task depends on small details — reading fine print, distinguishing similar-looking icons, or counting small objects. The alternative, detail="low", processes a downscaled version of the image, which is cheaper and faster but may miss small text or fine detail. If you omit detail, the API applies a default behavior chosen automatically based on the image.

Why does this option exist at all, rather than the model always using maximum resolution? Because resolution is directly tied to token cost (as discussed in Lesson 1). A request that only needs to identify "is this a cat or a dog" gains nothing from high-resolution processing, so forcing every request through the expensive path would waste money and add latency across an entire application for no benefit. Exposing detail as a parameter lets you make that cost/accuracy trade-off deliberately, per request, based on what the task actually needs.

Note: The exact set of accepted detail values and their default behavior are specific to the model version you are using. Verify the current options against the official OpenAI documentation before relying on a particular default in production.

Combining Multiple Text Parts Around an Image

You are not limited to one text part before the image. You can structure a message with instructions before the image and a specific question after it, which can help the model understand the ordering of your intent:

response = client.responses.create(
    model="gpt-5.6-terra",
    input=[
        {
            "role": "system",
            "content": "You are a careful visual inspector. Only describe what is visibly present.",
        },
        {
            "role": "user",
            "content": [
                {"type": "input_text", "text": "Here is a photo of a shipping label."},
                {
                    "type": "input_image",
                    "image_url": "https://images.example.com/shipping-label.jpg",
                    "detail": "high",
                },
                {"type": "input_text", "text": "What is the destination postal code?"},
            ],
        }
    ],
)

print(response.output_text)

This example uses a system message (a plain string, since it contains no image) to set behavioral ground rules, then a user message with three content parts: a short text introduction, the image, and a specific question placed after it. Placing the question after the image, rather than before, often produces more focused answers, because the model processes the parts in order and the question becomes the most recent — and therefore most emphasized — piece of context immediately before it generates a response. This is not a strict rule for every case, but it is a useful default when your prompt asks a specific, narrow question about an image.

Common Mistakes

Passing the image URL as a plain string instead of inside a content part, which happens when developers try to reuse the simple input="some text" pattern and assume they can just append a URL to the string. The model receives the URL as literal text characters, not as image data, and either ignores it or hallucinates about what might be at that address. Always wrap image references in an explicit {"type": "input_image", "image_url": ...} part.

Forgetting that content must be a list once it contains an image, and instead leaving it as a bare string. A content field can be a plain string only when the message is pure text; the moment an image is involved, it must be a list of typed parts, even if there is only one text part alongside the image.

Using an inaccessible image URL — one that requires authentication, is behind a firewall, or has expired — and being confused when the API returns an error or the model reports it cannot see the image. Always confirm the URL loads successfully in an incognito browser window (i.e., with no cookies or session state) before assuming the model will be able to fetch it.

Best Practices

Set detail deliberately rather than always omitting it, especially in production code, so your cost and latency profile is predictable rather than left to a model-specific default that could change between versions.

Keep the descriptive text close to the image it refers to, especially in multi-image requests (covered in Lesson 7), so there is no ambiguity about which text applies to which image.

Validate image URLs before sending them by performing a lightweight HEAD request or catching request failures gracefully, rather than assuming every URL in your data pipeline is guaranteed to resolve.

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 Sending Images to a Model and get answers drawn from it.

Signed-in readers only.