LangGraph也是LangChain开发团队开发的。可以独立于LangChain使用
和LangChain的不同在于
- 使用图结构来构建工作流,流程更灵活,功能更强大
LangGraph 核心构建块
- Node 节点(处理任务的函数)
- State 状态(数据)
- Edge 边(节点的链接)
环境准备
- python
- 虚拟环境创建与激活
python -m venv .venv
# windows
.venv\Script\active
- 安装依赖
pip install requests
pip install langgraph
一个简单的入门案例
构建的流程图如下
步骤
- 定义一个简单的状态
- 定义两个节点
- 定义图的结构
- 编译图
- 设置输入,运行图流程
- 展示图的结构
"""
langgraph core concept
node 节点
edge 边
state 状态
"""
from typing_extensions import TypedDict
# 1 定义状态
class HelloWorldState(TypedDict):
greeting: str
# 2 定义节点函数
def hello_world_node(state: HelloWorldState):
print("执行节点 hello_world_node")
state["greeting"] = "hello world, " + state["greeting"]
return state
def exclamation_node(state: HelloWorldState):
print("执行节点 exclamation_node")
state["greeting"] += "!"
return state
# 3 定义图结构
# START -> greet -> exclaim ->END
from langgraph.graph import StateGraph, START, END
builder = StateGraph(HelloWorldState)
builder.add_node("greet", hello_world_node)
builder.add_node("exclaim", exclamation_node)
builder.add_edge(START, "greet")
builder.add_edge("greet", "exclaim")
builder.add_edge("exclaim", END)
# 4 编译图
graph = builder.compile()
# 5 运行图
result = graph.invoke({"greeting": "from langGraph"})
print("result", result)
# 6 可视化
from langchain_core.runnables.graph import MermaidDrawMethod
import random
import os
import sys
import subprocess
mermaid_png = graph.get_graph(xray=1).draw_mermaid_png(
draw_method=MermaidDrawMethod.API
)
# 写入文件并打开
output_folder = "."
os.makedirs(output_folder, exist_ok=True)
filename = os.path.join(output_folder, f"graph_{random.randint(1,9999)}.png")
with open(filename, "wb") as f:
f.write(mermaid_png)
if sys.platform.startswith("darwin"):
subprocess.call("open", filename)
elif sys.platform.startswith("linux"):
subprocess.call("xdg-open", filename)
elif sys.platform.startswith("win"):
os.startfile(filename)
书籍参考 《The Complete LangGraph Blueprint Build 50+ AI Agents for Business Success (Karanja Maina, James) (Z-Library)》