during execution: 'str' object has no attribute 'choices'. Please check the capa...
错误信息
Reason: Planner encountered an error during execution: 'str' object has no attribute 'choices'. Please check the capabilities of your model qwen-plus-search (via OpenAI) and try again later.
AI 解决方案
#代码糕手报错分析报告
##
原文:'str' object has no attribute 'choices'
译文:'str'对象没有'choices'属性
##
这是一个典型的Python 属性访问错误。问题的根本原因在于:
- 类型不匹配:代码期望得到一个包含
choices属性的对象(通常是OpenAI API响应对象),但实际上收到的是一个字符串(str类型) - API调用处理不当:当调用模型
qwen-plus-search(通过OpenAI接口)时,返回的数据被错误地当作结构化对象处理,而实际上可能是错误信息字符串 - 缺乏错误处理:代码没有对API返回的异常响应进行适当的类型检查和错误处理
具体位置:Planner执行过程中的模型调用返回数据处理环节 解决方案
# 修复后的代码示例
def handle_api_response(response):
"""
正确处理API响应,处理可能的错误情况
"""
# 1. 检查响应是否为字符串(可能是错误信息)
if isinstance(response, str):
try:
# 尝试解析JSON格式的错误信息
error_data = json.loads(response)
if 'error' in error_data:
raise Exception(f"API Error: {error_data['error']}")
except json.JSONDecodeError:
# 如果是普通字符串错误信息
raise Exception(f"Unexpected API response: {response}")
# 2. 检查choices属性是否存在
if not hasattr(response, 'choices'):
# 根据实际情况处理,可能需要重新构建响应对象
# 或者检查响应的实际结构
if isinstance(response, dict) and 'choices' in response:
# 如果响应是字典格式
return process_dict_response(response)
else:
raise AttributeError(f"Response object missing 'choices' attribute. Actual type: {type(response)}")
# 3. 正常处理
return process_choices(response.choices)
# 或者在调用API时添加更健壮的错误处理
try:
response = openai_client.chat.completions.create(
model="qwen-plus-search",
messages=messages,
# 确保使用正确的参数
temperature=0.7
)
# 强制类型检查
if not hasattr(response, 'choices'):
logger.error(f"Unexpected response structure: {response}")
# 回退策略或使用默认值
return get_default_response()
except Exception as e:
logger.error(f"API call failed: {e}")
# 实现适当的错误恢复逻辑
return handle_api_failure(e)
️ 预防措施
1.响应验证
def validate_api_response(response, expected_attributes=['choices']):
for attr in expected_attributes:
if not hasattr(response, attr):
raise ValueError(f"Missing expected attribute: {attr}")
return True
2️ 防御性编程
mypy进行静态类型检查,确保类型安全 # 添加类型注解
from typing import Optional
def process_response(response: Optional[object]) -> dict:
if response is None:
return {}
# 使用getattr安全访问属性
choices = getattr(response, 'choices', None)
if choices is None:
# 优雅降级
return {"error": "Invalid response structure"}
return process_choices(choices)
监控和日志
qwen-plus-search模型的响应模式变化