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

Bla*_*ung 12 gpt-4

如何使用 API 将图像上传到聊天 gpt?你能给出一个可以做到这一点的代码示例吗?

我尝试查看文档,但他们没有上传 jpg 作为上下文的好方法。

Muh*_*ani 11

截至目前,API 提到了两种为其提供图像的方法:

\n
    \n
  1. 给它图像的 URL
  2. \n
  3. 给它base64编码格式
  4. \n
\n

这两个示例均在其文档中以代码形式给出: https: //platform.openai.com/docs/guides/vision

\n

编码选项的代码(最好访问链接以保持更新)

\n
import base64\nimport requests\n\n# OpenAI API Key\napi_key = "YOUR_OPENAI_API_KEY"\n\n# Function to encode the image\ndef encode_image(image_path):\n    with open(image_path, "rb") as image_file:\n        return base64.b64encode(image_file.read()).decode(\'utf-8\')\n\n# Path to your image\nimage_path = "path_to_your_image.jpg"\n\n# Getting the base64 string\nbase64_image = encode_image(image_path)\n\nheaders = {\n    "Content-Type": "application/json",\n    "Authorization": f"Bearer {api_key}"\n}\n\npayload = {\n    "model": "gpt-4-vision-preview",\n    "messages": [\n      {\n        "role": "user",\n        "content": [\n          {\n            "type": "text",\n            "text": "What\xe2\x80\x99s in this image?"\n          },\n          {\n            "type": "image_url",\n            "image_url": {\n              "url": f"data:image/jpeg;base64,{base64_image}"\n            }\n          }\n        ]\n      }\n    ],\n    "max_tokens": 300\n}\n\nresponse = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload)\n\nprint(response.json())\n
Run Code Online (Sandbox Code Playgroud)\n

这回答了你的问题了吗?

\n