时间旅行¶
在典型的聊天机器人工作流程中,用户会与机器人进行一次或多次交互以完成任务。记忆和人机协作可以在图状态中设置检查点并控制未来的响应。
如果希望用户能够从之前的回复开始,探索不同的结果呢?或者,是否希望用户能够回退聊天机器人的工作,以纠正错误或尝试不同的策略?这在像自主软件工程师这样的应用中是常见的。
你可以使用 LangGraph 内置的 时间旅行 功能来创建这些类型的体验。
Note
本教程基于 自定义状态。
1. 回退你的图¶
通过使用图的 get_state_history
方法获取一个检查点来回退你的图。然后你可以从这个之前的时间点恢复执行。
{}¶
import os
from langchain.chat_models import init_chat_model
os.environ["AZURE_OPENAI_API_KEY"] = "..."
os.environ["AZURE_OPENAI_ENDPOINT"] = "..."
os.environ["OPENAI_API_VERSION"] = "2025-03-01-preview"
llm = init_chat_model(
"azure_openai:gpt-4.1",
azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"],
)
API Reference: TavilySearch | BaseMessage | MemorySaver | StateGraph | START | END | add_messages | ToolNode | tools_condition
from typing import Annotated
from langchain_tavily import TavilySearch
from langchain_core.messages import BaseMessage
from typing_extensions import TypedDict
from langgraph.checkpoint.memory import MemorySaver
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode, tools_condition
class State(TypedDict):
messages: Annotated[list, add_messages]
graph_builder = StateGraph(State)
tool = TavilySearch(max_results=2)
tools = [tool]
llm_with_tools = llm.bind_tools(tools)
def chatbot(state: State):
return {"messages": [llm_with_tools.invoke(state["messages"])]}
graph_builder.add_node("chatbot", chatbot)
tool_node = ToolNode(tools=[tool])
graph_builder.add_node("tools", tool_node)
graph_builder.add_conditional_edges(
"chatbot",
tools_condition,
)
graph_builder.add_edge("tools", "chatbot")
graph_builder.add_edge(START, "chatbot")
memory = MemorySaver()
graph = graph_builder.compile(checkpointer=memory)
2. 添加步骤¶
向你的图中添加步骤。每个步骤的状态历史都会被记录为检查点:
config = {"configurable": {"thread_id": "1"}}
events = graph.stream(
{
"messages": [
{
"role": "user",
"content": (
"I'm learning LangGraph. "
"Could you do some research on it for me?"
),
},
],
},
config,
stream_mode="values",
)
for event in events:
if "messages" in event:
event["messages"][-1].pretty_print()
================================ Human Message =================================
I'm learning LangGraph. Could you do some research on it for me?
================================== Ai Message ==================================
[{'text': "Certainly! I'd be happy to research LangGraph for you. To get the most up-to-date and accurate information, I'll use the Tavily search engine to look this up. Let me do that for you now.", 'type': 'text'}, {'id': 'toolu_01BscbfJJB9EWJFqGrN6E54e', 'input': {'query': 'LangGraph latest information and features'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]
Tool Calls:
tavily_search_results_json (toolu_01BscbfJJB9EWJFqGrN6E54e)
Call ID: toolu_01BscbfJJB9EWJFqGrN6E54e
Args:
query: LangGraph latest information and features
================================= Tool Message =================================
Name: tavily_search_results_json
[{"url": "https://blockchain.news/news/langchain-new-features-upcoming-events-update", "content": "LangChain, a leading platform in the AI development space, has released its latest updates, showcasing new use cases and enhancements across its ecosystem. According to the LangChain Blog, the updates cover advancements in LangGraph Platform, LangSmith's self-improving evaluators, and revamped documentation for LangGraph."}, {"url": "https://blog.langchain.dev/langgraph-platform-announce/", "content": "With these learnings under our belt, we decided to couple some of our latest offerings under LangGraph Platform. LangGraph Platform today includes LangGraph Server, LangGraph Studio, plus the CLI and SDK. ... we added features in LangGraph Server to deliver on a few key value areas. Below, we'll focus on these aspects of LangGraph Platform."}]
================================== Ai Message ==================================
Thank you for your patience. I've found some recent information about LangGraph for you. Let me summarize the key points:
1. LangGraph 是 LangChain 生态系统的一部分,这是一个在人工智能开发领域领先的平台。
2. LangGraph 最新更新和功能包括:
a. LangGraph 平台:这似乎是 LangGraph 的云版本,尽管搜索结果中没有提供具体细节。
...
3. 请关注 LangGraph 平台的开发,因为基于云的解决方案通常为学习者提供了更简单的入门方式。
4. 考虑 LangGraph 在整个 LangChain 生态系统中的定位,特别是其与 LangSmith 等工具的交互。
你是否想了解 LangGraph 的某个特定方面?我很乐意为您进行更深入的搜索,针对特定的功能或用例。
输出已被截断。以可滚动元素查看或在文本编辑器中打开。调整单元格输出设置...
events = graph.stream(
{
"messages": [
{
"role": "user",
"content": (
"Ya that's helpful. Maybe I'll "
"build an autonomous agent with it!"
),
},
],
},
config,
stream_mode="values",
)
for event in events:
if "messages" in event:
event["messages"][-1].pretty_print()
================================ Human Message =================================
Ya that's helpful. Maybe I'll build an autonomous agent with it!
================================== Ai Message ==================================
[{'text': "That's an exciting idea! Building an autonomous agent with LangGraph is indeed a great application of this technology. LangGraph is particularly well-suited for creating complex, multi-step AI workflows, which is perfect for autonomous agents. Let me gather some more specific information about using LangGraph for building autonomous agents.", 'type': 'text'}, {'id': 'toolu_01QWNHhUaeeWcGXvA4eHT7Zo', 'input': {'query': 'Building autonomous agents with LangGraph examples and tutorials'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]
Tool Calls:
tavily_search_results_json (toolu_01QWNHhUaeeWcGXvA4eHT7Zo)
Call ID: toolu_01QWNHhUaeeWcGXvA4eHT7Zo
Args:
query: Building autonomous agents with LangGraph examples and tutorials
================================= Tool Message =================================
Name: tavily_search_results_json
[{"url": "https://towardsdatascience.com/building-autonomous-multi-tool-agents-with-gemini-2-0-and-langgraph-ad3d7bd5e79d", "content": "Building Autonomous Multi-Tool Agents with Gemini 2.0 and LangGraph | by Youness Mansar | Jan, 2025 | Towards Data Science Building Autonomous Multi-Tool Agents with Gemini 2.0 and LangGraph A practical tutorial with full code examples for building and running multi-tool agents Towards Data Science LLMs are remarkable — they can memorize vast amounts of information, answer general knowledge questions, write code, generate stories, and even fix your grammar. In this tutorial, we are going to build a simple LLM agent that is equipped with four tools that it can use to answer a user’s question. This Agent will have the following specifications: Follow Published in Towards Data Science --------------------------------- Your home for data science and AI. Follow Follow Follow"}, {"url": "https://github.com/anmolaman20/Tools_and_Agents", "content": "GitHub - anmolaman20/Tools_and_Agents: This repository provides resources for building AI agents using Langchain and Langgraph. This repository provides resources for building AI agents using Langchain and Langgraph. This repository provides resources for building AI agents using Langchain and Langgraph. This repository serves as a comprehensive guide for building AI-powered agents using Langchain and Langgraph. It provides hands-on examples, practical tutorials, and resources for developers and AI enthusiasts to master building intelligent systems and workflows. AI Agent Development: Gain insights into creating intelligent systems that think, reason, and adapt in real time. This repository is ideal for AI practitioners, developers exploring language models, or anyone interested in building intelligent systems. This repository provides resources for building AI agents using Langchain and Langgraph."}]
================================== Ai Message ==================================
Great idea! Building an autonomous agent with LangGraph is definitely an exciting project. Based on the latest information I've found, here are some insights and tips for building autonomous agents with LangGraph:
1. 多工具代理:LangGraph 特别适合创建能够使用多个工具的自主代理。这允许您的代理具有多样化的功能,并为每个任务选择合适的工具。
2. 与大型语言模型(LLMs)集成:您可以将 LangGraph 与强大的 LLM(如 Gemini 2.0)结合使用,以创建更智能、功能更强的代理。LLM 可以作为您代理的“大脑”,做出决策并生成响应。
3. 工作流管理:LangGraph 在管理复杂、多步骤的人工智能工作流方面表现出色。这对于需要将任务分解为较小步骤并按正确顺序执行的自主代理至关重要。
...
6. 注意如何构建代理的决策过程和工作流。
7. 不要忘记实现适当的错误处理和安全措施,尤其是如果您的代理将与外部系统交互或做出重要决策时。
构建一个自主代理是一个迭代的过程,因此准备好逐步完善和改进您的代理。祝你在项目中好运!如果你在推进过程中需要任何更具体的信息,请随时提问。
输出已被截断。以可滚动元素查看或在文本编辑器中打开。调整单元格输出设置...
3. 重放完整状态历史¶
现在你已经向聊天机器人添加了步骤,你可以 replay
完整的状态历史,以查看所有发生的情况。
to_replay = None
for state in graph.get_state_history(config):
print("Num Messages: ", len(state.values["messages"]), "Next: ", state.next)
print("-" * 80)
if len(state.values["messages"]) == 6:
# 我们基于状态中聊天消息的数量,任意选择一个特定的状态。
to_replay = state
Num Messages: 8 Next: ()
--------------------------------------------------------------------------------
Num Messages: 7 Next: ('chatbot',)
--------------------------------------------------------------------------------
Num Messages: 6 Next: ('tools',)
--------------------------------------------------------------------------------
Num Messages: 5 Next: ('chatbot',)
--------------------------------------------------------------------------------
Num Messages: 4 Next: ('__start__',)
--------------------------------------------------------------------------------
Num Messages: 4 Next: ()
--------------------------------------------------------------------------------
Num Messages: 3 Next: ('chatbot',)
--------------------------------------------------------------------------------
Num Messages: 2 Next: ('tools',)
--------------------------------------------------------------------------------
Num Messages: 1 Next: ('chatbot',)
--------------------------------------------------------------------------------
Num Messages: 0 Next: ('__start__',)
--------------------------------------------------------------------------------
图的每一步都会保存检查点。这 涵盖了调用,因此你可以回退到整个线程的历史记录。
从检查点恢复¶
从 to_replay
状态恢复,该状态位于第二次调用图中的 chatbot
节点之后。从这一点恢复将接下来调用 action 节点。
('tools',)
{'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1efd43e3-0c1f-6c4e-8006-891877d65740'}}
4. 从某一时刻加载状态¶
检查点的 to_replay.config
中包含一个 checkpoint_id
时间戳。提供这个 checkpoint_id
值会告诉 LangGraph 的检查点系统 加载 该时间点的状态。
# `to_replay.config` 中的 `checkpoint_id` 对应我们已保存到检查点系统中的某个状态。
for event in graph.stream(None, to_replay.config, stream_mode="values"):
if "messages" in event:
event["messages"][-1].pretty_print()
================================== Ai Message ==================================
[{'text': "That's an exciting idea! Building an autonomous agent with LangGraph is indeed a great application of this technology. LangGraph is particularly well-suited for creating complex, multi-step AI workflows, which is perfect for autonomous agents. Let me gather some more specific information about using LangGraph for building autonomous agents.", 'type': 'text'}, {'id': 'toolu_01QWNHhUaeeWcGXvA4eHT7Zo', 'input': {'query': 'Building autonomous agents with LangGraph examples and tutorials'}, 'name': 'tavily_search_results_json', 'type': 'tool_use'}]
Tool Calls:
tavily_search_results_json (toolu_01QWNHhUaeeWcGXvA4eHT7Zo)
Call ID: toolu_01QWNHhUaeeWcGXvA4eHT7Zo
Args:
query: Building autonomous agents with LangGraph examples and tutorials
================================= Tool Message =================================
Name: tavily_search_results_json
[{"url": "https://towardsdatascience.com/building-autonomous-multi-tool-agents-with-gemini-2-0-and-langgraph-ad3d7bd5e79d", "content": "Building Autonomous Multi-Tool Agents with Gemini 2.0 and LangGraph | by Youness Mansar | Jan, 2025 | Towards Data Science Building Autonomous Multi-Tool Agents with Gemini 2.0 and LangGraph A practical tutorial with full code examples for building and running multi-tool agents Towards Data Science LLMs are remarkable — they can memorize vast amounts of information, answer general knowledge questions, write code, generate stories, and even fix your grammar. In this tutorial, we are going to build a simple LLM agent that is equipped with four tools that it can use to answer a user’s question. This Agent will have the following specifications: Follow Published in Towards Data Science --------------------------------- Your home for data science and AI. Follow Follow Follow"}, {"url": "https://github.com/anmolaman20/Tools_and_Agents", "content": "GitHub - anmolaman20/Tools_and_Agents: This repository provides resources for building AI agents using Langchain and Langgraph. This repository provides resources for building AI agents using Langchain and Langgraph. This repository provides resources for building AI agents using Langchain and Langgraph. This repository serves as a comprehensive guide for building AI-powered agents using Langchain and Langgraph. It provides hands-on examples, practical tutorials, and resources for developers and AI enthusiasts to master building intelligent systems and workflows. AI Agent Development: Gain insights into creating intelligent systems that think, reason, and adapt in real time. This repository is ideal for AI practitioners, developers exploring language models, or anyone interested in building intelligent systems. This repository provides resources for building AI agents using Langchain and Langgraph."}]
================================== Ai Message ==================================
Great idea! Building an autonomous agent with LangGraph is indeed an excellent way to apply and deepen your understanding of the technology. Based on the search results, I can provide you with some insights and resources to help you get started:
1. Multi-Tool Agents:
LangGraph is well-suited for building autonomous agents that can use multiple tools. This allows your agent to have a variety of capabilities and choose the appropriate tool based on the task at hand.
2. Integration with Large Language Models (LLMs):
There's a tutorial that specifically mentions using Gemini 2.0 (Google's LLM) with LangGraph to build autonomous agents. This suggests that LangGraph can be integrated with various LLMs, giving you flexibility in choosing the language model that best fits your needs.
3. Practical Tutorials:
There are tutorials available that provide full code examples for building and running multi-tool agents. These can be invaluable as you start your project, giving you a concrete starting point and demonstrating best practices.
...
Remember, building an autonomous agent is an iterative process. Start simple and gradually increase complexity as you become more comfortable with LangGraph and its capabilities.
Would you like more information on any specific aspect of building your autonomous agent with LangGraph?
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
图从 action
节点恢复了执行。你可以通过上面打印的第一个值是来自搜索引擎工具的响应来判断这一点。
恭喜! 现在你已经使用了 LangGraph 中的时间旅行检查点遍历功能。能够回退并探索其他路径,为调试、实验和交互式应用打开了无限可能。
了解更多¶
通过探索部署和高级功能,进一步深入了解 LangGraph:
- LangGraph Server 快速入门: 在本地启动 LangGraph 服务器,并通过 REST API 和 LangGraph Studio Web UI 与其进行交互。
- LangGraph 平台快速入门: 使用 LangGraph 平台部署你的 LangGraph 应用。
- LangGraph 平台概念: 了解 LangGraph 平台的基础概念。