'str' object has no attribute 'choices' File "C:\Users\soiry\python-pro\公司\compa...
错误信息
发生异常: 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'
AI 解决方案
错误翻译原文:AttributeError: 'str' object has no attribute 'choices'
译文:属性错误:'str' 对象没有 'choices' 属性
原因分析 解决方案
根本原因:chat_with_deepseek 函数返回的是一个字符串对象,而不是包含 choices 属性的响应对象
错误位置:在 company.py 第451行,代码试图访问字符串对象的 choices 属性
# 修复 chat_with_deepseek 函数
def chat_with_deepseek(user_input, model_set, system_prompt, conversation_history):
# 确保返回的是完整的响应对象,而不是提取后的字符串
# 如果使用 OpenAI SDK,应该是这样的结构:
response = client.chat.completions.create(
model=model_set,
messages=[
{"role": "system", "content": system_prompt},
*conversation_history,
{"role": "user", "content": user_input}
]
)
# 返回完整的响应对象,让调用方提取内容
return response
# 在调用方(如 wordshuchu 函数)提取内容
def wordshuchu(user_input, model_set1, system_prompt, conversation_history):
response = chat_with_deepseek(user_input, model_set1, system_prompt, conversation_history)
# 在这里提取消息内容
return response.choices[0].message.content
预防措施
try:
content = response.choices[0].message.content
except AttributeError:
print("响应对象结构异常,请检查API返回格式")
# 处理异常情况