使用AutoGen Conversable Agent时触发AttributeError错误
AutoGen Conversable Agent时触发AttributeError错误
看起来你在使用AutoGen的ConversableAgent时踩了一个参数使用的坑,这个AttributeError: 'list' object has no attribute '_raise_exception_on_async_reply_functions'错误,根源是你调用initiate_chat方法的方式不对。
问题原因
AutoGen的ConversableAgent.initiate_chat方法的第一个参数要求是另一个Agent实例(比如UserProxyAgent或者其他ConversableAgent),作为聊天的接收方。但你直接把消息列表[{"role": "user", "content": user_message}]传进去了,方法内部会把这个列表当成接收方Agent对象,去访问它的内部属性,而列表显然没有这个属性,所以触发了错误。
解决方案
你有两种可行的修复方式,根据你的需求选择:
方式一:使用UserProxyAgent发起对话(更符合AutoGen的对话模式)
这种方式需要创建一个用户代理Agent来作为对话的发起者,和你的评分Agent交互:
- 首先导入UserProxyAgent:
from autogen import UserProxyAgent
- 修改
analyze_reviews_with_agent函数中的对话逻辑:
def analyze_reviews_with_agent(reviews: List[str]) -> Dict[str, List[int]]: """Uses an agent to analyze reviews and extract scores.""" agent = create_scoring_agent() # 创建用户代理,不需要LLM,只负责转发消息 user_proxy = UserProxyAgent( name="user_proxy", llm_config=False, human_input_mode="NEVER" # 自动处理,不需要人工干预 ) food_scores, service_scores = [], [] for review in reviews: user_message = f"Analyze this review: '{review}'. Extract food_score and service_score." print(user_message) # 用用户代理发起和评分Agent的对话 chat_result = user_proxy.initiate_chat( recipient=agent, message=user_message ) print(chat_result) # 解析聊天结果:取最后一条回复的内容 try: # 注意:尽量用json.loads代替eval,更安全 import json result = json.loads(chat_result.chat_history[-1]['content']) food_scores.append(result["food_score"]) service_scores.append(result["service_score"]) except Exception as e: print(f"Error processing review: {review}. Error: {e}") return {"food_scores": food_scores, "customer_service_scores": service_scores}
方式二:直接调用generate_reply(单轮对话场景更简洁)
如果只是需要单轮的评分请求,不需要多轮对话,可以直接用generate_reply方法,它接受消息列表作为参数:
修改对话调用的代码部分:
# 替换原来的initiate_chat调用 response_content = agent.generate_reply(messages=[{"role": "user", "content": user_message}]) print(response_content) # 解析回复 try: import json result = json.loads(response_content) food_scores.append(result["food_score"]) service_scores.append(result["service_score"]) except Exception as e: print(f"Error processing review: {review}. Error: {e}")
额外提醒
- 尽量避免用
eval解析JSON,因为它存在安全风险(如果返回的内容包含恶意代码会被执行),改用json.loads更安全可靠。 - 确保你的AutoGen版本是最新的,部分旧版本可能存在参数兼容问题。
备注:内容来源于stack exchange,提问作者shubham gaur
相关产品推荐
相关产品推荐

