Skip to main content
Functional API 允许您以最少的代码改动,将 LangGraph 的关键功能——持久化记忆human-in-the-loop流式传输——添加到您的应用程序中。 它旨在将这些功能集成到现有代码中,这些代码可能使用标准语言原语进行分支和控制流,例如 if 语句、for 循环和函数调用。与许多需要将代码重构为显式管道或 DAG 的数据编排框架不同,Functional API 允许您在不强制执行严格执行模型的情况下集成这些功能。 Functional API 使用两个关键构建块:
  • @entrypoint – 将函数标记为工作流的起始点,封装逻辑并管理执行流程,包括处理长时间运行的任务和中断。
  • @task – 表示一个离散的工作单元,例如 API 调用或数据处理步骤,可以在 entrypoint 内异步执行。任务返回一个类似 future 的对象,可以等待或同步解析。
这为构建具有状态管理和流式传输的工作流提供了最小抽象。
有关如何使用 Functional API 的信息,请参阅使用 Functional API

Functional API 与 Graph API

对于喜欢更具声明性方法的用户,LangGraph 的 Graph API 允许您使用图范式定义工作流。两种 API 共享相同的底层运行时,因此您可以在同一应用程序中同时使用它们。 以下是一些关键区别:
  • 控制流:Functional API 不需要考虑图结构。您可以使用标准 Python 构造来定义工作流。这通常会减少您需要编写的代码量。
  • 短期记忆GraphAPI 需要声明 State 并可能需要定义 reducers 来管理对图状态的更新。@entrypoint@tasks 不需要显式的状态管理,因为它们的状态仅限于函数范围,不在函数之间共享。
  • 检查点:两种 API 都会生成并使用检查点。在 Graph API 中,每次 superstep 之后都会生成一个新的检查点。在 Functional API 中,当任务执行时,其结果将保存到与给定 entrypoint 关联的现有检查点中,而不是创建新的检查点。
  • 可视化:Graph API 可以轻松地将工作流可视化为图,这对于调试、理解工作流以及与他人共享非常有用。Functional API 不支持可视化,因为图是在运行时动态生成的。

示例

下面我们演示一个简单的应用程序,该应用程序编写一篇文章并中断以请求人工审查。
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.func import entrypoint, task
from langgraph.types import interrupt

@task
def write_essay(topic: str) -> str:
    """Write an essay about the given topic."""
    time.sleep(1) # A placeholder for a long-running task.
    return f"An essay about topic: {topic}"

@entrypoint(checkpointer=InMemorySaver())
def workflow(topic: str) -> dict:
    """A simple workflow that writes an essay and asks for a review."""
    essay = write_essay("cat").result()
    is_approved = interrupt({
        # Any json-serializable payload provided to interrupt as argument.
        # It will be surfaced on the client side as an Interrupt when streaming data
        # from the workflow.
        "essay": essay, # The essay we want reviewed.
        # We can add any additional information that we need.
        # For example, introduce a key called "action" with some instructions.
        "action": "Please approve/reject the essay",
    })

    return {
        "essay": essay, # The essay that was generated
        "is_approved": is_approved, # Response from HIL
    }
此工作流将编写一篇关于”cat”主题的文章,然后暂停以获取人工审查。工作流可以无限期地暂停,直到提供审查为止。当工作流恢复时,它从最开始执行,但由于 writeEssay 任务的结果已经保存,任务结果将从检查点加载,而不是重新计算。
import time
import uuid
from langgraph.func import entrypoint, task
from langgraph.types import interrupt
from langgraph.checkpoint.memory import InMemorySaver


@task
def write_essay(topic: str) -> str:
    """Write an essay about the given topic."""
    time.sleep(1)  # This is a placeholder for a long-running task.
    return f"An essay about topic: {topic}"

