1. 构建状态图
from typing import Annotated
from typing_extensions import TypedDict
from langchain_tavily import TavilySearch
from langchain.chat_models import init_chat_model
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode, tools_condition
from langgraph.checkpoint.memory import MemorySaver
class State(TypedDict):
messages: Annotated[list, add_messages]
llm = init_chat_model(
"deepseek:deepseek-chat"
)
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 ==================================
Tool Calls:
tavily_search (call_0_af54c218-cc42-4b20-9a08-2514646b73f3)
Call ID: call_0_af54c218-cc42-4b20-9a08-2514646b73f3
Args:
query: LangGraph
search_depth: advanced
================================= Tool Message =================================
Name: tavily_search
{"query": "LangGraph", "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, 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 (LLMs) in a scalable and efficient manner. At its core, LangGraph uses the power of graph-based architectures to model and manage the intricate relationships between various components of an AI agent workflow. [...] 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\nLLM 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. [...] By using a graph-based architecture, LangGraph enables users to scale artificial intelligence workflows without slowing down or sacrificing efficiency. LangGraph uses enhanced decision-making by modeling complex relationships between nodes, which means it uses AI agents to analyze their past actions and feedback. In the world of LLMs, this process is referred to as reflection.", "score": 0.9353998, "raw_content": null}, {"url": "https://github.com/langchain-ai/langgraph", "title": "langchain-ai/langgraph: Build resilient language agents as graphs.", "content": "LangGraph — used by Replit, Uber, LinkedIn, GitLab and more — is a low-level orchestration framework for building controllable agents. While langchain provides integrations and composable components to streamline LLM application development, the LangGraph library enables agent orchestration — offering customizable architectures, long-term memory, and human-in-the-loop to reliably handle complex tasks.\n\n```\npip install -U langgraph\n```", "score": 0.8884594, "raw_content": null}], "response_time": 1.45}
================================== Ai Message ==================================
Here's what I found about **LangGraph**:
1. **IBM's Overview**:
- LangGraph is an open-source AI agent framework developed by LangChain. It is designed to build, deploy, and manage complex generative AI agent workflows.
- It uses a graph-based architecture to model and manage relationships between components in AI workflows, making it scalable and efficient.
- Applications include agent-based systems (e.g., robotics, autonomous vehicles) and large language model (LLM) applications. For example, Norwegian Cruise Line uses LangGraph to enhance guest-facing AI solutions for personalized experiences.
- Key features include reflection (analyzing past actions and feedback) and enhanced decision-making.
2. **GitHub Repository**:
- LangGraph is described as a low-level orchestration framework for building resilient and controllable agents. It is used by companies like Replit, Uber, LinkedIn, and GitLab.
- It complements LangChain by providing customizable architectures, long-term memory, and human-in-the-loop capabilities for complex tasks.
- Installation is straightforward with `pip install -U langgraph`.
### Resources:
- [IBM's LangGraph Overview](https://www.ibm.com/think/topics/langgraph)
- [LangGraph GitHub Repository](https://github.com/langchain-ai/langgraph)
Would you like more details on any specific aspect of 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()
运行结果(由于返回结果也是Markdown格式,因此去除了某些代码块的符号```):
================================ Human Message =================================
Ya that's helpful, Maybe I'll build an autonomous agent with it!
================================== Ai Message ==================================
That sounds like an exciting project! Building an autonomous agent with **LangGraph** can be a great way to explore its capabilities, especially its graph-based architecture for managing workflows and decision-making. Here’s a quick roadmap to get you started:
---
### **1. Understand the Basics**
- **LangGraph vs. LangChain**: While LangChain provides composable components for LLM applications, LangGraph focuses on **orchestrating agents** with customizable workflows.
- **Graph-Based Architecture**: Agents are modeled as nodes in a graph, and edges define how they interact. This is useful for complex, multi-step tasks.
---
### **2. Set Up Your Environment**
Install LangGraph:
pip install -U langgraph
---
### **3. Define Your Agent's Workflow**
Here’s a simple example to create a basic agent workflow:
from langgraph.graph import Graph
from langgraph.nodes import ToolNode, LLMNode
# Define nodes (tools or LLMs)
def fetch_data(input):
return f"Fetched data: {input}"
def analyze_data(input):
return f"Analyzed: {input}"
# Create nodes
fetch_node = ToolNode(tool=fetch_data)
analyze_node = ToolNode(tool=analyze_data)
# Build the graph
workflow = Graph()
workflow.add_node("fetch", fetch_node)
workflow.add_node("analyze", analyze_node)
workflow.add_edge("fetch", "analyze") # Connect nodes
# Compile and run
app = workflow.compile()
result = app.invoke("query")
print(result)
---
### **4. Add Advanced Features**
- **Memory**: Use LangGraph’s built-in memory to store context or state between agent actions.
- **Human-in-the-Loop**: Integrate user feedback for tasks requiring approval or corrections.
- **Reflection**: Enable the agent to analyze past actions for self-improvement.
---
### **5. Test and Deploy**
- Start with simple tasks (e.g., fetching and summarizing data).
- Gradually add complexity (e.g., multi-agent collaboration).
- Deploy as a microservice or integrate with platforms like FastAPI.
---
### **Resources**
- [LangGraph Documentation](https://github.com/langchain-ai/langgraph)
- [LangChain’s Agent Guide](https://python.langchain.com/docs/modules/agents/) (for foundational concepts)
Would you like help brainstorming specific use cases or debugging your implementation? Let me know how I can assist further! 🚀
3. 重放完整的状态历史
在向聊天机器人添加了步骤后,可以重放完整的状态历史记录以查看发生的所有事情。
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"]) == 2:
to_replay = state
运行结果为:
Num Messages: 6 Next: ()
--------------------------------------------------------------------------------
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__',)
--------------------------------------------------------------------------------
检查点会保存图中每一步的执行情况。这涵盖了所有调用,因此你可以回溯整个线程的历史记录。
4. 从检查点恢复
从to_replay状态恢复,该状态位于第一次图调用中的chatbot机器人节点之后。从此处恢复将调用接下来的操作节点。
print(to_replay.next)
print(to_replay.config)
运行结果为:
('tools',)
{'configurable': {'thread_id': '1', 'checkpoint_ns': '', 'checkpoint_id': '1f0385ca-311c-6fd3-8001-154f972290c5'}}
5. 加载某个时刻的状态
检查点的to_replay.conifg包含一个checkpoint_id时间戳。提供此checkpoint_id值会告诉LangGraph的检查点程序从该时刻加载状态。
for event in graph.stream(None, to_replay.config, stream_mode="values"):
if "messages" in event:
event["messages"][-1].pretty_print()
运行结果:
================================== Ai Message ==================================
Tool Calls:
tavily_search (call_0_af54c218-cc42-4b20-9a08-2514646b73f3)
Call ID: call_0_af54c218-cc42-4b20-9a08-2514646b73f3
Args:
query: LangGraph
search_depth: advanced
================================= Tool Message =================================
Name: tavily_search
{"query": "LangGraph", "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, 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 (LLMs) in a scalable and efficient manner. At its core, LangGraph uses the power of graph-based architectures to model and manage the intricate relationships between various components of an AI agent workflow. [...] 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\nLLM 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. [...] By using a graph-based architecture, LangGraph enables users to scale artificial intelligence workflows without slowing down or sacrificing efficiency. LangGraph uses enhanced decision-making by modeling complex relationships between nodes, which means it uses AI agents to analyze their past actions and feedback. In the world of LLMs, this process is referred to as reflection.", "score": 0.9353998, "raw_content": null}, {"url": "https://github.com/langchain-ai/langgraph", "title": "langchain-ai/langgraph: Build resilient language agents as graphs.", "content": "LangGraph — used by Replit, Uber, LinkedIn, GitLab and more — is a low-level orchestration framework for building controllable agents. While langchain provides integrations and composable components to streamline LLM application development, the LangGraph library enables agent orchestration — offering customizable architectures, long-term memory, and human-in-the-loop to reliably handle complex tasks.\n\n```\npip install -U langgraph\n```", "score": 0.8884594, "raw_content": null}], "response_time": 1.57}
================================== Ai Message ==================================
Here’s what I found about **LangGraph**:
1. **IBM's Overview**:
- LangGraph is an open-source AI agent framework created by LangChain. It is designed to build, deploy, and manage complex generative AI agent workflows.
- It uses graph-based architectures to model relationships between components in AI workflows, making it scalable and efficient.
- Applications include:
- **Agent systems**: Used in robotics, autonomous vehicles, and video games.
- **LLM applications**: Enables developers to create sophisticated AI models that improve over time. For example, Norwegian Cruise Line uses LangGraph for personalized guest experiences.
- LangGraph enhances decision-making by analyzing past actions and feedback, a process known as "reflection" in the context of large language models (LLMs).
[Read more on IBM's page](https://www.ibm.com/think/topics/langgraph)
2. **GitHub Repository**:
- LangGraph is described as a low-level orchestration framework for building controllable agents. It is used by companies like Replit, Uber, LinkedIn, and GitLab.
- It complements LangChain by providing customizable architectures, long-term memory, and human-in-the-loop features for handling complex tasks.
- Installation is straightforward with `pip install -U langgraph`.
[Check out the GitHub repo](https://github.com/langchain-ai/langgraph)
Would you like more details on any specific aspect of LangGraph?
图从action节点恢复执行。上面打印的第一个值是来自搜索引擎工具的响应。
参考
https://langchain-ai.github.io/langgraph/tutorials/get-started/6-time-travel/