LangGraph官方文档笔记(6)——时间旅行

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

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

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

官方文档参考:时间旅行

创建聊天机器人

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

python 复制代码
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)

添加步骤

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

csharp 复制代码
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()

返回结果:

swift 复制代码
================================ 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).

继续添加步骤:

csharp 复制代码
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()

返回结果:

vbnet 复制代码
================================ 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 完整的状态历史,以查看所有发生的情况。

python 复制代码
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

返回结果:

markdown 复制代码
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 节点。

lua 复制代码
print(to_replay.next)
print(to_replay.config)

返回结果:

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

从某一时刻加载状态

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

vbnet 复制代码
# 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()

返回结果:

vbnet 复制代码
================================== 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中使用了时光旅行检查点遍历功能。能够回溯并探索替代路径为调试、实验和交互式应用程序打开了一个充满可能性的世界。

原文地址:https://www.cnblogs.com/LiShengTrip/p/18925018

相关推荐
程序员鱼皮21 分钟前
Cursor 网页版来了,这下拉屎时也能工作了
计算机·ai·程序员·开发·项目·编程经验
redreamSo3 小时前
AI Daily | AI日报:Nature:超14%生物医学论文或由AI代写; Grok 4测试成绩优异,数据真实性引争议; 李飞飞:攻克空间智能,为AGI补拼图
程序员·aigc·资讯
老周聊大模型4 小时前
《ChatGLM/Llama调优实战:从指令微调到RLHF的工业级对齐方案》
人工智能·程序员·架构
ResponsibilityAmbiti4 小时前
AI 发展 && MCP
人工智能·llm·aigc
马可奥勒留19 小时前
睡前幻想——基于透明化黄金锚定的超主权货币体系设计:一种解决政府货币滥用的奥地利学派方案(3)
程序员
CoderLiu20 小时前
用这个MCP,只给大模型一个figma链接就能直接导出图片,还能自动压缩上传?
前端·llm·mcp
程序员的小马甲1 天前
如何编写AI提示词
人工智能·程序员·产品经理
是小王同学啊~1 天前
(LangChain)RAG系统链路向量检索器之Retrievers(五)
python·算法·langchain