跳到内容

类型

All = Literal['*'] module-attribute

特殊值,指示图应在所有节点上中断。

StreamMode = Literal['values', 'updates', 'debug', 'messages', 'custom'] module-attribute

流方法应如何发出输出。

  • "values": 在每个步骤后发出状态中的所有值。当与函数式 API 一起使用时,值在工作流程结束时发出一次。
  • "updates": 仅在每个步骤后发出节点或任务名称以及节点或任务返回的更新。如果在同一步骤中进行多次更新(例如,运行多个节点),则这些更新将分别发出。
  • "custom": 使用来自节点或任务内部的 StreamWriter 发出自定义数据。
  • "messages": 将 LLM 消息与元数据一起逐个令牌地发出,用于节点或任务内部的任何 LLM 调用。
  • "debug": 发出调试事件,其中包含每个步骤尽可能多的信息。

StreamWriter = Callable[[Any], None] module-attribute

接受单个参数并将其写入输出流的可调用对象。如果作为关键字参数请求,则始终注入到节点中,但在不使用 stream_mode="custom" 时,它是无操作的。

RetryPolicy

基类: NamedTuple

用于重试节点的配置。

initial_interval: float = 0.5 class-attribute instance-attribute

首次重试前必须经过的时间量。以秒为单位。

backoff_factor: float = 2.0 class-attribute instance-attribute

每次重试后间隔增加的倍数。

max_interval: float = 128.0 class-attribute instance-attribute

重试之间可能经过的最大时间量。以秒为单位。

max_attempts: int = 3 class-attribute instance-attribute

放弃之前尝试的最大次数,包括第一次。

jitter: bool = True class-attribute instance-attribute

是否在重试之间的间隔中添加随机抖动。

retry_on: Union[Type[Exception], Sequence[Type[Exception]], Callable[[Exception], bool]] = default_retry_on class-attribute instance-attribute

应触发重试的异常类列表,或对于应触发重试的异常返回 True 的可调用对象。

CachePolicy

基类: NamedTuple

用于缓存节点的配置。

Interrupt dataclass

PregelTask

基类: NamedTuple

PregelExecutableTask

基类: NamedTuple

StateSnapshot

基类: NamedTuple

步骤开始时图的状态快照。

values: Union[dict[str, Any], Any] instance-attribute

通道的当前值

next: tuple[str, ...] instance-attribute

在此步骤中为每个任务执行的节点的名称。

config: RunnableConfig instance-attribute

用于获取此快照的配置

metadata: Optional[CheckpointMetadata] instance-attribute

与此快照关联的元数据

created_at: Optional[str] instance-attribute

快照创建的时间戳

parent_config: Optional[RunnableConfig] instance-attribute

用于获取父快照(如果有)的配置

tasks: tuple[PregelTask, ...] instance-attribute

在此步骤中要执行的任务。如果已尝试,则可能包含错误。

Send

要发送到图中特定节点的消息或数据包。

Send 类在 StateGraph 的条件边中使用,以在下一步动态调用具有自定义状态的节点。

重要的是,发送的状态可以与核心图的状态不同,从而实现灵活和动态的工作流程管理。

一个这样的示例是“map-reduce”工作流程,其中您的图并行多次调用同一节点,并使用不同的状态,然后在将结果聚合回主图的状态。

属性

  • node (str) –

    要将消息发送到的目标节点的名称。

  • arg (Any) –

    要发送到目标节点的状态或消息。

示例

>>> from typing import Annotated
>>> import operator
>>> class OverallState(TypedDict):
...     subjects: list[str]
...     jokes: Annotated[list[str], operator.add]
...
>>> from langgraph.types import Send
>>> from langgraph.graph import END, START
>>> def continue_to_jokes(state: OverallState):
...     return [Send("generate_joke", {"subject": s}) for s in state['subjects']]
...
>>> from langgraph.graph import StateGraph
>>> builder = StateGraph(OverallState)
>>> builder.add_node("generate_joke", lambda state: {"jokes": [f"Joke about {state['subject']}"]})
>>> builder.add_conditional_edges(START, continue_to_jokes)
>>> builder.add_edge("generate_joke", END)
>>> graph = builder.compile()
>>>
>>> # Invoking with two subjects results in a generated joke for each
>>> graph.invoke({"subjects": ["cats", "dogs"]})
{'subjects': ['cats', 'dogs'], 'jokes': ['Joke about cats', 'Joke about dogs']}

