使用API将图像上传到GPT聊天?

9
如何使用API将图像上传到Chat GPT?你能给出一个可以实现这个功能的代码示例吗?
我已经尝试查看文档,但他们没有一个很好的方法来上传jpg作为上下文。

他们还没有将这项功能添加到API中,实际上,他们还在通过常规聊天逐步推出图片上传功能,因此它也并非在所有地方都可用。 - undefined
明白了,你知道有什么好的解决办法吗?比如将一个jpg文件转换成文本?我见过一些工具可以使用你的API密钥来有效地理解一张图片。 - undefined
1个回答

3

目前的API提到了两种输入图像的方法:

  1. 提供图像的URL
  2. 提供base64编码格式

这两个示例在文档中以代码的形式给出,可以在这里查看:https://platform.openai.com/docs/guides/vision

关于编码选项的代码可以在链接中找到(最好访问链接以获取最新信息)

import base64
import requests

# OpenAI API Key
api_key = "YOUR_OPENAI_API_KEY"

# Function to encode the image
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')

# Path to your image
image_path = "path_to_your_image.jpg"

# Getting the base64 string
base64_image = encode_image(image_path)

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key}"
}

payload = {
    "model": "gpt-4-vision-preview",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "What’s in this image?"
          },
          {
            "type": "image_url",
            "image_url": {
              "url": f"data:image/jpeg;base64,{base64_image}"
            }
          }
        ]
      }
    ],
    "max_tokens": 300
}

response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)

print(response.json())

这个回答解决了你的问题吗?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接