我正在使用Langgraph创建状态图,但我遇到了一个问题,即条件边中的END条件没有按预期终止执行。即使should_concontinue返回“END”,图也会继续循环通过generate节点,而不是停在END节点
以下是我的可复制代码:
import operator
import logging
import random
from typing import TypedDict, Annotated, Sequence, List
from langgraph.graph import StateGraph, END
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage
logging.basicConfig(level=logging.INFO)
class AgentState(TypedDict):
messages: Annotated[Sequence[BaseMessage], operator.add]
class Agent:
def __init__(self):
# graph init
graph = StateGraph(AgentState)
graph.add_node("init", self.init_node)
graph.add_node("generate", self.generate_node)
graph.add_node("eval", self.eval_node)
graph.add_node("search", self.search_node)
graph.set_entry_point("init")
graph.add_conditional_edges(
"eval",
self.should_continue,
{
"END": END,
"CONTINUE": "generate",
},
)
graph.add_edge("init", "search")
graph.add_edge("search", "eval")
graph.add_edge("eval", "generate")
graph.add_edge("generate", "search")
self.graph = graph.compile()
def init_node(self, state: AgentState):
content = "some keywords"
logging.info(content)
return {"messages": [AIMessage(content=content)]}
def search_node(self, state: AgentState):
content = "some results...."
logging.info(content)
return {"messages": [AIMessage(content=content)]}
def eval_node(self, state: AgentState):
content = "some evaluation...."
logging.info(content)
return {"messages": [AIMessage(content=content)]}
def generate_node(self, state: AgentState):
content = "some new keywords...."
logging.info(content)
return {"messages": [AIMessage(content=content)]}
def should_continue(self, state: AgentState):
choice = random.choice(["END", "CONTINUE"])
logging.info(choice)
return choice
然后我这样称呼它:
from reproducible_agent import Agent
from langchain_core.messages import HumanMessage
bot = Agent()
messages = [HumanMessage(content="hello world")]
result = bot.graph.invoke({"messages": messages})
日志:
信息:根:一些关键字。
信息:根:一些结果。。。。
信息:根:一些评估。。。。
信息:根:结束。
信息:根:一些新关键字。。。。
信息:根:一些结果。。。。
信息:根:一些评估。。。。
信息:根:结束。
信息:根:一些新关键字。。。。
信息:根:一些结果。。。。
信息:根:一些评估。。。。
信息:根:继续。
信息:根:一些新关键字。。。。
信息:根:一些结果。。。。
信息:根:一些评估。。。。
信息:根:继续。
信息:根:一些新关键字。。。。
信息:根:一些结果。。。。
信息:根:一些评估。。。。
信息:根:继续。
信息:根:一些新关键字。。。。
信息:根:一些结果。。。。
信息:根:一些评估。。。。
信息:根:继续。
信息:根:一些新关键字。。。。
...
信息:根:一些结果。。。。
信息:根:一些评估。。。。
信息:根:继续。
信息:根:一些新关键字。。。。
最终,它会出现以下错误:
GraphRecursionError:在不满足停止条件的情况下达到了25的递归限制。您可以通过设置来增加限制
recursion_limit
配置键。
我也试过了,但没有成功
...
graph.add_conditional_edges(
"eval",
self.should_continue)
...
def should_continue(self, state: AgentState):
choice = random.choice(["END", "CONTINUE"])
logging.info(choice)
if choice == "END":
return END
else:
return "generate"