LangGraph(Python)中Chatbot节点多余条件边的成因及解决方法
LangGraph中Chatbot到summarize_conversation多余条件边的问题排查与解决
我是LangGraph(Python)的新手,正在学习LangGraph官方文档中的对话历史总结示例。我的代码如下:
class State(TypedDict): summary: str messages: list def summarize_conversation(state: State): # First, we summarize the conversation summary = state.get("summary", "") if summary: # If a summary already exists, we use a different system prompt # to summarize it than if one didn't summary_message = ( f"This is summary of the conversation to date: {summary}\n\n" "Extend the summary by taking into account the new messages above:" ) else: summary_message = "Create a summary of the conversation above:" messages = state["messages"] + [HumanMessage(content=summary_message)] response = model.invoke(messages) return {"summary": response.content, "messages": messages} graph_builder = StateGraph(State) graph_builder.add_node("tools", ToolNode(tool_set)) graph_builder.add_node("chatbot", lambda state: {"messages":assistant_runnable.invoke(state)}) graph_builder.add_node("summarize_conversation", summarize_conversation) graph_builder.add_edge("tools", "summarize_conversation") graph_builder.add_edge("summarize_conversation", "chatbot") graph_builder.add_conditional_edges( "chatbot", tools_condition ) graph_builder.set_entry_point("chatbot") graph = graph_builder.compile()
问题在于,Chatbot节点到summarize_conversation节点出现了一条多余的条件边:
注:为简洁起见,未附上完整代码。
问题成因
这条多余的条件边是由tools_condition函数的逻辑错误导致的:
- 调用
add_conditional_edges("chatbot", tools_condition)时,LangGraph会根据tools_condition函数的返回值创建对应跳转边。 - 如果
tools_condition在某些场景下返回了summarize_conversation节点名称,就会自动生成Chatbot到该节点的条件边。
解决方法
- 修正
tools_condition函数逻辑
确保该函数仅返回预定义节点名(比如"tools")或END(表示流程结束),不要返回summarize_conversation。示例如下:
def tools_condition(state: State): messages = state["messages"] last_message = messages[-1] # 仅当需要调用工具时返回"tools",否则结束流程 if isinstance(last_message, AIMessage) and hasattr(last_message, 'tool_calls') and last_message.tool_calls: return "tools" return END
- 明确总结节点的触发时机
已通过add_edge("tools", "summarize_conversation")设置工具调用完成后自动进入总结节点,无需让Chatbot节点的条件边触发总结流程,保持现有固定边逻辑即可。
内容的提问来源于stack exchange,提问作者web profiler
相关产品推荐
相关产品推荐