@entrypoint(checkpointer=InMemorySaver())
def workflow(topic: str) -> dict:
    """A simple workflow that writes an essay and asks for a review."""
    essay = write_essay("cat").result()
    is_approved = interrupt(
        {
            # Any json-serializable payload provided to interrupt as argument.
            # It will be surfaced on the client side as an Interrupt when streaming data
            # from the workflow.
            "essay": essay,  # The essay we want reviewed.
            # We can add any additional information that we need.
            # For example, introduce a key called "action" with some instructions.
            "action": "Please approve/reject the essay",
        }
    )
    return {
        "essay": essay,  # The essay that was generated
        "is_approved": is_approved,  # Response from HIL
    }


thread_id = str(uuid.uuid4())
config = {"configurable": {"thread_id": thread_id}}
for item in workflow.stream("cat", config):
    print(item)
# > {'write_essay': 'An essay about topic: cat'}
# > {
# >     '__interrupt__': (
# >        Interrupt(
# >            value={
# >                'essay': 'An essay about topic: cat',
# >                'action': 'Please approve/reject the essay'
# >            },
# >            id='b9b2b9d788f482663ced6dc755c9e981'
# >        ),
# >    )
# > }
文章已编写完毕并等待审查。一旦提供了审查,我们可以恢复工作流:
from langgraph.types import Command

# Get review from a user (e.g., via a UI)
# In this case, we're using a bool, but this can be any json-serializable value.
human_review = True

for item in workflow.stream(Command(resume=human_review), config):
    print(item)
{'workflow': {'essay': 'An essay about topic: cat', 'is_approved': False}}
工作流已完成,审查结果已添加到文章中。

Entrypoint

@entrypoint 装饰器可用于从函数创建工作流。它封装工作流逻辑并管理执行流程,包括处理_长时间运行的任务_和中断

定义

entrypoint 通过使用 @entrypoint 装饰器修饰函数来定义。 函数必须接受单个位置参数,该参数作为工作流输入。如果需要传递多个数据,请使用字典作为第一个参数的输入类型。 使用 entrypoint 装饰函数会生成一个 Pregel 实例,该实例帮助管理工作流的执行(例如,处理流式传输、恢复和检查点)。 通常您需要将 checkpointer 传递给 @entrypoint 装饰器,以启用持久化并使用 human-in-the-loop 等功能。
from langgraph.func import entrypoint

@entrypoint(checkpointer=checkpointer)
def my_workflow(some_input: dict) -> int:
    # some logic that may involve long-running tasks like API calls,
    # and may be interrupted for human-in-the-loop.
    ...
    return result
序列化 entrypoint 的输入输出必须是 JSON 可序列化的,以支持检查点。请参阅序列化部分了解更多详情。

可注入参数

声明 entrypoint 时,您可以请求访问在运行时自动注入的附加参数。这些参数包括:
参数描述
previous访问与给定线程的上一个 checkpoint 关联的状态。请参阅短期记忆
store[BaseStore][langgraph.store.base.BaseStore] 的实例。对于长期记忆很有用。
writer在使用 Async Python < 3.11 时用于访问 StreamWriter。请参阅使用 Functional API 进行流式传输的详细信息
config用于访问运行时配置。请参阅 RunnableConfig 了解信息。
使用适当的名称和类型注解声明参数。
from langchain_core.runnables import RunnableConfig
from langgraph.func import entrypoint
from langgraph.store.base import BaseStore
from langgraph.store.memory import InMemoryStore
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import StreamWriter

in_memory_checkpointer = InMemorySaver(...)
in_memory_store = InMemoryStore(...)  # An instance of InMemoryStore for long-term memory

@entrypoint(
    checkpointer=in_memory_checkpointer,  # Specify the checkpointer
    store=in_memory_store  # Specify the store
)
def my_workflow(
    some_input: dict,  # The input (e.g., passed via `invoke`)
    *,
    previous: Any = None, # For short-term memory
    store: BaseStore,  # For long-term memory
    writer: StreamWriter,  # For streaming custom data
    config: RunnableConfig  # For accessing the configuration passed to the entrypoint
) -> ...:

执行