__init__(node: str, arg: Any) -> None

初始化 Send 类的新实例。

参数

  • node (str) –

    要将消息发送到的目标节点的名称。

  • arg (Any) –

    要发送到目标节点的状态或消息。

Command dataclass

基类: Generic[N], ToolOutputMixin

用于更新图的状态并将消息发送到节点的一个或多个命令。

参数

  • graph (Optional[str], default: None ) –

    要将命令发送到的图。支持的值为

    • None: 当前图 (默认)
    • Command.PARENT: 最近的父图
  • update (Optional[Any], default: None ) –

    要应用于图状态的更新。

  • resume (Optional[Union[Any, dict[str, Any]]], default: None ) –

    用于恢复执行的值。与 interrupt() 一起使用。

  • goto (Union[Send, Sequence[Union[Send, str]], str], default: () ) –

    可以是以下之一

    • 要导航到的下一个节点的名称(属于指定 graph 的任何节点)
    • 要导航到的下一个节点名称序列
    • Send 对象(使用提供的输入执行节点)
    • Send 对象序列

interrupt(value: Any) -> Any

从节点内部使用可恢复的异常中断图。

interrupt 函数通过暂停图执行并将值呈现给客户端来启用人机环路工作流程。此值可以传达上下文或请求恢复执行所需的输入。

在给定的节点中,首次调用此函数会引发 GraphInterrupt 异常,从而停止执行。提供的 value 包含在异常中并发送到执行图的客户端。

恢复图的客户端必须使用 Command 原语来指定中断的值并继续执行。图从节点开始处恢复,重新执行所有逻辑。

如果节点包含多个 interrupt 调用,LangGraph 会根据中断在节点中的顺序将恢复值与中断匹配。此恢复值列表的作用域限定为执行节点的特定任务,并且不跨任务共享。

要使用 interrupt,您必须启用检查点程序,因为该功能依赖于持久化图状态。

示例
import uuid
from typing import Optional
from typing_extensions import TypedDict

from langgraph.checkpoint.memory import MemorySaver
from langgraph.constants import START
from langgraph.graph import StateGraph
from langgraph.types import interrupt


class State(TypedDict):
    """The graph state."""

    foo: str
    human_value: Optional[str]
    """Human value will be updated using an interrupt."""


def node(state: State):
    answer = interrupt(
        # This value will be sent to the client
        # as part of the interrupt information.
        "what is your age?"
    )
    print(f"> Received an input from the interrupt: {answer}")
    return {"human_value": answer}


builder = StateGraph(State)
builder.add_node("node", node)
builder.add_edge(START, "node")

# A checkpointer must be enabled for interrupts to work!
checkpointer = MemorySaver()
graph = builder.compile(checkpointer=checkpointer)

config = {
    "configurable": {
        "thread_id": uuid.uuid4(),
    }
}

for chunk in graph.stream({"foo": "abc"}, config):
    print(chunk)
{'__interrupt__': (Interrupt(value='what is your age?', resumable=True, ns=['node:62e598fa-8653-9d6d-2046-a70203020e37'], when='during'),)}
command = Command(resume="some input from a human!!!")

for chunk in graph.stream(Command(resume="some input from a human!!!"), config):
    print(chunk)
Received an input from the interrupt: some input from a human!!!
{'node': {'human_value': 'some input from a human!!!'}}

参数

  • value (Any) –

    当图中断时要呈现给客户端的值。

返回

  • Any ( Any ) –

    在同一节点(更准确地说是同一任务)内的后续调用中,返回首次调用期间提供的值

引发

  • GraphInterrupt

    在节点内的首次调用时,停止执行并将提供的值呈现给客户端。

评论