Langgraph条件边实现报错:AIMessage不可下标访问修复方案
错误修复方案
错误原因
调用llm.invoke()后返回的是AIMessage实例,而非包含messages键的字典,因此使用response["messages"]会触发"对象不可下标访问"的TypeError。
修复步骤
- 直接通过
response.content获取模型返回的文本内容,而非尝试以字典方式访问messages字段。 - 可选:优化系统提示,强制模型仅返回指定关键词(
language_info或development_tasks),减少后续判断的干扰。
修改后的query_decision_func代码
def query_decision_func(state): user_query = [msg for msg in state["messages"] if isinstance(msg, HumanMessage)][-1].content system_message = """ You are an AI assistant that decides whether the query is about software development tasks or a specific question about a programming language. Based on the context of the user's query, determine whether it is about: - A specific programming language (e.g., "When was Java released?") - A software development task (e.g., writing code, designing architecture, etc.) Provide your decision on how the query should be processed. YOU MUST ONLY RETURN ONE OF THE FOLLOWING EXACT STRINGS: "language_info" or "development_tasks" """ # Get the model's response to the query and system message response = llm.invoke([SystemMessage(content=system_message)] + [HumanMessage(content=user_query)]) # Analyze the response from the model model_decision = response.content.strip().lower() # Based on the model's decision, route to the appropriate node if model_decision == "language_info": return "language_info" elif model_decision == "development_tasks": return "analyst" else: # Default case: route to development tasks if unsure return "analyst"
内容的提问来源于stack exchange,提问作者xxjmpxx__
相关产品推荐
相关产品推荐