使用 @entrypoint 会生成一个 Pregel 对象,可以使用 invokeainvokestreamastream 方法执行。
config = {
    "configurable": {
        "thread_id": "some_thread_id"
    }
}
my_workflow.invoke(some_input, config)  # Wait for the result synchronously

恢复

中断之后恢复执行,可以通过将 resume 值传递给 Command 原语来实现。
from langgraph.types import Command

config = {
    "configurable": {
        "thread_id": "some_thread_id"
    }
}

my_workflow.invoke(Command(resume=some_resume_value), config)
错误后恢复 要在错误后恢复,请使用 None 和相同的线程 ID(config)运行 entrypoint 这假设底层错误已解决,执行可以成功进行。

config = {
    "configurable": {
        "thread_id": "some_thread_id"
    }
}

my_workflow.invoke(None, config)

短期记忆

entrypoint 使用 checkpointer 定义时,它会在相同线程 ID 的连续调用之间将信息存储在检查点中。 这允许使用 previous 参数访问上一次调用的状态。 默认情况下,previous 参数是上一次调用的返回值。
@entrypoint(checkpointer=checkpointer)
def my_workflow(number: int, *, previous: Any = None) -> int:
    previous = previous or 0
    return number + previous

config = {
    "configurable": {
        "thread_id": "some_thread_id"
    }
}

my_workflow.invoke(1, config)  # 1 (previous was None)
my_workflow.invoke(2, config)  # 3 (previous was 1 from the previous invocation)

entrypoint.final

entrypoint.final 是一个特殊的原语,可以从 entrypoint 返回,允许解耦保存在检查点中的值与 entrypoint 的返回值 第一个值是 entrypoint 的返回值,第二个值是将保存在检查点中的值。类型注解为 entrypoint.final[return_type, save_type]
@entrypoint(checkpointer=checkpointer)
def my_workflow(number: int, *, previous: Any = None) -> entrypoint.final[int, int]:
    previous = previous or 0
    # This will return the previous value to the caller, saving
    # 2 * number to the checkpoint, which will be used in the next invocation
    # for the `previous` parameter.
    return entrypoint.final(value=previous, save=2 * number)

config = {
    "configurable": {
        "thread_id": "1"
    }
}

my_workflow.invoke(3, config)  # 0 (previous was None)
my_workflow.invoke(1, config)  # 6 (previous was 3 * 2 from the previous invocation)

Task

task 表示一个离散的工作单元,例如 API 调用或数据处理步骤。它有两个关键特征:
  • 异步执行:任务设计为异步执行,允许多个操作并发运行而不阻塞。
  • 检查点:任务结果保存到检查点,使工作流能够从最后保存的状态恢复。(有关更多详细信息,请参阅持久化)。

定义

任务使用 @task 装饰器定义,它包装一个普通的 Python 函数。
from langgraph.func import task

@task()
def slow_computation(input_value):
    # Simulate a long-running operation
    ...
    return result
序列化 任务的输出必须是 JSON 可序列化的,以支持检查点。

执行

任务只能从entrypoint、另一个任务状态图节点内部调用。 任务_不能_直接从主应用程序代码中调用。 当您调用一个任务时,它会_立即_返回一个 future 对象。future 是稍后将可用结果的占位符。 要获取任务的结果,您可以同步等待它(使用 result())或异步等待它(使用 await)。
@entrypoint(checkpointer=checkpointer)
def my_workflow(some_input: int) -> int:
    future = slow_computation(some_input)
    return future.result()  # Wait for the result synchronously

何时使用任务

任务在以下场景中很有用:
  • 检查点:当您需要将长时间运行操作的结果保存到检查点时,这样在恢复工作流时就不需要重新计算。
  • Human-in-the-loop:如果您正在构建需要人工干预的工作流,您必须使用任务来封装任何随机性(例如 API 调用),以确保工作流可以正确恢复。有关更多详细信息,请参阅确定性部分。
  • 并行执行:对于 I/O 密集型任务,任务支持并行执行,允许多个操作并发运行而不阻塞(例如,调用多个 API)。
  • 可观察性:将操作包装在任务中提供了一种使用 LangSmith 跟踪工作流进度和监控单个操作执行的方式。
  • 可重试工作:当工作需要重试以处理失败或不一致时,任务提供了一种封装和管理重试逻辑的方式。

