OpenAI 多模态视觉示例
以下示例展示如何使用OpenAI的GPT-4V模型分析图片内容。快速开始
curl -X POST "https://api.tokenops.ai/v1/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <API-KEY>" \
-d '{
"model": "gpt-5-2025-08-07",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "这张图片里有什么?"
},
{
"type": "image_url",
"image_url": {
"url": "https://example.com/image.jpg"
}
}
]
}
],
"max_tokens": 1000
}'
import requests
import json
import base64
API_KEY = "<API-KEY>"
BASE_URL = "https://api.tokenops.ai/v1"
def encode_image(image_path):
"""将本地图片编码为base64"""
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
def analyze_image(image_path, question="这张图片里有什么?"):
url = f"{BASE_URL}/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}"
}
# 编码图片
base64_image = encode_image(image_path)
data = {
"model": "gpt-5-2025-08-07",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": question
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
]
}
],
"max_tokens": 1000
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
result = response.json()
return result['choices'][0]['message']['content']
else:
return f"错误: {response.status_code} - {response.text}"
# 使用示例
if __name__ == "__main__":
# 分析图片内容
image_path = "example.jpg"
result = analyze_image(image_path, "详细描述这张图片的内容")
print(f"图片分析结果: {result}")
支持的功能
- 图片描述: 详细描述图片内容
- 物体识别: 识别图片中的物体
- 文字识别: 读取图片中的文字
- 情感分析: 分析图片传达的情感
- 场景理解: 理解图片的场景和上下文
应用场景
- 内容审核: 自动检测不当内容
- 辅助功能: 为视障用户描述图片
- 电商分析: 分析产品图片特征
- 教育应用: 图片内容教学辅助