12.3 人工中断与一次性批准
HumanGraph 用于本节单后继人工流程,与 WaveGraph 分开。暂停发生在敏感节点前;演示只记录模拟邮件参数,不向外部发送消息。
实现选择
HumanDecision 匹配暂停节点,批准/修改执行节点,拒绝跳过节点。内部 token 一次性消费,错节点或重复恢复被拒绝;跨暂停/恢复也累计步骤上限。
状态与 token 只保存在本进程,示例调用方可信。真实审批需要验证身份、绑定不可篡改的操作参数、持久化一次性批准及恢复记录,不能把普通 dict/token 直接暴露到公网。
minagent/workflow/human.py
# file: minagent/workflow/human.py | write
from dataclasses import dataclass, field
from copy import deepcopy
import uuid
from .graph import Graph
@dataclass
class HumanDecision:
node: str
action: str
payload: dict = field(default_factory=dict)
@dataclass
class RunOutcome:
state: dict
paused_at: str | None = None
pending: dict | None = None
done: bool = False
steps: int = 0
token: str = ""
class HumanGraph(Graph):
def __init__(self):
super().__init__(); self.interrupt_before=set(); self.pending_tokens=set()
def interrupt(self,node): self.interrupt_before.add(node); return self
def run(self,state,on_node=None,max_steps=25):
if self.entry not in self.nodes or max_steps<1: raise ValueError("invalid graph")
self.max_steps=max_steps
return self._run_from(self.entry,deepcopy(state),on_node,0)
def _run_from(self,cur,state,on_node,steps,approved=None):
while cur is not None:
if steps>=self.max_steps: raise RuntimeError("max_steps")
if cur in self.interrupt_before and cur!=approved:
token=uuid.uuid4().hex; self.pending_tokens.add(token)
return RunOutcome(state,cur,{"node":cur,"state":deepcopy(state)},False,steps,token)
approved=None; steps+=1
before=deepcopy(state); state.update(self.nodes[cur].fn(state) or {})
if on_node: on_node(cur,before,deepcopy(state))
cur=self._next(cur,state)
return RunOutcome(state,done=True,steps=steps)
def resume(self,outcome,decision,on_node=None):
if outcome.done or outcome.token not in self.pending_tokens or outcome.paused_at!=decision.node:
raise ValueError("stale/mismatched decision")
if decision.action not in {"approve","reject","modify"}: raise ValueError("invalid action")
self.pending_tokens.remove(outcome.token)
state=deepcopy(outcome.state)
if decision.action=="reject":
state["approved"]=False
return self._run_from(self._next(decision.node,state),state,on_node,outcome.steps)
if decision.action=="modify": state.update(deepcopy(decision.payload))
state["approved"]=True
return self._run_from(decision.node,state,on_node,outcome.steps,decision.node)
demo_human.py
# file: demo_human.py | write
from __future__ import annotations
from minagent.fake import FakeModel
from minagent.types import Message, ToolCall
from minagent.workflow.human import HumanGraph, HumanDecision
TOOL_SCHEMAS = [{
"name": "send_email",
"description": "发送邮件(对外、不可逆)",
"parameters": {"to": "string", "body": "string"},
}]
def build_model():
return FakeModel([
[ToolCall(id="t1", name="send_email",
arguments={"to": "alice@example.com", "body": "退款已处理"})],
"已按你的批准发送退款邮件。",
])
MODEL = build_model()
def decide(state):
resp = MODEL.complete([Message(role="user", content=state["goal"])], TOOL_SCHEMAS)
return {"tool_call": resp.message.tool_calls[0]}
def execute(state):
tc = state["tool_call"]
args = dict(tc.arguments)
args.update(state.get("override", {})) # 人的修改覆盖模型给的参数
return {"sent_args": args, "result": f"{tc.name}(to={args['to']}) 已执行"}
def summarize(state):
if not state.get("result"):
return {"final": "已按你的决定取消发送。"}
resp = MODEL.complete([Message(role="user", content=state["result"])], [])
return {"final": resp.message.content.strip()}
g = (
HumanGraph()
.add_node("decide", decide)
.add_node("execute", execute)
.add_node("summarize", summarize)
.add_edge("decide", "execute")
.add_edge("execute", "summarize")
.set_entry("decide")
.interrupt("execute") # 执行敏感工具前暂停,等人批
)
class ScriptedHuman:
"""脚本化的人:按预设顺序吐出决策,替代真实 stdin。"""
def __init__(self, decisions):
self.decisions = list(decisions)
def decide(self, pending):
print(f" [人] 待决策节点={pending['node']} state keys={sorted(pending['state'])}")
return self.decisions.pop(0)
def show(name, before, after):
print(f"[{name}] 新增 {sorted(set(after) - set(before))}")
def drive(graph, state, human):
out = graph.run(state, on_node=show)
while not out.done:
print(f"⏸ 暂停于 {out.paused_at},等待人工决策")
out = graph.resume(out, human.decide(out.pending), on_node=show)
return out
def run(decision, label):
global MODEL
MODEL = build_model() # 每个场景重建模型,避免脚本串味
print(f"=== {label} ===")
out = drive(g, {"goal": "给 alice 发退款通知"}, ScriptedHuman([decision]))
print("final:", out.state["final"],
"| sent_args:", out.state.get("sent_args"), "\n")
run(HumanDecision(node="execute", action="approve"), "批准")
run(HumanDecision(node="execute", action="reject"), "拒绝")
run(HumanDecision(node="execute", action="modify",
payload={"override": {"to": "bob@example.com"}}), "修改")
运行与练习
运行 demo_human.py 检查批准、拒绝和修改收件人;练习重复使用同一 outcome,应拒绝且不再执行。参考 OrchestrationTests.test_human_reject_wrong_node_and_replay。
下载全卷项目 。在项目根运行本节 demo 文件;练习检查与故障用例见 tests/test_book.py、tests/test_extensions.py 和附录 B。
阅读导航:上一节:12.2 分支、合并与循环 · 下一节:13.1 角色与分工 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。