🙄

gpt-4o APIで画像をプロンプトする方法【python】

2024/05/24に公開

やること

gpt-4o APIで画像をプロンプトする方法を紹介します。
今回は、pythonで実装します。

参考記事

https://cookbook.openai.com/examples/gpt4o/introduction_to_gpt4o#current-api-capabilities

前提

  • Azure Open AI Service上にGPT-4oをデプロイ済みであること

https://zenn.dev/headwaters/articles/9d4410846fd6b9

  • Keyとendpointを取得済みであること

実行環境

  • python:3.10.2
  • openai:0.28.0

手順

  1. 画像を用意する
    ※今回は、以下の画像を使う

  2. 以下のコードを書いたPythonファイルを作成

import openai
import base64

# Azure OpenAIの設定
openai.api_type = "azure"
openai.api_base = "<endpoint>"  
openai.api_version = "2023-05-15"  
openai.api_key = "<key>"

# Open the image file and encode it as a base64 string
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")
    
base64_image = encode_image(<ファイルパス>) #ファイルパスを入力

response = openai.ChatCompletion.create(
    engine="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": [
            {"type": "text", "text": "Describe this image:"},
            {"type": "image_url", "image_url": {
                "url": f"data:image/png;base64,{base64_image}"}
            }
        ]}
    ],
    temperature=0.0,
)

print(response.choices[0].message.content)
  1. 実行する
  2. 以下のように出力される
The image is a logo for "Headwaters." The logo consists of the word "Headwaters" with the letter "H" in orange and the rest of the letters in gray. To the left of the text, there is a circular design with a blue swirl and a yellow dot in the center. The blue swirl appears to be dynamic, giving a sense of motion or flow.

OpenAI Python 1.x の場合

import openai
import base64
import os
import requests
import json
from openai import AzureOpenAI

client = AzureOpenAI(
    api_version="2023-05-15", # 固定
    api_key="<key>",
    azure_endpoint="<endpoint>"
)

#Open the image file and encode it as a base64 string
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")
    
base64_image = encode_image("<ファイルパス>") #ファイルパスを入力

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": [
            {"type": "text", "text": "Describe this image:"},
            {"type": "image_url", "image_url": {
                "url": f"data:image/png;base64,{base64_image}"}
            }
        ]}
    ],
    temperature=0.0,
)

print(response.choices[0].message.content)

まとめ

gpt-4oで画像をプロンプトで入力する方法をサクッとまとめました。
動画は、まだ未対応みたいです。早く使えるようになってほしいなー。

ヘッドウォータース

Discussion