在典型的聊天机器人工作流中,用户与机器人交互 1 次或多次来完成任务。在前面的部分中,我们看到了如何添加记忆和人在回路功能,以便能够检查我们的图状态并控制未来的回复。

但是,如果您想让用户从之前的回复开始,“分支”出来探索另一个结果怎么办?或者,如果您想让用户能够“回溯”您的助手的操作,以修复一些错误或尝试不同的策略(这在自主软件工程师等应用中很常见)怎么办?

您可以使用 LangGraph 的内置“时间旅行”功能创建这两种体验以及更多功能。在本节中,您将通过使用图的 get_state_history 方法获取检查点来“回溯”您的图。然后,您可以在之前的时间点恢复执行。

官方文档参考:时间旅行

创建聊天机器人

这部分照搬第三章节的代码:

import os
from typing import Annotated # from langchain.chat_models import init_chat_model
from langchain_openai import ChatOpenAI
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 #环境变量设置,替换为你的API_KEY
os.environ['TAVILY_API_KEY'] = 'TAVILY_API_KEY'
os.environ['ARK_API_KEY'] = 'API_KEY' class State(TypedDict):
messages: Annotated[list, add_messages] graph_builder = StateGraph(State) tool = TavilySearch(max_results=2)
tools = [tool]
llm = ChatOpenAI(
base_url="https://ark.cn-beijing.volces.com/api/v3",
api_key=os.environ.get('ARK_API_KEY'),
model="doubao-1-5-pro-32k-250115" # 根据实际模型名称修改
)
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)

添加步骤

