Skip to content

6.4 处理连续消息 ​

本章依据上游 Notebook 与 Python 实现重新整理;教学说明为本站新增中文内容,英文版与之对应。

原始 Notebook · 配套 Python 与配置

版本与运行环境

代码对应上游 2025-10-12 快照,并非对最新版 SDK 的兼容承诺。以下原始代码按 Notebook 单元顺序保留,包含 Jupyter %pip / %%capture 等语法,应在 Notebook 环境分单元执行。凭据通过本地环境配置,不要写入网页或提交 Git。本网站只渲染教程,未运行这些付费模型或 Docker 实验。

为什么需要并发输入策略 ​

用户可能在第一个 run 仍执行时发送第二条消息。新 run 的 multitask_strategy 决定同一 thread 如何处理这种情况。测试必须确保首个 run 尚未完成,否则第二条成功并不能证明并发策略生效。

拒绝或排队 ​

reject 在线程忙碌时拒绝新 run,示例捕获 HTTPStatusError。enqueue 保留两次请求,按顺序执行。界面需要说明拒绝原因或显示排队状态,避免用户误以为消息丢失。

中断或回滚 ​

interrupt 停止当前 run,但保留已保存进展,旧 run 可显示 interrupted。rollback 移除之前的 run 并回退 thread 状态,再运行新输入。两者都不能被当成外部副作用的自动撤销机制,例如已发送的邮件或独立的 Store 写入。

原始代码单元 ​

保留上游代码中的英文注释和标识符。各单元共享前面的变量;Notebook 输出与历史截图不作为本次运行结果。

单元 1 ​

python
%%capture --no-stderr
%pip install -U langgraph_sdk

单元 2 ​

python
from langgraph_sdk import get_client
url_for_cli_deployment = "http://localhost:8123"
client = get_client(url=url_for_cli_deployment)

单元 3 ​

python
import httpx
from langchain_core.messages import HumanMessage

# Create a thread
thread = await client.threads.create()

# Create to dos
user_input_1 = "Add a ToDo to follow-up with DI Repairs."
user_input_2 = "Add a ToDo to mount dresser to the wall."
config = {"configurable": {"user_id": "Test-Double-Texting"}}
graph_name = "task_maistro"

run = await client.runs.create(
    thread["thread_id"],
    graph_name,
    input={"messages": [HumanMessage(content=user_input_1)]},
    config=config,
)
try:
    await client.runs.create(
        thread["thread_id"],
        graph_name,
        input={"messages": [HumanMessage(content=user_input_2)]},
        config=config,
        multitask_strategy="reject",
    )
except httpx.HTTPStatusError as e:
    print("Failed to start concurrent run", e)

单元 4 ​

python
from langchain_core.messages import convert_to_messages

# Wait until the original run completes
await client.runs.join(thread["thread_id"], run["run_id"])

# Get the state of the thread
state = await client.threads.get_state(thread["thread_id"])
for m in convert_to_messages(state["values"]["messages"]):
    m.pretty_print()

单元 5 ​

python
# Create a new thread
thread = await client.threads.create()

# Create new ToDos
user_input_1 = "Send Erik his t-shirt gift this weekend."
user_input_2 = "Get cash and pay nanny for 2 weeks. Do this by Friday."
config = {"configurable": {"user_id": "Test-Double-Texting"}}
graph_name = "task_maistro"

first_run = await client.runs.create(
    thread["thread_id"],
    graph_name,
    input={"messages": [HumanMessage(content=user_input_1)]},
    config=config,
)

second_run = await client.runs.create(
    thread["thread_id"],
    graph_name,
    input={"messages": [HumanMessage(content=user_input_2)]},
    config=config,
    multitask_strategy="enqueue",
)

# Wait until the second run completes
await client.runs.join(thread["thread_id"], second_run["run_id"])

# Get the state of the thread
state = await client.threads.get_state(thread["thread_id"])
for m in convert_to_messages(state["values"]["messages"]):
    m.pretty_print()

单元 6 ​

python
import asyncio

# Create a new thread
thread = await client.threads.create()

# Create new ToDos
user_input_1 = "Give me a summary of my ToDos due tomrrow."
user_input_2 = "Never mind, create a ToDo to Order Ham for Thanksgiving by next Friday."
config = {"configurable": {"user_id": "Test-Double-Texting"}}
graph_name = "task_maistro"

interrupted_run = await client.runs.create(
    thread["thread_id"],
    graph_name,
    input={"messages": [HumanMessage(content=user_input_1)]},
    config=config,
)

# Wait for some of run 1 to complete so that we can see it in the thread
await asyncio.sleep(1)

second_run = await client.runs.create(
    thread["thread_id"],
    graph_name,
    input={"messages": [HumanMessage(content=user_input_2)]},
    config=config,
    multitask_strategy="interrupt",
)

# Wait until the second run completes
await client.runs.join(thread["thread_id"], second_run["run_id"])

# Get the state of the thread
state = await client.threads.get_state(thread["thread_id"])
for m in convert_to_messages(state["values"]["messages"]):
    m.pretty_print()

单元 7 ​

python
# Confirm that the first run was interrupted
print((await client.runs.get(thread["thread_id"], interrupted_run["run_id"]))["status"])

单元 8 ​

python
# Create a new thread
thread = await client.threads.create()

# Create new ToDos
user_input_1 = "Add a ToDo to call to make appointment at Yoga."
user_input_2 = "Actually, add a ToDo to drop by Yoga in person on Sunday."
config = {"configurable": {"user_id": "Test-Double-Texting"}}
graph_name = "task_maistro"

rolled_back_run = await client.runs.create(
    thread["thread_id"],
    graph_name,
    input={"messages": [HumanMessage(content=user_input_1)]},
    config=config,
)

second_run = await client.runs.create(
    thread["thread_id"],
    graph_name,
    input={"messages": [HumanMessage(content=user_input_2)]},
    config=config,
    multitask_strategy="rollback",
)

# Wait until the second run completes
await client.runs.join(thread["thread_id"], second_run["run_id"])

# Get the state of the thread
state = await client.threads.get_state(thread["thread_id"])
for m in convert_to_messages(state["values"]["messages"]):
    m.pretty_print()

单元 9 ​

python
# Confirm that the original run was deleted
try:
    await client.runs.get(thread["thread_id"], rolled_back_run["run_id"])
except httpx.HTTPStatusError as _:
    print("Original run was correctly deleted")

练习与检查 ​

每种策略用新的测试 thread 运行,同时检查 run 状态和 thread 消息。rollback 后还要单独检查 Store;enqueue 应等待第二个 run 完成再判断最终状态。

完整讲解、历史输出和图示请对照 Notebook。

内容基于 MIT 许可证发布;版权归原作者所有。