'str' object has no attribute 'choices' ⚠ [llm] chat FAIL | 0.2s | AttributeErro...
错误信息
⚠ [llm] reminder extract FAIL | AttributeError: 'str' object has no attribute 'choices'
⚠ [llm] chat FAIL | 0.2s | AttributeError: 'str' object has no attribute 'choices' | input=你好
AI 解决方案
报错分析报告
1.错误翻译
原文:AttributeError: 'str' object has no attribute 'choices'
译文:属性错误:字符串对象没有'choices'属性
2. 原因分析
choices属性的响应对象(如LLM API返回的结构体)使用。 .choices属性时,目标变量实际为字符串(而非预期的响应对象),上下文是LLM的reminder extract和chat操作。3. 解决方案
# 修复示例:正确获取LLM响应(以OpenAI库为例)
from openai import OpenAI
client = OpenAI()
def safe_llm_chat(prompt: str):
try:
# 调用API获取正确响应对象(含choices属性)
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content # 提取有效内容
except Exception as e:
print(f"LLM调用失败:{e}")
return None
# 正确使用
input_text = "你好"
result = safe_llm_chat(input_text)
if result:
print(result)
4. 预防措施
isinstance(obj, ExpectedType)确认对象类型(如if not isinstance(resp, ResponseClass): raise TypeError)。