'str' object has no attribute 'choices' ⚠ [llm] chat FAIL | 0.2s | AttributeErro...

2026年04月13日 16:34 processing

错误信息

⚠ [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 extractchat操作。
  • 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)。

  • 文档对齐:使用第三方库时,严格对照官方文档确认返回值结构(如LLM API的响应格式)。

  • 推荐工具:PyCharm类型提示、mypy静态类型检查、Postman模拟API响应。