跳到内容

如何在达到递归限制之前返回状态

先决条件

本指南假定您熟悉以下内容

设置图递归限制 可以帮助您控制图的运行时间,但是如果达到递归限制,您的图会返回错误 - 这可能并非适用于所有用例。相反,您可能希望返回刚好在达到递归限制之前的状态值。本操作指南将向您展示如何做到这一点。

设置

首先,让我们安装所需的软件包

%%capture --no-stderr
%pip install -U langgraph

设置 LangSmith 以进行 LangGraph 开发

注册 LangSmith 以快速发现问题并提高 LangGraph 项目的性能。LangSmith 允许您使用跟踪数据来调试、测试和监控使用 LangGraph 构建的 LLM 应用程序——阅读此处了解更多关于如何开始的信息。

不返回状态

在本示例中,我们将定义一个总是会达到递归限制的虚拟图。首先,我们将实现不返回状态的情况,并展示它会达到递归限制。此图基于 ReAct 架构,但它只是永远循环,而不是实际做出决策和采取行动。

from typing_extensions import TypedDict
from langgraph.graph import StateGraph
from langgraph.graph import START, END


class State(TypedDict):
    value: str
    action_result: str


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()

API 参考: StateGraph | START | END

from IPython.display import Image, display

display(Image(app.get_graph().draw_mermaid_png()))

让我们验证我们的图是否总是会达到递归限制

from langgraph.errors import GraphRecursionError

try:
    app.invoke({"value": "hi!"})
except GraphRecursionError:
    print("Recursion Error")
Recursion Error

返回状态

为了避免达到递归限制,我们可以在状态中引入一个新的键,名为 remaining_steps。它将跟踪到达递归限制之前的步数。然后我们可以检查 remaining_steps 的值,以确定是否应该终止图的执行并返回状态给用户,而不会导致 RecursionError

为此,我们将使用特殊的 RemainingSteps 注解。在底层,它创建了一个特殊的 ManagedValue 通道 —— 一个状态通道,它将在我们的图运行期间存在,并且之后不再存在。

由于我们的 action 节点总是会给我们的图增加至少 2 个额外的步骤(因为 action 节点总是会在之后调用 decision 节点),我们将使用此通道来检查我们是否在限制的 2 步之内。

现在,当我们运行我们的图时,我们应该不会收到任何错误,而是获得达到递归限制之前的最后一个状态值。

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


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"


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()

API 参考: StateGraph

app.invoke({"value": "hi!"})
{'value': 'keep going!', 'action_result': 'what a great result!'}

完美!我们的代码运行没有错误,正如我们预期的那样!

评论