如何使用API将图像上传到Chat GPT?你能给出一个可以实现这个功能的代码示例吗?
我已经尝试查看文档,但他们没有一个很好的方法来上传jpg作为上下文。
我已经尝试查看文档,但他们没有一个很好的方法来上传jpg作为上下文。
目前的API提到了两种输入图像的方法:
这两个示例在文档中以代码的形式给出,可以在这里查看: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())