_from_response(err.response) from None openai.BadRequestError: Error code: 400 -...
🚨 错误信息
🤖 AI解决方案
1. 错误翻译
原文:Invalid param: {"detail":"Failed to load image: Unsupported URL format: *.jpg"}
译文:参数无效:{"detail":"无法加载图像:不支持的URL格式:*.jpg"}
2. 原因分析
根本原因:OpenAI API 无法加载指定URL格式的图片文件。
具体分析:
client.chat.completions.create() 时,这是向OpenAI API发送请求的函数BadRequestError,状态码400,表示客户端请求参数有问题1. URL协议不正确(如使用文件路径而非HTTP/HTTPS URL)
2. URL格式不符合API要求
3. 图片文件无法通过URL访问
3. 解决方案
方案A:如果使用本地文件路径
python
import base64
from openai import OpenAI初始化客户端
client = OpenAI(api_key="你的API密钥")读取本地图片并转换为base64
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')使用base64编码的图片
base64_image = encode_image("your_image.jpg")response = client.chat.completions.create(
model="gpt-4-vision-preview", # 或最新的视觉模型
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "这是什么图片?"},
{
"type": "image_url",
"image_url": {
"url": f"data:image/jpeg;base64,{base64_image}"
}
}
]
}
],
max_tokens=300,
)
方案B:如果使用网络URL
python
from openai import OpenAIclient = OpenAI(api_key="你的API密钥")
确保URL格式正确且可公开访问
image_url = "https://example.com/your_image.jpg" # 必须是完整的HTTP/HTTPS URLresponse = client.chat.completions.create(
model="gpt-4-vision-preview",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "这是什么图片?"},
{
"type": "image_url",
"image_url": {
"url": image_url
}
}
]
}
],
max_tokens=300,
)
4. ️ 预防措施
最佳实践:
https://example.com/image.jpg)或正确的base64 data URL格式推荐工具:
requests 库测试URL可访问性:python
import requests
response = requests.head(image_url)
if response.status_code == 200:
print("URL可访问")
---
提示:如果您使用的是本地文件,请采用方案A的base64编码方法;如果使用网络图片,请确保URL格式正确且可公开访问。