《AI Agent 开发入门》14.3 幂等与副作用

相同参数不等于同一次业务。给同一客户发送相同正文的第二次合法通知应允许执行;重试同一通知则应复用原操作键。本进程锁串行包住查缓存、执行和存结果,防止同进程并发重复。snapshot/restore 保留已记录结果;函数异常不缓存,失败前是否已经产生副作用必须由业务确认。

14.3 业务操作键与本地幂等缓存

相同参数不等于同一次业务。给同一客户发送相同正文的第二次合法通知应允许执行;重试同一通知则应复用原操作键。

实现选择

operation_id 由可信调用方按业务操作生成,不能只依赖模型的 ToolCall.id。缓存键是工具名与业务键,参数哈希只检测同键异参冲突;冲突直接拒绝。

本进程锁串行包住查缓存、执行和存结果,防止同进程并发重复。snapshot/restore 保留已记录结果;函数异常不缓存,失败前是否已经产生副作用必须由业务确认。

minagent/idempotent.py

# file: minagent/idempotent.py | write
import hashlib,json,threading
from copy import deepcopy

def normalize_args(args):
    return json.dumps(args,sort_keys=True,ensure_ascii=False,separators=(",",":"),allow_nan=False)
def idempotency_key(tool_name,args):
    return hashlib.sha256((tool_name+":"+normalize_args(args)).encode()).hexdigest()

class IdempotentRegistry:
    """Process-local serialized cache; not distributed exactly-once execution."""
    def __init__(self):
        self._results={}; self._write_tools=set(); self._lock=threading.Lock()
    def mark_write(self,name): self._write_tools.add(name)
    def call(self,name,func,args,*,operation_id=None):
        if name not in self._write_tools: return func(**args)
        if not operation_id: raise ValueError("write requires business operation_id")
        key=(name,operation_id); fingerprint=idempotency_key(name,args)
        with self._lock:
            if key in self._results:
                previous,result=self._results[key]
                if previous!=fingerprint: raise ValueError("operation payload conflict")
                return deepcopy(result)
            result=func(**args)
            self._results[key]=(fingerprint,deepcopy(result))
            return result
    def snapshot(self):
        with self._lock:
            return [{"name":name,"operation_id":op,"fingerprint":fp,"result":deepcopy(result)}
                    for (name,op),(fp,result) in self._results.items()]
    def restore(self,rows):
        with self._lock:
            self._results={(row["name"],row["operation_id"]):(row["fingerprint"],deepcopy(row["result"])) for row in rows}

demo_idempotent.py

# file: demo_idempotent.py | write
from minagent.idempotent import IdempotentRegistry
from dataclasses import dataclass
from typing import Any

from minagent.types import ToolCall
side = {"count": 0}
def send_email(to: str, subject: str) -> str:
    side["count"] += 1
    return f'{{"sent": "{to}", "n": {side["count"]}}}'

reg = IdempotentRegistry()
reg.mark_write("send_email")

# 假模型脚本:连续两轮发出同一个写操作
script = [
    [ToolCall("c1", "send_email", {"to": "a@x.com", "subject": "Hi"})],
    [ToolCall("c2", "send_email", {"subject": "Hi", "to": "a@x.com"})],  # 键序不同
    "已通知客户。",
]

for turn, item in enumerate(script):
    if isinstance(item, str):
        print(f"turn {turn}: final -> {item}")
        break
    for tc in item:
        out = reg.call(tc.name, send_email, tc.arguments, operation_id="notice-001")
        print(f"turn {turn}: {tc.id} -> {out}")
print("实际副作用次数:", side["count"])
assert side["count"]==1
restored=IdempotentRegistry();restored.mark_write("send_email");restored.restore(reg.snapshot())
restored.call("send_email",send_email,{"to":"a@x.com","subject":"Hi"},operation_id="notice-001")
assert side["count"]==1

运行与练习

内存缓存不覆盖多进程、多副本和崩溃窗口。副作用完成但缓存未持久化时仍可能重放,生产应使用可原子提交的业务事务、outbox 或外部服务幂等接口。只读工具没有写副作用,但返回值也未必稳定。

下载全卷项目 。在项目根运行本节 demo 文件;练习检查与故障用例见 tests/test_book.py、tests/test_extensions.py 和附录 B。

阅读导航:上一节:14.2 超时、取消与结构化并发 · 下一节:15.1 运行追踪 。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「agent」更多文章

  1. 《AI Agent 高级编程》目录
  2. 《AI Agent 高级编程》11.3 全景回顾:从零到框架的完整路径与展望
  3. 《AI Agent 高级编程》11.2 真实 API 冒烟:假模型 vs 真模型量化差距