序列化

LangGraph 中的序列化有两个关键方面:
  1. entrypoint 的输入和输出必须是 JSON 可序列化的。
  2. task 的输出必须是 JSON 可序列化的。
这些要求对于启用检查点和工作流恢复是必要的。使用 Python 原语,如字典、列表、字符串、数字和布尔值,以确保您的输入和输出可序列化。 序列化确保工作流状态(如任务结果和中间值)可以可靠地保存和恢复。这对于启用 human-in-the-loop 交互、容错和并行执行至关重要。 提供不可序列化的输入或输出将导致使用检查点配置工作流时出现运行时错误。

确定性

要使用 human-in-the-loop 等功能,任何随机性都应封装在任务中。这保证了当执行被暂停(例如,用于 human in the loop)然后恢复时,它将遵循相同的_步骤序列_,即使任务结果是非确定性的。 LangGraph 通过在任务子图执行时持久化其结果来实现此行为。精心设计的工作流确保恢复执行遵循_相同的步骤序列_,允许正确检索先前计算的结果,而无需重新执行它们。这对于长时间运行的任务或具有非确定性结果的任务特别有用,因为它避免了重复先前已完成的工作,并允许从基本相同的位置恢复。 虽然工作流的不同运行可能产生不同的结果,但恢复特定运行应始终遵循相同的记录步骤序列。这允许 LangGraph 有效地查找在图被中断之前执行的任务子图结果,并避免重新计算它们。

幂等性

幂等性确保多次运行相同操作会产生相同的结果。这有助于在步骤因失败而重新运行时防止重复 API 调用和冗余处理。始终将 API 调用放在任务函数中以进行检查点,并将它们设计为幂等的以防止重新执行。如果任务开始但未成功完成,则可能发生重新执行。然后,如果工作流恢复,任务将再次运行。使用幂等性密钥或验证现有结果以避免重复。

常见陷阱

处理副作用

将副作用(例如,写入文件、发送电子邮件)封装在任务中,以确保在恢复工作流时不会多次执行。
在此示例中,副作用(写入文件)直接包含在工作流中,因此在恢复工作流时将再次执行。
@entrypoint(checkpointer=checkpointer)
def my_workflow(inputs: dict) -> int:
    # This code will be executed a second time when resuming the workflow.
    # Which is likely not what you want.
    with open("output.txt", "w") as f:
        f.write("Side effect executed")
    value = interrupt("question")
    return value

非确定性控制流

每次可能给出不同结果的操作(如获取当前时间或随机数)应封装在任务中,以确保在恢复时返回相同的结果。
  • 在任务中:获取随机数 (5) → 中断 → 恢复 → (再次返回 5)→ …
  • 不在任务中:获取随机数 (5) → 中断 → 恢复 → 获取新随机数 (7) → …
这在使用具有多个中断调用的 human-in-the-loop 工作流时尤为重要。LangGraph 为每个任务/entrypoint 保留一个恢复值列表。当遇到中断时,它与相应的恢复值匹配。此匹配严格基于索引,因此恢复值的顺序应与中断的顺序匹配。 如果恢复时执行顺序未保持,一个 interrupt 调用可能与错误的 resume 值匹配,导致错误的结果。 有关更多详细信息,请阅读确定性部分。
在此示例中,工作流使用当前时间来确定要执行哪个任务。这是非确定性的,因为工作流的结果取决于执行时间。
from langgraph.func import entrypoint

@entrypoint(checkpointer=checkpointer)
def my_workflow(inputs: dict) -> int:
    t0 = inputs["t0"]
    t1 = time.time()

    delta_t = t1 - t0

    if delta_t > 1:
        result = slow_task(1).result()
        value = interrupt("question")
    else:
        result = slow_task(2).result()
        value = interrupt("question")

    return {
        "result": result,
        "value": value
    }

了解更多