从头开发AI Agent应用系列之三:用LangGraph建工作流
之三:用LangGraph建工作流
本章的目标是:用 LangGraph 搭出 collect → generate → finalize → publish 四阶段状态机,节点先返回桩数据(stub),验证 checkpoint 能持久化到 SQLite 且可恢复。
代码结构
主要增加的内容在APP目录下
backend/
└── pyproject.toml # 加了 3 个依赖 + pytest 配置:
backend/app/
├── db.py # ★ SQLite 数据层: 连接 + 业务表 + CRUD
├── config.py # 加了 mewgo_data_dir 配置
├── main.py # 挂 workflow 路由 + 启动时初始化 DB
├── workflow/ # ★ 工作流核心
│ ├── state.py # WorkflowState (TypedDict) + Stage 枚举
│ ├── graph.py # 四节点 + build_graph + run/resume/get_state
│ └── checkpoint.py # SqliteSaver 单例
├── api/
│ └── workflow.py # ★ POST /start, GET /state, POST /resume
└── ...
backend/tests/
├── conftest.py # ★ pytest fixture (临时 DB 隔离)
└── test_workflow_graph.py # ★ 三个验收用例
带 ★ 的是这次新增的文件。
pyproject.toml增加依赖类
在backend/pyproject.toml —— 加了 3 个依赖 + pytest 配置
"langgraph>=0.2.60", # 状态机引擎
"langgraph-checkpoint-sqlite>=2.0.6", # SqliteSaver(独立包!)
"pytest>=8.0", # 测试框架
[tool.pytest.ini_options] # 新增整段:让 pytest 知道去 tests/ 找用例
testpaths = ["tests"]
pythonpath = ["."]
修改后需要 uv sync 同步一下。
app/config.py中增加一个目录配置
mewgo_data_dir: str = "./data"
app/db.py 数据层
暂时新建了两个表
| 表名 | 说明 |
|---|---|
| workflow_runs | 一次工作流运行的元数据:run_id、project_id、当前阶段、状态(running/paused/completed)、上下文 |
| node_executions | 每个节点执行的留痕:输入、输出、LLM 调用、错误、时间。用于回放和调试 |
CREATE TABLE IF NOT EXISTS workflow_runs (
id TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
current_stage TEXT,
current_node TEXT,
status TEXT NOT NULL,
context TEXT,
checkpoint BLOB,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS node_executions (
id TEXT PRIMARY KEY,
workflow_run_id TEXT NOT NULL,
node_name TEXT NOT NULL,
input TEXT,
output TEXT,
llm_calls TEXT,
agent_steps TEXT,
error TEXT,
started_at TEXT NOT NULL,
finished_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_node_exec_run
ON node_executions(workflow_run_id);
"""
app/workflow/state.py,工作流状态定义
from __future__ import annotations
from enum import Enum
from typing import TypedDict
class Stage(str, Enum):
"""工作流四阶段。用 str 枚举方便 JSON 序列化。"""
COLLECT = "collect" # 资料收集
GENERATE = "generate" # 初稿生成
FINALIZE = "finalize" # 定稿(人工介入)
PUBLISH = "publish" # 多平台发布
class WorkflowState(TypedDict, total=False):
"""LangGraph 全局状态。
total=False: 所有字段可选, 初始 state 可以只带 project_id, 后续节点逐步填充。
每个节点 return 一个 dict, LangGraph 按 key 覆盖合并。
字段对应各阶段的产物:
materials — collect 产出 (资料卡片列表)
outline — generate 的输入大纲
draft — generate 产出 (初稿)
final — finalize 产出 (定稿, 人工确认后写入)
platform_posts— publish 产出 (各平台稿)
"""
project_id: str
current_stage: str # 当前阶段, 便于观察
# collect
materials: list[dict]
# generate
outline: dict
draft: str
# finalize
final: str
# publish
platform_posts: list[dict]
# 横切
errors: list[str]
def initial_state(project_id: str) -> WorkflowState:
"""构造工作流初始状态。"""
return WorkflowState(
project_id=project_id,
current_stage=Stage.COLLECT.value,
materials=[],
outline={},
draft="",
final="",
platform_posts=[],
errors=[],
)
app/workflow/graph.py 四个桩节点
# ---- 桩节点 ----
# 每个节点: 入参是当前 state, 返回一个 partial dict, LangGraph 合并进全局 state。
def collect_node(state: WorkflowState) -> dict:
"""阶段1: 资料收集。桩: 返回固定资料卡片。"""
stub_materials = [
{"id": "mat-1", "title": "示例资料", "source_type": "import",
"summary": "桩数据: collect 节点占位资料。"},
]
return {
"current_stage": Stage.COLLECT.value,
"materials": stub_materials,
}
def generate_node(state: WorkflowState) -> dict:
"""阶段2: 初稿生成。桩: 返回固定初稿文本。"""
stub_draft = (
"# 示例初稿(桩)\n\n"
f"基于 {len(state.get('materials', []))} 条资料生成的占位初稿。"
" 以后会接入真实大纲驱动生成。"
)
return {
"current_stage": Stage.GENERATE.value,
"draft": stub_draft,
}
def finalize_node(state: WorkflowState) -> dict:
"""阶段3: 定稿(人工介入点)。
这里调 interrupt() 暂停整个工作流 —— state 被 checkpoint 落盘,
控制权交回前端, 等用户在编辑器里确认定稿后 resume。
resume 时 interrupt() 返回 resume_value, 节点继续往下走。
"""
resume_value = interrupt({"prompt": "请在编辑器确认定稿"})
# resume_value 是人工注入的结果; 真实场景是定稿内容, 这里桩处理:
final_text = state.get("draft", "")
if isinstance(resume_value, dict) and "final" in resume_value:
final_text = resume_value["final"]
elif isinstance(resume_value, str) and resume_value:
final_text = resume_value
return {
"current_stage": Stage.FINALIZE.value,
"final": final_text or "(空定稿)",
}
def publish_node(state: WorkflowState) -> dict:
"""阶段4: 多平台发布。桩: 返回固定平台稿列表。"""
stub_posts = [
{"platform": "wechat", "status": "stub"},
{"platform": "wordpress", "status": "stub"},
]
return {
"current_stage": Stage.PUBLISH.value,
"platform_posts": stub_posts,
}
上面的 finalize_node 会调用中断函数 interrupt() 等待人工介入。
节点配置后,用build_graph 组装状态机:
# ---- 图构建 ----
def build_graph(checkpointer: BaseCheckpointSaver):
"""构建并编译四阶段状态图。
拓扑: START → collect → generate → finalize → publish → END (线性)。
checkpointer 决定 checkpoint 存哪里(SqliteSaver 存 SQLite)。
"""
g = StateGraph(WorkflowState)
g.add_node("collect", collect_node)
g.add_node("generate", generate_node)
g.add_node("finalize", finalize_node)
g.add_node("publish", publish_node)
g.add_edge(START, "collect")
g.add_edge("collect", "generate")
g.add_edge("generate", "finalize")
g.add_edge("finalize", "publish")
g.add_edge("publish", END)
return g.compile(checkpointer=checkpointer)
def _config(run_id: str) -> dict:
"""LangGraph 的 thread 配置。thread_id = run_id, 同一 run 的所有
invoke / get_state 用同一 thread_id 才能定位到 checkpoint。"""
return {"configurable": {"thread_id": run_id}}
下面则是状态机在运行过程中的关键函数 run_workflow() 和 resume_workflow()。
def run_workflow(project_id: str, run_id: str, checkpointer: BaseCheckpointSaver) -> dict:
"""启动/推进工作流。
从初始状态 invoke。跑到 finalize 节点会因 interrupt 暂停 ——
此时函数返回暂停点的 state snapshot values, 调用方据 status=paused_human
判断需等待人工 resume。
"""
graph = build_graph(checkpointer)
cfg = _config(run_id)
init = initial_state(project_id)
db.update_workflow_run(run_id, status="running", current_stage=Stage.COLLECT.value)
# invoke 到 interrupt 处会返回当前累计的 state values (不抛异常)
# 注意: result 里可能带 __interrupt__ (LangGraph 内部对象, 不可 JSON 序列化),
# 所以存库/返回都用 snap.values (干净的用户状态)。
result = graph.invoke(init, cfg)
snap = graph.get_state(cfg)
clean_values = dict(snap.values)
# 留痕: 每个已执行节点记一条
for node_name, node_input, node_output in _collect_node_io(graph, cfg):
_record_execution(run_id, node_name, node_input, node_output)
# 根据 snapshot 判断是暂停还是完成
if snap.next: # 还有未执行的节点 → 在 interrupt 处暂停
db.update_workflow_run(
run_id,
status="paused_human",
current_stage=Stage.FINALIZE.value,
current_node=snap.next[0] if snap.next else None,
context=clean_values,
)
else:
db.update_workflow_run(
run_id,
status="completed",
current_stage=Stage.PUBLISH.value,
current_node=None,
context=clean_values,
)
return clean_values
def resume_workflow(run_id: str, resume_value: Any,
checkpointer: BaseCheckpointSaver) -> dict:
"""从中断处恢复工作流。
把 resume_value(人工结果)通过 Command 注入, 工作流从 finalize 节点继续。
"""
graph = build_graph(checkpointer)
cfg = _config(run_id)
db.update_workflow_run(run_id, status="running")
result = graph.invoke(Command(resume=resume_value), cfg)
snap = graph.get_state(cfg)
clean_values = dict(snap.values)
if snap.next:
db.update_workflow_run(
run_id, status="paused_human",
current_node=snap.next[0] if snap.next else None,
context=clean_values,
)
else:
db.update_workflow_run(
run_id, status="completed",
current_stage=Stage.PUBLISH.value,
current_node=None,
context=clean_values,
)
return clean_values
上面 snap=graph.get_state(cfg),因为get_state()返回的 StateSnapshot 有个 next 字段,是"接下来要执行的节点名元组"。 如果 next 非空,说明工作流停在某个节点前(比如 interrupt 了);如果 next 为空,说明跑完了。 这是我们判断"暂停还是完成"的依据。
而resume_workflow和run_workflow基本上流程差不多,只是在调用时,传的不是初始状态,而是恢复的状态Command(resume=resume_value)。
app/workflow/checkpoint.py sqlite单例
LangGraph 的 SqliteSaver 把工作流状态(checkpoint)序列化进 SQLite。
它和 db.py 的业务表(workflow_runs / node_executions)共用同一个 .sqlite 文件和同一个连接 —— 这样一份数据库既有 LangGraph 的检查点, 又有我们的元数据。
全进程一个 SqliteSaver + 一个 sqlite 连接,能避免多连接写锁竞争。
from langgraph.checkpoint.sqlite import SqliteSaver
from functools import lru_cache
@lru_cache
def get_checkpointer() -> SqliteSaver:
conn = db.get_conn() # 共用 db.py 的连接
db.init_db(conn) # 建业务表
saver = SqliteSaver(conn)
saver.setup() # 建检查点表 (langgraph 自己的表)
return saver
api/workflow.py API路由
router = APIRouter(prefix="/api/v1", tags=["workflow"])
@router.post("/projects/{project_id}/workflow/start")
def start_workflow(project_id: str):
checkpointer = checkpoint.get_checkpointer()
run_id = db.create_workflow_run(project_id)
state = graph.run_workflow(project_id, run_id, checkpointer)
snap = graph.get_state_snapshot(run_id, checkpointer)
return _build_response(run_id, state, list(snap.next))
@router.get("/projects/{project_id}/workflow/state")
def get_workflow_state(project_id: str, run_id: str): ...
@router.post("/projects/{project_id}/workflow/resume")
def resume_workflow(project_id: str, req: WorkflowResumeRequest): ...
这里使用def 而不是 async_def,这是因为LangGraph中如果用 async def 调同步阻塞函数,会卡住事件循环。用 def,FastAPI 自动把它丢到线程池跑,不阻塞其他请求。 这是 FastAPI 的约定:路由里调同步阻塞代码就用 def,调 async 库才用 async def。
app/main.py中修改配置
加了 lifespan 启动钩子 + app.include_router(workflow.router)。这是把新模块"接进主干"的接线点。
@asynccontextmanager
async def lifespan(app: FastAPI):
"""应用生命周期: 启动时初始化 SQLite + 预热 checkpointer。
get_checkpointer() 首次调用会建表(workflow_runs / node_executions +
LangGraph 检查点表), 这里显式调一次确保启动时就绪。
"""
checkpoint.get_checkpointer()
yield
最后增加一行
app.include_router(workflow.router)
lifespan 是 FastAPI 的生命周期钩子。 yield 前的代码在启动时跑一次,yield 后的在关闭时跑。这里用它预热 checkpointer(建表)。
以上让LangGraph跑起来了。因为并没有界面,下面写测试用例。
test/conftest.py 和 test/test_workflow_graph.py
在conftest.py中写配置,让每个测试用独立的临时 SQLite 文件, 互不污染。
做法: monkeypatch Settings.mewgo_data_dir 指向 tmp_path, 再清掉 checkpointer单例缓存, 这样 get_checkpointer() 会基于新路径重建。
@pytest.fixture
def tmp_data_dir(tmp_path, monkeypatch):
settings = get_settings()
monkeypatch.setattr(settings, "mewgo_data_dir", str(tmp_path))
checkpoint.reset_checkpointer_for_tests() # 清单例缓存
yield tmp_path
checkpoint.reset_checkpointer_for_tests()
在test_workflow_graph.py中写三个测试用例。
用例 1:test_run_completes_all_stages —— 跑通四阶段
run_id = db.create_workflow_run("proj-1")
state = graph.run_workflow("proj-1", run_id, saver) # 跑到 finalize 暂停
snap = graph.get_state_snapshot(run_id, saver)
assert snap.next and "finalize" in snap.next # 停在 finalize
assert state["materials"] # collect 产出了
assert state["draft"] # generate 产出了
final_state = graph.resume_workflow(run_id, "人工定稿", saver) # 恢复
assert final_state["current_stage"] == "publish" # 跑到 publish
assert final_state["final"] == "人工定稿" # resume_value 注入成功
assert db.get_workflow_run(run_id)["status"] == "completed"
用例 2:test_checkpoint_persists —— kill 后恢复
# 第一次"进程"
saver1 = _new_saver(db_path)
run_id = db.create_workflow_run("proj-2")
graph.run_workflow("proj-2", run_id, saver1) # 跑到暂停
# 模拟进程死亡: 删掉所有内存对象
del saver1
gc.collect()
# 第二次"进程": 全新 saver, 同一个 sqlite 文件
saver2 = _new_saver(db_path)
snap2 = graph.get_state_snapshot(run_id, saver2)
assert snap2.next and "finalize" in snap2.next # ★ 能读回暂停状态!
assert snap2.values.get("draft") # ★ generate 的产物还在!
# 能从断点 resume
final_state = graph.resume_workflow(run_id, "断点恢复定稿", saver2)
assert final_state["current_stage"] == "publish" # 跑完了
这个测试验证了什么? 真实场景:用户跑到一半,sidecar 崩了 / 应用关了。 Rust 主进程重启 sidecar,新进程重新连 sqlite,读回 checkpoint,接着跑。 测试里 del saver1 + 新建 saver2 模拟的就是"进程死亡再重生"。能读回暂停状态 + 能 resume = 可恢复性验证通过。
用例 3:test_interrupt_and_resume —— interrupt 语义
g = graph.build_graph(saver)
cfg = {"configurable": {"thread_id": "run-test"}}
g.invoke(graph.initial_state("proj-3"), cfg) # 跑到 finalize 暂停
snap = g.get_state(cfg)
assert snap.next == ("finalize",) # 精确停在 finalize
assert snap.values.get("draft") # generate 已执行
assert not snap.values.get("final") # finalize 未完成, final 为空
g.invoke(Command(resume="人工确认定稿"), cfg) # resume
snap2 = g.get_state(cfg)
assert not snap2.next # 跑完了, next 为空
assert snap2.values["final"] == "人工确认定稿" # resume_value 注入成功
assert snap2.values["current_stage"] == "publish"
手动验证
因为上面只有逻辑代码,没有办法可视化地验证。但我们可以从中间数据来跟踪工作流的实现情况。
先在终端开启服务:
cd backend
uv sync
uv run uvicorn app.main:app --port 8000
然后在另一个终端(因为是在Windows平台,可用PowerShell)
Invoke-RestMethod -Uri "http://localhost:8000/api/v1/projects/test-1/workflow/start" -Method POST

能看到run_id是ddd2cde7-f6a8-48f8-bd16-5cc6c1ffa939
Invoke-RestMethod -Uri "http://localhost:8000/api/v1/projects/test-1/workflow/state?run_id=ddd2cde7-f6a8-48f8-bd16-5cc6c1ffa939"

最后一个是
Invoke-RestMethod -Uri "http://localhost:8000/api/v1/projects/test-1/workflow/resume" -Method POST -ContentType "application/json" -Body '{"run_id":"ddd2cde7-f6a8-48f8-bd16-5cc6c1ffa939","resume_value":"定稿内容"}'

这里涉及到另一个细节,正常的命令应该是
curl -X POST http://localhost:8000/api/v1/projects/test-1/workflow/start
curl "http://localhost:8000/api/v1/projects/test-1/workflow/state?run_id=<上面返回的run_id>"
curl -X POST http://localhost:8000/api/v1/projects/test-1/workflow/resume \
-H "Content-Type: application/json" \
--data-binary '{"run_id":"ddd2cde7-f6a8-48f8-bd16-5cc6c1ffa939","resume_value":"定稿内容"}'
但PowerShell并不支持原生的curl,所以用Invoke-RestMethod代替。
而且,这时会出现文件:backend/data/mewgo.sqlite
可以用Navicat查看这个sqlite库的情况:

致此,工作流的骨架已经建立。LangGraph的状态机能够跑通。可启动,可暂定,也可恢复。状态能保存在SQLite中。
下一章,我们将继续工作流的操作,并让工作流状态可视化。因为源代码量比较大,以后将只贴关键代码或伪代码。保证对代码的理解即可。
