Skip to main content
In this tutorial, you’ll build a Python script that takes an image URL and generates a descriptive caption using GPT-4’s vision capabilities. Instead of DALL·E, we’ll use the GPT-4 chat completion endpoint, which can process image URLs directly and describe what it “sees.”

Table of Contents

  1. Prerequisites
  2. Installation
  3. Initialize the OpenAI Client
  4. Define the Image URL
  5. Generate Captions Function
  6. Run the Script
  7. Sample Output
  8. References

Prerequisites

  • Python 3.7+
  • pip package manager
  • An OpenAI API key with GPT-4 access
  • Internet connectivity to fetch the image
Never hard-code your API key in a public repository. Use environment variables or a secure vault.

Installation

Install the official OpenAI Python client:

Initialize the OpenAI Client

Import and initialize the client with your API key:
You can find the latest OpenAI Python SDK and examples in the openai-python GitHub repo.

Define the Image URL

Specify the publicly accessible image URL you want to caption:

Generate Captions Function

Create a helper function that sends a chat completion request to GPT-4, including both a text prompt and the image URL. We’ll cap the response at 125 tokens to keep captions concise.

Run the Script

Use the function and print the returned caption:

Sample Output


References

Watch Video

Practice Lab