← Back to learning path

This chapter has not been reviewed in English; the original Simplified Chinese is shown.

Chapter · Published

Agent 重试、幂等与证据:让失败可以恢复 (original language)

用预算、幂等键和最小证据记录控制 Agent 重试,避免重复副作用。

Source: knowledge/p27/ai-agent-engineering/tutorials/agent-retries-idempotency-and-evidence.mdAI agent engineering
Chapter progress 0%Learning path progress 0% · 0/10 chapters completedContinue learning path →

Agent 的重试不是简单地再调用一次模型。工具调用可能已经产生副作用,正确做法是区分可重试错误、永久错误和需要人工接管的状态,并用幂等键保护写操作。

核心概念

每次运行生成 run_id,每次工具调用生成 operation_id。重试前查询幂等记录;只读查询可有限重试,写操作必须返回第一次结果或转人工。证据只记录参数摘要、状态和来源,不保存完整客户正文。

可运行示例

def execute_once(store: dict, operation_id: str, action):
    if operation_id in store:
        return store[operation_id]
    result = action()
    store[operation_id] = result
    return result

store = {}
assert execute_once(store, 'op-1', lambda: {'status': 'created'}) == execute_once(store, 'op-1', lambda: {'status': 'wrong'})

操作步骤

  1. 为可写工具定义幂等键组成规则,确保相同业务操作得到相同 key。
  2. 把工具结果和状态写入持久记录,写入成功后再向模型返回完成。
  3. 按错误类别设置重试次数和退避时间,超出预算则返回 needs_human。
  4. 在后台查看 run_id、operation_id、状态和证据摘要,禁止把密钥或完整输入写入日志。

Use cases

适合工单更新、资料同步和部署建议;删除、付款和权限升级默认需要人工确认。

常见问题

超时后能直接重试写操作吗? 先用幂等键查询上一次结果,无法确认时转人工。

证据要保存多久? 按业务审计和隐私要求设定最小期限。

模型能决定重试次数吗? 不能,预算和错误分类应由服务端控制。

延伸阅读

官方参考

OpenAI Agents 指南;OpenAI Production best practices。

最后核对日期:2026-11-17。涉及版本、接口、模型行为和价格的结论以链接中的官方资料为准;本文不把一次本地运行结果表述为通用性能结论。

Related practical cases

KnowledgeCase study: an evidence package and human handoff after an agent failureKnowledgeCase study: a deployment-advice agent with human approvalKnowledgeCase study: an auditable support-ticket triage agent

Further reading

KnowledgeAI Agents: From Core Concepts to ProductionKnowledgeDesigning Reliable AI Automation Workflows
Product Hub Demo · V0.3