向你的图中添加步骤。每个步骤的状态历史都会被记录为检查点:

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 ================================== 用户需要了解LangGraph的相关信息,调用tavily_search函数进行查询。
Tool Calls:
tavily_search (call_krieo3m8ddu6ob3gojouzvtp)
Call ID: call_krieo3m8ddu6ob3gojouzvtp
Args:
query: Introduction to LangGraph, including its features, use cases, and related technologies
search_depth: advanced
================================= Tool Message =================================
Name: tavily_search {"query": "Introduction to LangGraph, including its features, use cases, and related technologies", "follow_up_questions": null, "answer": null, "images": [], "results": [{"url": "https://www.ibm.com/think/topics/langgraph", "title": "What is LangGraph? - IBM", "content": "LangGraph, created by [LangChain](https://www.ibm.com/think/topics/langchain), is an open source AI agent framework designed to build, deploy and manage complex generative AI agent workflows. It provides a set of tools and libraries that enable users to create, run and optimize [large language models](https://www.ibm.com/think/topics/large-language-models) (LLMs) in a scalable and efficient manner. At its core, LangGraph uses the power of graph-based architectures to model and manage the [...] LangGraph is also built on several key technologies, including [LangChain,](https://www.ibm.com/think/topics/langchain) a Python framework for building AI applications. LangChain includes a library for building and managing [LLMs](https://www.ibm.com/think/topics/large-language-models). LangGraph also uses the human-in-the-loop approach. By combining these technologies with a set of APIs and tools, LangGraph provides users with a versatile platform for developing AI solutions and workflows [...] **Agent systems**: LangGraph provides a framework for building agent-based systems, which can be used in applications such as robotics, autonomous vehicles or video games.\n\n**LLM applications**: By using LangGraph’s capabilities, developers can build more sophisticated AI models that learn and improve over time. Norwegian Cruise Line uses LangGraph to compile, construct and refine guest-facing AI solutions. This capability allows for improved and personalized guest experiences.", "score": 0.75442725, "raw_content": null}, {"url": "https://www.langchain.com/langgraph", "title": "LangGraph - LangChain", "content": "LangGraph is a stateful, orchestration framework that brings added control to agent workflows. LangGraph Platform is a service for deploying and scaling LangGraph applications, with an opinionated API for building agent UXs, plus an integrated developer studio.\n\nLangGraph (open source)\n\nLangGraph Platform\n\nFeatures\n\nDescription\n\nStateful orchestration framework for agentic applications\n\nScalable infrastructure for deploying LangGraph applications\n\nSDKs\n\nPython and JavaScript [...] ![Image 1](https://cdn.prod.website-files.com/65b8cd72835ceeacd4449a53/66db8c2317fe5b9ad2b84ea0_lcacademylogo.png)\nIntroduction to LangGraph\n-------------------------\n\nLearn the basics of LangGraph in this LangChain Academy Course. You'll learn how to build agents that automate real-world tasks with LangGraph orchestration.\n\n[Enroll for free](https://academy.langchain.com/courses/intro-to-langgraph)[Book enterprise training](https://airtable.com/appGjCAN6126Jm7K8/pagNAp7niHQzRH8zk/form) [...] Introduction to LangGraph\n-------------------------\n\nLearn the basics of LangGraph in this LangChain Academy Course. You'll learn how to build agents that automate real-world tasks with LangGraph orchestration.\n\n[Enroll for free](https://academy.langchain.com/courses/intro-to-langgraph)[Book a training](https://airtable.com/appGjCAN6126Jm7K8/pagNAp7niHQzRH8zk/form)", "score": 0.7173491, "raw_content": null}], "response_time": 1.67}
================================== Ai Message ================================== LangGraph is an open - source AI agent framework created by LangChain. It is designed to build, deploy, and manage complex generative AI agent workflows. ### Key Features
1. **Graph - based Architecture**: It uses graph - based architectures to model and manage large language models (LLMs). This helps in handling complex workflows in a structured way.
2. **Stateful Orchestration**: It is a stateful orchestration framework for agentic applications, bringing added control to agent workflows.
3. **SDK Support**: It provides SDKs in Python and JavaScript, which is convenient for developers to use.
4. **Scalable Infrastructure**: The LangGraph Platform offers a scalable infrastructure for deploying LangGraph applications. ### Technologies It Builds On
1. **LangChain**: LangGraph is built on LangChain, a Python framework for building AI applications. LangChain includes a library for building and managing LLMs.
2. **Human - in - the - Loop Approach**: It also uses the human - in - the - loop approach, which combines human expertise with AI capabilities. ### Use Cases
1. **Agent Systems**: It provides a framework for building agent - based systems, which can be used in applications such as robotics, autonomous vehicles, or video games.
2. **LLM Applications**: Developers can use LangGraph to build more sophisticated AI models that learn and improve over time. For example, Norwegian Cruise Line uses LangGraph to compile, construct, and refine guest - facing AI solutions, enabling improved and personalized guest experiences. You can find more information about LangGraph on [What is LangGraph? - IBM](https://www.ibm.com/think/topics/langgraph) and [LangGraph - LangChain](https://www.langchain.com/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 ================================== Building an autonomous agent with LangGraph is an exciting endeavor! To learn more about the process of building an autonomous agent using LangGraph, I'll search for relevant information.
Tool Calls:
tavily_search (call_omts787jviabpafisk9j2yil)
Call ID: call_omts787jviabpafisk9j2yil
Args:
query: Steps and best practices for building an autonomous agent with LangGraph
search_depth: advanced
================================= Tool Message =================================
Name: tavily_search {"query": "Steps and best practices for building an autonomous agent with LangGraph", "follow_up_questions": null, "answer": null, "images": [], "results": [{"url": "https://www.amazon.com/Building-Autonomous-Agents-LangGraph-Developers/dp/B0DVR7LL3G", "title": "Building Autonomous AI Agents with LangGraph: A Developer's Guide", "content": "This guide stands out among LangGraph books by offering the complete LangGraph blueprint you need to master every aspect of managing autonomous systems. Learn how to create AI agent LangGraph designs that not only simplify the development process but also empower you to build sophisticated, self-operating systems. Our step-by-step tutorials cover everything—from basic graph theory to mastering LangGraph, ensuring you gain the confidence to tackle complex projects with ease. [...] Building Autonomous AI Agents with LangGraph: A Developer’s Guide is the ultimate resource for developers who want to harness the power of modern graph-based AI. This comprehensive guide demystifies LangGraph and provides a complete LangGraph blueprint for designing, building, and optimizing autonomous AI agents. Whether you’re a seasoned coder or just starting out, this book is packed with practical insights, detailed LangGraph code examples, and hands-on projects that will take your skills to [...] With clear explanations, robust code examples, and expert advice on LangGraph managing AI agents systems using best practices, this book is your go-to resource for mastering LangGraph and building cutting-edge solutions. Explore topics that cover LangGraph and AI agents, as well as the innovative integration of Langchain Langraph—all presented in a style that’s both engaging and accessible.", "score": 0.78846955, "raw_content": null}, {"url": "https://profil-software.com/blog/machine-learning/the-revolutionary-world-of-ai-agents-why-how-to-build-them-leveraging-langgraph/", "title": "How to create AI Agents with LangGraph? Step-by-step guide", "content": "The control flow of an agent typically follows a sequence of steps. First, the agent receives a query or instruction from a user. Next, it uses its language model to reason about what actions would be appropriate to fulfill the request. Then, it selects and calls the relevant tools with specific parameters. Finally, it processes the results of those tool calls to either formulate a response or determine additional actions to take.", "score": 0.7515939, "raw_content": null}], "response_time": 1.97}
================================== Ai Message ================================== Here are some insights on building an autonomous agent with LangGraph: ### General Resources
- There is a book titled "Building Autonomous AI Agents with LangGraph: A Developer's Guide". It offers a complete LangGraph blueprint to master every aspect of managing autonomous systems. The book includes step - by - step tutorials covering from basic graph theory to mastering LangGraph, and is filled with practical insights, detailed code examples, and hands - on projects. It can be a great resource whether you're a seasoned coder or a beginner. ### Control Flow of an Agent
- When building an autonomous agent, the control flow typically involves the following steps:
1. **Receiving a Query**: The agent first gets a query or instruction from a user.
2. **Reasoning**: It uses its language model to figure out appropriate actions to fulfill the request.
3. **Tool Selection and Call**: The agent selects relevant tools and calls them with specific parameters.
4. **Result Processing**: It processes the results of the tool calls. Based on the results, it can either formulate a response or decide on additional actions. You can refer to [Building Autonomous AI Agents with LangGraph: A Developer's Guide](https://www.amazon.com/Building-Autonomous-Agents-LangGraph-Developers/dp/B0DVR7LL3G) and [How to create AI Agents with LangGraph? Step - by - step guide](https://profil-software.com/blog/machine-learning/the-revolutionary-world-of-ai-agents-why-how-to-build-them-leveraging-langgraph/) for more information.

重放完整状态历史

现在你已经向聊天机器人添加了步骤,你可以 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:
# We are somewhat arbitrarily selecting a specific state based on the number of chat messages in the state.
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 节点。

print(to_replay.next)
print(to_replay.config)

返回结果:

('tools',)
{'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1f045d9c-2d47-63c8-8006-4b85a770d5d2'}}

从某一时刻加载状态

检查点的 to_replay.config 中包含一个 checkpoint_id 时间戳。提供这个 checkpoint_id 值会告诉 LangGraph 的检查点系统 加载 该时间点的状态。

# The `checkpoint_id` in the `to_replay.config` corresponds to a state we've persisted to our checkpointer.
for event in graph.stream(None, to_replay.config, stream_mode="values"):
if "messages" in event:
event["messages"][-1].pretty_print()

返回结果:

================================== Ai Message ==================================

Building an autonomous agent with LangGraph is an exciting endeavor! To learn more about the process of building an autonomous agent using LangGraph, I'll search for relevant information.
Tool Calls:
tavily_search (call_omts787jviabpafisk9j2yil)
Call ID: call_omts787jviabpafisk9j2yil
Args:
query: Steps and best practices for building an autonomous agent with LangGraph
search_depth: advanced
================================= Tool Message =================================
Name: tavily_search {"query": "Steps and best practices for building an autonomous agent with LangGraph", "follow_up_questions": null, "answer": null, "images": [], "results": [{"url": "https://www.amazon.com/Building-Autonomous-Agents-LangGraph-Developers/dp/B0DVR7LL3G", "title": "Building Autonomous AI Agents with LangGraph: A Developer's Guide", "content": "This guide stands out among LangGraph books by offering the complete LangGraph blueprint you need to master every aspect of managing autonomous systems. Learn how to create AI agent LangGraph designs that not only simplify the development process but also empower you to build sophisticated, self-operating systems. Our step-by-step tutorials cover everything—from basic graph theory to mastering LangGraph, ensuring you gain the confidence to tackle complex projects with ease. [...] Building Autonomous AI Agents with LangGraph: A Developer’s Guide is the ultimate resource for developers who want to harness the power of modern graph-based AI. This comprehensive guide demystifies LangGraph and provides a complete LangGraph blueprint for designing, building, and optimizing autonomous AI agents. Whether you’re a seasoned coder or just starting out, this book is packed with practical insights, detailed LangGraph code examples, and hands-on projects that will take your skills to [...] With clear explanations, robust code examples, and expert advice on LangGraph managing AI agents systems using best practices, this book is your go-to resource for mastering LangGraph and building cutting-edge solutions. Explore topics that cover LangGraph and AI agents, as well as the innovative integration of Langchain Langraph—all presented in a style that’s both engaging and accessible.", "score": 0.78846955, "raw_content": null}, {"url": "https://profil-software.com/blog/machine-learning/the-revolutionary-world-of-ai-agents-why-how-to-build-them-leveraging-langgraph/", "title": "How to create AI Agents with LangGraph? Step-by-step guide", "content": "The control flow of an agent typically follows a sequence of steps. First, the agent receives a query or instruction from a user. Next, it uses its language model to reason about what actions would be appropriate to fulfill the request. Then, it selects and calls the relevant tools with specific parameters. Finally, it processes the results of those tool calls to either formulate a response or determine additional actions to take.", "score": 0.7515939, "raw_content": null}], "response_time": 1.03}
================================== Ai Message ================================== Although the exact step - by - step process with in - depth details for building an autonomous agent with LangGraph isn't fully presented in the search results, here's a general understanding and related information: ### General Agent Control Flow (Relevant for LangGraph - based Agents)
1. **Query Receipt**: The agent first takes in a query or instruction from the user. This is the starting point where the agent becomes aware of the task it needs to perform.
2. **Reasoning**: Using its underlying language model, the agent reasons about what actions would be appropriate to fulfill the received request. This involves analyzing the query, understanding its context, and mapping it to potential actions.
3. **Tool Selection and Call**: After reasoning, the agent selects the relevant tools and calls them with specific parameters. These tools could be functions, APIs, or other components that help in achieving the task.
4. **Result Processing**: The agent processes the results of the tool calls. It can either use these results to formulate a response back to the user or determine if additional actions are needed to fully complete the task. ### Further Resources
- **Building Autonomous AI Agents with LangGraph: A Developer's Guide**: This book is described as a comprehensive resource. It offers a complete LangGraph blueprint for designing, building, and optimizing autonomous AI agents. It covers from basic graph theory to mastering LangGraph and provides practical insights, detailed code examples, and hands - on projects. You can find more about it [here](https://www.amazon.com/Building-Autonomous-Agents-LangGraph-Developers/dp/B0DVR7LL3G). You might want to refer to this book or other in - depth developer resources to get a more detailed and structured approach for building your autonomous agent with LangGraph.

注意,图从 action 节点恢复执行。您可以看出这是事实,因为上面打印的第一个值是我们的搜索引擎工具的响应。

恭喜!你现在已经在LangGraph中使用了时光旅行检查点遍历功能。能够回溯并探索替代路径为调试、实验和交互式应用程序打开了一个充满可能性的世界。

LangGraph官方文档笔记——6.时间旅行的更多相关文章

  1. docker官方文档笔记

    Docker在 CentOS7.X上运行.Docker可能在其他EL7的兼容版本中成功安装,但是官方并未进行测试,因此也不提供任何支持. 系统环境要求 docker必须运行在64-bit的系统上,对于 ...

  2. Vue官方文档笔记(二)

    23.$refs是什么东东? 通过在标签上设置ref属性,然后在Vue实例方法中可以通过$refs拿到这些标签,如: <input ref="input"> metho ...

  3. React官方文档笔记之快速入门

    快速开始 JSFiddle 我们建议在 React 中使用 CommonJS 模块系统,比如 browserify 或 webpack. 要用 webpack 安装 React DOM 和构建你的包: ...

  4. Vue官方文档笔记

    1.如何创建一个Vue实例对象? var vm = new Vue({ el: "#app", //标签id 或 标签类名 data:{ //双向绑定的数据 message: &q ...

  5. Spring 官方文档笔记---Bean

    In Spring, the objects that form the backbone of your application and that are managed by the Spring ...

  6. Swift -- 官方文档Swift-Guides的学习笔记

    在经历的一段时间的郁闷之后,我发现感情都是虚伪的,只有代码是真实的(呸) 因为看了swift语法之后依然不会用swift,然后我非常作死的跑去看官方文档,就是xcode里自带的help>docu ...

  7. pm2 官方文档 学习笔记

    一.安装 1.安装 npm install pm2 -g 2.更新 npm install pm2 -g && pm2 update pm2 update 是为了刷新 PM2 的守护进 ...

  8. vue.js 2.0 官方文档学习笔记 —— 01. vue 介绍

    这是我的vue.js 2.0的学习笔记,采取了将官方文档中的代码集中到一个文件的形式.目的是保存下来,方便自己查阅. !官方文档:https://cn.vuejs.org/v2/guide/ 01. ...

  9. Effective Go(官方文档)笔记

    Effective Go(官方文档)笔记 自己主动局部变量提升(编译期完毕?):return &...; 内置函数: new/make copy, append delete range(这是 ...

  10. TypeScript 学习笔记 — 看官方文档

    TYPESCRITP OF GEEK NOTE 以后会更新这个完整度,和理解度,目前这个还不够 ts官方推荐使用let来替代 var ts 支持 js语法 声明变量 let temp:string = ...

随机推荐

  1. 【2020.11.17提高组模拟】数数(cuvelia) 题解

    [2020.11.17提高组模拟]数数(cuvelia) 题解 题目描述 给你一个长度为n的序列\(a_1...a_n\).对于所有的\(k\in [1,n]\)选择序列中的\(k\)个数(下标为\( ...

  2. [python] python抽象基类使用总结

    在Python中,抽象基类是一类特殊的类,它不能被实例化,主要用于作为基类被其他子类继承.抽象基类的核心作用是为一组相关的子类提供统一的蓝图或接口规范,明确规定子类必须实现的方法,从而增强代码的规范性 ...

  3. 2. LangChain4j-AIServices,原来调用AI这么简单?

    1. 简介 上一章节我们讲了如何使用LangChain4J的底层组件来进行AI的交互,如 ChatLanguageModel.ChatMessage.ChatMemory 等. 在这个层面上工作非常灵 ...

  4. Tauri2.0-DeepSeek电脑端Ai对话|tauri2+vite6+deepseek流式ai聊天系统

    重磅新作tauri2.0+vue3.5+deepseek+arco桌面客户端ai流式输出聊天对话系统. tauri2-vue3-deepseek:桌面端ai聊天对话,基于Tauri2.x+Vite6集 ...

  5. GitHub MCP Server - 无缝集成GitHub API的自动化工具

    GitHub MCP Server GitHub MCP Server是一个Model Context Protocol(MCP)服务器,提供与GitHub API的无缝集成,使开发者和工具能够实现高 ...

  6. 《机器人SLAM导航核心技术与实战》第1季:第12章_典型自主导航系统

    <机器人SLAM导航核心技术与实战>第1季:第12章_典型自主导航系统 视频讲解 [第1季]12.第12章_典型自主导航系统-视频讲解 [第1季]12.1.第12章_典型自主导航系统_ro ...

  7. 东方财富服务端开发暑期实习面试,已拿offer!!

    这是一位球友投稿的东方财富服务端开发暑期实习面经,问的内容还是比较多的,难度也相对比较大.下面是正文. 最近参与了东方财富服务端开发暑期实习的招聘,并最终收获了 Offer.整个过程持续了大约一周,从 ...

  8. 2023年成都.NET线下技术沙龙即将到来!

    MASA技术团队联合成都.NET俱乐部,将在成都市举办一场.NET线下技术沙龙,为.NET开发者创造一次交流学习的契机,我们邀请到的几位技术大咖,将会围绕各自的主题向大家分享他们的技术心得. 本场沙龙 ...

  9. C# WinForm 查询时设置DataGridView 的颜色

    用:CellPainting 事件去修改颜色不会那么卡 private void dataGridView1_CellPainting(object sender, DataGridViewCellP ...

  10. node安装与使用

    nvm for mac/linx 安装 使用yum安装node,最新只能安装到0.12.X 版本,而自定义安装二进制的又有点麻烦,所以用nvm安装 (如果命令下载不下来 可以手动下载到服务器上执行). ...