gpt-4-vision-preview是OpenAI推出的多模态模型,也是基于GPT-4的,可以额外提供一个image_url的参数,本文分享下gpt-4-vision-preview多模态模型接入教程。
一、前言
本文参考OpenAI官方API文档:
- API reference:https://platform.openai.com/docs/api-reference
- Docs:https://platform.openai.com/docs/overview
文中使用的API Key均为便携AI聚合API后台生成的令牌,以sk-开头的一串随机字符,获取方法:《便携AI聚合API新建令牌(API key)教程》。
便携AI聚合API有三个接入地址(即URL),一般推荐选择第一个:
- 中转API调用地址①(中国香港服务器,直连线路,带宽大):
https://api.bianxie.ai - 中转API调用地址②(国内上海服务器,带宽稍小):
https://api.bianxieai.com - 中转API调用地址③(国外服务器,也可以直连,备用):
https://api.a8.hk(三个网站都可以登录账号,数据同步)
模型支持各种语言接入,包括python、PHP、C#、C、Ruby、Java、Go、JavaScript等,本文主要分享官方的CURL调用方法,以及基于python的调用方法,如果你是用其他语言调用API的,则直接问ChatGPT或者其他语言模型怎么改写就行了,如下图:

二、gpt-4-vision-preview模型接入教程
gpt-4-vision-preview是OpenAI推出的GPT-4多模态模型,基于GPT-4,可以额外提供image_url参数,其余的调用方法跟gpt模型的调用方法一样,支持多种参数,必须的就是model和messages,其他参数如temperature、max_tokens可以让你自定义这次请求的设置,具体每个参数的意思大家可以参考官网。
python代码:
import requests
api_key = 'sk-Xy3'
url = 'https://api.bianxie.ai/v1/chat/completions'
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}'
}
data = {
'model': 'gpt-4-vision-preview',
'messages': [
{
"role": "user",
"content": [
{
"type": "text",
"text": "这张图片的图标是个什么动物?"
},
{
"type": "image_url",
"image_url": {
"url": "https://github.com/dianping/cat/raw/master/cat-home/src/main/webapp/images/logo/cat_logo03.png"
}
}
]
}
],
}
response = requests.post(url, headers=headers, json=data)
print(response.json())
除了传url外,也可以传base64链接,在base64码前面加一个data:image/jpeg;base64,就行了,如:
def image_to_base64(image_path):
with open(image_path, "rb") as image_file:
image_data = image_file.read()
base64_encoded_data = base64.b64encode(image_data)
base64_encoded_str = base64_encoded_data.decode('utf-8')
return base64_encoded_str
import requests
api_key = 'sk-Xy3WuCpTTvY19gB
url = 'https://api.bianxie.ai/v1/chat/completions'
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}'
}
image_base64 = image_to_base64('source.jpg')
data = {
'model': 'gpt-4-vision-preview',
'messages': [
{
"role": "user",
"content": [
{
"type": "text",
"text": "这张图片是什么内容?"
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{image_base64}"
}
}
]
}
],
}
response = requests.post(url, headers=headers, json=data)
print(response.json())
返回示例:
{
'id': 'chatcmpl-9WaNbvPCmjMQE2okqryYb4O3fCOni',
'object': 'chat.completion',
'created': 1717553368,
'model': 'gpt-4-vision-preview',
'choices': [{
'index': 0,
'message': {
'role': 'assistant',
'content': '这个图标是一只猫。图案的设计'
},
'finish_reason': 'stop'
}],
'usage': {
'prompt_tokens': 722,
'completion_tokens': 15,
'total_tokens': 737
},
'system_fingerprint': ''
}





