Skip to content
LangSmith 文档版本 跟随上游 源快照 edecfeac 更新于 2026-10-18

使用服务器 API 进行时间旅行

LangGraph 提供时间旅行功能,可从先前的检查点恢复执行,既可以重放相同状态,也可以修改状态以探索其他方案。无论哪种情况,恢复过去的执行都会在历史中产生新的分支。

要使用 LangSmith Deployment API(通过 LangGraph SDK)进行时间旅行:

  1. 使用 LangGraph SDK 的 client.runs.wait 或 client.runs.stream API,以初始输入运行图。
  2. 在现有线程中识别检查点:使用 client.threads.get_history 方法检索特定 thread_id 的执行历史,并定位所需的 checkpoint_id。 或者,在你希望执行暂停的节点之前设置断点。然后可以找到截至该断点最近记录的检查点。
  3. (可选)修改图状态:使用 client.threads.update_state 方法修改图在检查点处的状态,并从替代状态恢复执行。
  4. 从检查点恢复执行:使用 client.runs.wait 或 client.runs.stream API,传入 None 作为输入,并提供适当的 thread_id 和 checkpoint_id。

在工作流中使用时间旅行

示例图
python
from typing_extensions import TypedDict, NotRequired
from langgraph.graph import StateGraph, START, END
from langchain.chat_models import init_chat_model
from langgraph.checkpoint.memory import InMemorySaver

class State(TypedDict):
    topic: NotRequired[str]
    joke: NotRequired[str]

model = init_chat_model(
    "claude-sonnet-4-6",
    temperature=0,
)

def generate_topic(state: State):
    """LLM call to generate a topic for the joke"""
    msg = model.invoke("Give me a funny topic for a joke")
    return {"topic": msg.content}

def write_joke(state: State):
    """LLM call to write a joke based on the topic"""
    msg = model.invoke(f"Write a short joke about {state['topic']}")
    return {"joke": msg.content}

# Build workflow
builder = StateGraph(State)

# Add nodes
builder.add_node("generate_topic", generate_topic)
builder.add_node("write_joke", write_joke)

# Add edges to connect nodes
builder.add_edge(START, "generate_topic")
builder.add_edge("generate_topic", "write_joke")

# Compile
graph = builder.compile()

1. 运行图

python
from langgraph_sdk import get_client
client = get_client(url=<DEPLOYMENT_URL>)

# Using the graph deployed with the name "agent"
assistant_id = "agent"

# create a thread
thread = await client.threads.create()
thread_id = thread["thread_id"]

# Run the graph
result = await client.runs.wait(
    thread_id,
    assistant_id,
    input={}
)

2. 识别检查点

python
# The states are returned in reverse chronological order.
states = await client.threads.get_history(thread_id)
selected_state = states[1]
print(selected_state)

3. 更新状态

update_state 将创建一个新检查点。新检查点将关联到同一线程,但使用新的检查点 ID。

python
new_config = await client.threads.update_state(
    thread_id,
    {"topic": "chickens"},
    checkpoint_id=selected_state["checkpoint_id"]
)
print(new_config)

4. 从检查点恢复执行

python
await client.runs.wait(
    thread_id,
    assistant_id,
    input=None,
    checkpoint_id=new_config["checkpoint_id"]
)

了解更多


BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。