LangGraph官方文档笔记——6.时间旅行
在典型的聊天机器人工作流中,用户与机器人交互 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 [...] \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.时间旅行的更多相关文章
- docker官方文档笔记
Docker在 CentOS7.X上运行.Docker可能在其他EL7的兼容版本中成功安装,但是官方并未进行测试,因此也不提供任何支持. 系统环境要求 docker必须运行在64-bit的系统上,对于 ...
- Vue官方文档笔记(二)
23.$refs是什么东东? 通过在标签上设置ref属性,然后在Vue实例方法中可以通过$refs拿到这些标签,如: <input ref="input"> metho ...
- React官方文档笔记之快速入门
快速开始 JSFiddle 我们建议在 React 中使用 CommonJS 模块系统,比如 browserify 或 webpack. 要用 webpack 安装 React DOM 和构建你的包: ...
- Vue官方文档笔记
1.如何创建一个Vue实例对象? var vm = new Vue({ el: "#app", //标签id 或 标签类名 data:{ //双向绑定的数据 message: &q ...
- Spring 官方文档笔记---Bean
In Spring, the objects that form the backbone of your application and that are managed by the Spring ...
- Swift -- 官方文档Swift-Guides的学习笔记
在经历的一段时间的郁闷之后,我发现感情都是虚伪的,只有代码是真实的(呸) 因为看了swift语法之后依然不会用swift,然后我非常作死的跑去看官方文档,就是xcode里自带的help>docu ...
- pm2 官方文档 学习笔记
一.安装 1.安装 npm install pm2 -g 2.更新 npm install pm2 -g && pm2 update pm2 update 是为了刷新 PM2 的守护进 ...
- vue.js 2.0 官方文档学习笔记 —— 01. vue 介绍
这是我的vue.js 2.0的学习笔记,采取了将官方文档中的代码集中到一个文件的形式.目的是保存下来,方便自己查阅. !官方文档:https://cn.vuejs.org/v2/guide/ 01. ...
- Effective Go(官方文档)笔记
Effective Go(官方文档)笔记 自己主动局部变量提升(编译期完毕?):return &...; 内置函数: new/make copy, append delete range(这是 ...
- TypeScript 学习笔记 — 看官方文档
TYPESCRITP OF GEEK NOTE 以后会更新这个完整度,和理解度,目前这个还不够 ts官方推荐使用let来替代 var ts 支持 js语法 声明变量 let temp:string = ...
随机推荐
- python3里面比较两个字符串的不同【difflib】
一.difflib库的用法 a = '/Users/melon/Desktop/odoo14/myaddons/watermark_design/fonts/SimSun.ttf' b = '/Use ...
- mysql的递归写法:部门层级
前言 详细的可以参考:https://cloud.tencent.com/developer/article/2106748 这里用 WITH RECURSIVE 实现递归,需要 MySQL 8.0 ...
- Maui 实践:为控件动态扩展 DragDrop 能力
作者:夏群林 原创 2025.6.9 拖放的实现,和其他的 GestureRecognizer 不同,需要 DragGestureRecognizer 与 DropGestureRecognizer ...
- 微软 AI Agent三剑客:AutoGen、Semantic Kernel与MEAI的协同演进
引言 微软正在积极构建其人工智能(AI)开发者生态系统,旨在为开发者提供从实验研究到生产部署的全方位支持.在这一宏大蓝图中,AutoGen.Semantic Kernel (SK) 和 Microso ...
- 记一次安装ESP32开发环境:ESP-IDF安装配置的排坑之旅
esp官方文档:快速入门 https://docs.espressif.com/projects/esp-idf/zh_CN/stable/get-started/ 按常理来说应该不会出现什么问题啊, ...
- EasyMR:为 AI 未来赋能,打造弹性大数据引擎的革命
如果要评一个2023科技圈的热搜榜,那么以人工智能聊天机器人 ChatGPT 为代表的 AI大模型 绝对会霸榜整个2023. ChatGPT 于2022年11月30日发布.产品发布5日,注册用户数就超 ...
- DTMO直播预告丨ChunJun 2022年开源规划&支持异构数据源DDL转换与自动执行
DTMO DTMO(DTstack Meetup Online)是袋鼠云数栈技术团队2022年的全新开源项目技术分享活动,我们秉承着开源共享的理念,旨在为大家分享大家分享袋鼠云大数据开源项目家族 ...
- HyperWorks批处理网格的类型设置
网格类型设置(Configuration Tab) HyperWorks中BatchMesher 的 Configuration Tab 向用户提供了网格方案类型(Mesh Type)的选择.一个典型 ...
- .NET中全新的MongoDb ORM框架 - SqlSugar
.NET中好用的MongoDb ORM很少,选择也很少,所以我打造了一款适合SQL习惯的MongoDb ORM,让用户多一个选择. 1. MongoDB ORM教程 1.1 NUGET 安装 SqlS ...
- 内网环境下Go module的包管理和包拉取解决方案
前言 很多开发的小伙伴在工作中经常会遇到需要在内网环境下开发生产,因此就必须要解决内网环境下Go语言的包管理和包拉取问题.恰逢我现在公司就需要在内网环境下开发新项目,因此在此记录我们内网环境下Go m ...