Error code: 404 - {'error': {'message': 'Invalid URL (POST /v1/chat/completions/...
🚨 错误信息
openai.NotFoundError: Error code: 404 - {'error': {'message': 'Invalid URL (POST /v1/chat/completions/chat/completio发生异常: AttributeError
'str' object has no attribute 'choices'
File "C:\Users\soiry\python-pro\公司\company.py", line 451, in chat_with_deepseek
return response.choices[0].message.content
^^^^^^^^^^^^^^^^
File "C:\Users\soiry\python-pro\公司\company.py", line 480, in wordshuchu
response = chat_with_deepseek(user_input,model_set1, system_prompt, conversation_history)
File "C:\Users\soiry\python-pro\公司\company.py", line 524, in <module>
jichu = wordshuchu(muban1+muban2+user_input,model_set)
AttributeError: 'str' object has no attribute 'choices'ns)', 'type': 'invalid_request_error', 'code': ''}}
🤖 AI解决方案
错误分析报告
错误翻译
原文:Invalid URL (POST /v1/chat/completions/chat/completions)
译文:无效的URL(POST /v1/chat/completions/chat/completions)
原因分析
根本原因:URL路径重复导致404错误,API请求失败返回字符串而非有效的响应对象。详细分析:
- 第451行试图访问
response.choices,但此时response是字符串而非API响应对象 - OpenAI API返回404错误,说明URL构造有误:
/v1/chat/completions/chat/completions存在路径重复 - 错误的URL导致API调用失败,返回错误信息字符串而非正常响应
解决方案
修复URL路径问题
# 修改前的错误URL构造
# 修改后的正确URL构造
# 在OpenAI客户端初始化或API调用时确保URL正确
# 示例修复代码:
def chat_with_deepseek(user_input, model_set, system_prompt, conversation_history):
try:
# 确保使用正确的API端点
response = openai.ChatCompletion.create(
model=model_set,
messages=[
{"role": "system", "content": system_prompt},
*conversation_history,
{"role": "user", "content": user_input}
]
)
# 添加响应类型检查
if hasattr(response, 'choices') and response.choices:
return response.choices[0].message.content
else:
return "API响应格式异常"
except Exception as e:
print(f"API调用异常: {e}")
return f"请求失败: {str(e)}"
添加错误处理机制
def wordshuchu(user_input, model_set):
try:
response = chat_with_deepseek(user_input, model_set, system_prompt, conversation_history)
return response
except AttributeError as e:
print(f"属性错误: {e}")
# 返回默认响应或重新尝试
return "服务暂时不可用,请稍后重试"
️ 预防措施
1. URL验证最佳实践
2. 防御性编程建议
# 添加类型检查和错误处理
def safe_api_call(response):
if response and hasattr(response, 'choices'):
return response.choices[0].message.content
elif isinstance(response, str):
# 处理错误信息字符串
return f"API错误: {response}"
else:
return "未知响应格式"