设置图形递归限制可以帮助你控制图形运行的时间,但如果达到递归限制,图形会返回一个错误——这在某些用例中可能并不理想。相反,你可能希望返回递归限制被触及之前的状态值。当递归限制被触及时,如何返回之前的状态。设置图形递归限制可以帮助你控制图形运行的时间,但如果达到递归限制,图形会返回一个错误——这在某些用例中可能并不理想。相反,你可能希望返回递归限制被触及之前的状态值。
1. 定义状态和工作流
首先,我们需要定义状态类型和工作流的基本结构。
1.1 定义状态类型
我们使用 TypedDict
来定义状态类型,包含 value
和 action_result
两个字段。
from typing_extensions import TypedDict
from langgraph.graph import StateGraph
from langgraph.graph import START, END
class State(TypedDict):
value: str
action_result: str
1.2 创建工作流
创建一个 StateGraph
实例,并添加节点和边。
def router(state: State):
if state["value"] == "end":
return END
else:
return "action"
def decision_node(state):
return {"value": "keep going!"}
def action_node(state: State):
# Do your action here ...
return {"action_result": "what a great result!"}
workflow = StateGraph(State)
workflow.add_node("decision", decision_node)
workflow.add_node("action", action_node)
workflow.add_edge(START, "decision")
workflow.add_conditional_edges("decision", router, ["action", END])
workflow.add_edge("action", "decision")
app = workflow.compile()
1.3 可视化工作流
使用 IPython.display
模块展示工作流的图形表示。
from IPython.display import Image, display
display(Image(app.get_graph().draw_mermaid_png()))
2. 处理递归错误
在执行工作流时,可能会遇到递归错误。我们需要捕获并处理这种错误。
2.1 捕获递归错误
尝试执行工作流,并捕获 GraphRecursionError
。
from langgraph.errors import GraphRecursionError
try:
app.invoke({"value": "hi!"})
except GraphRecursionError:
print("Recursion Error")
输出:
Recursion Error
3. 限制递归次数
为了避免递归错误,我们可以在状态中添加一个 remaining_steps
字段来限制递归次数。
3.1 修改状态类型
添加 remaining_steps
字段到状态类型。
from typing_extensions import TypedDict
from langgraph.graph import StateGraph
from typing import Annotated
from langgraph.managed.is_last_step import RemainingSteps
class State(TypedDict):
value: str
action_result: str
remaining_steps: RemainingSteps
3.2 修改路由函数
在路由函数中添加对 remaining_steps
的检查。
def router(state: State):
# Force the agent to end
if state["remaining_steps"] <= 2:
return END
if state["value"] == "end":
return END
else:
return "action"
3.3 重新创建工作流
重新创建并编译工作流。
workflow = StateGraph(State)
workflow.add_node("decision", decision_node)
workflow.add_node("action", action_node)
workflow.add_edge(START, "decision")
workflow.add_conditional_edges("decision", router, ["action", END])
workflow.add_edge("action", "decision")
app = workflow.compile()
3.4 执行工作流
再次执行工作流,观察结果。
app.invoke({"value": "hi!"})
输出:
{'value': 'keep going!', 'action_result': 'what a great result!'}
注意事项:
在decision节点中打印循环次数,可以看出state[“remaining_steps”] 变化
结果:
通过以上步骤,我们成功构建了一个带有递归限制的状态图工作流,并在递归错误之前返回state值。希望这个教程对你有所帮助!
如果有任何问题,欢迎在评论区提问。