当前位置: 首页 > news >正文

Chapter 7:生产级设计:错误处理与可观测性

Chapter 7:生产级设计:错误处理与可观测性

7.1 生产级 Agent 系统要求

与开发环境的本质区别

┌─────────────────────────────────────────────────────────────┐ │ 生产环境挑战 │ ├─────────────────────────────────────────────────────────────┤ │ 1. 网络不稳定 → LLM API 调用可能超时/失败 │ │ 2. 流量峰值 → 需要限流和熔断 │ │ 3. 长时运行 → 需要状态持久化和恢复 │ │ 4. 问题定位 → 无日志无法排查 │ │ 5. 性能监控 → 需要指标和告警 │ │ 6. 合规审计 → 需要完整操作记录 │ └─────────────────────────────────────────────────────────────┘

生产级 checklist

错误处理:-超时控制-重试机制-熔断策略-降级方案-死信处理可观测性:-结构化日志-链路追踪-指标监控-告警机制韧性设计:-幂等性-状态持久化-优雅关闭-限流保护

7.2 错误处理策略

错误分类

错误类型说明处理策略
Transient临时性错误(网络抖动)重试
Permanent永久性错误(参数错误)记录并返回友好错误
Resource资源不足(内存/连接池)排队/降级
Timeout超时重试或降级
RateLimit限流等待后重试

统一错误处理框架

@Service@Slf4jpublicclassAgentErrorHandler{publicAssistantMessagehandleAgentError(AgentExecutionExceptione,ErrorContextcontext){log.error("Agent error: type={}, agent={}, message={}",e.getErrorType(),context.getAgentName(),e.getMessage());switch(e.getErrorType()){caseTRANSIENT:returnhandleTransientError(e,context);caseTIMEOUT:returnhandleTimeoutError(e,context);caseRATE_LIMIT:returnhandleRateLimitError(e,context);caseRESOURCE_EXHAUSTED:returnhandleResourceError(e,context);casePERMANENT:default:returnhandlePermanentError(e,context);}}privateAssistantMessagehandleTransientError(AgentExecutionExceptione,ErrorContextcontext){// 检查重试次数if(context.getRetryCount()<MAX_RETRIES){log.info("Retrying transient error, attempt {}",context.getRetryCount()+1);thrownewRetryableException(e);}// 重试耗尽,降级处理log.warn("Max retries exhausted for transient error");returnfallbackResponse(context);}privateAssistantMessagehandleTimeoutError(AgentExecutionExceptione,ErrorContextcontext){log.error("Agent timeout: agent={}, elapsed={}ms",context.getAgentName(),context.getElapsedTime());returnnewAssistantMessage(""" 处理时间较长,请稍后重试。 如果问题持续存在,请联系技术支持。 """);}privateAssistantMessagehandleRateLimitError(AgentExecutionExceptione,ErrorContextcontext){// 获取重试时间DurationretryAfter=context.getRetryAfter();log.warn("Rate limit hit, retry after {} seconds",retryAfter.getSeconds());thrownewRateLimitException(retryAfter);}privateAssistantMessagehandleResourceError(AgentExecutionExceptione,ErrorContextcontext){log.error("Resource exhausted: {}",e.getMessage());returnnewAssistantMessage(""" 系统繁忙,请稍后再试。 感谢您的耐心等待。 """);}privateAssistantMessagehandlePermanentError(AgentExecutionExceptione,ErrorContextcontext){log.error("Permanent error, no retry: {}",e.getMessage());// 记录完整错误用于排查log.error("Error details",Map.of("agent",context.getAgentName(),"input",context.getInput(),"stack",ExceptionUtils.getStackTrace(e)));returnnewAssistantMessage(""" 处理您的请求时遇到问题。 错误已记录,技术团队将尽快处理。 错误参考码:{},请保存此码以便查询。 """.formatted(context.getErrorCode()));}privateAssistantMessagefallbackResponse(ErrorContextcontext){// 降级方案:根据上下文尝试简化处理if(context.hasSimpleFallback()){log.info("Attempting simple fallback");returncontext.getSimpleFallback().process();}returnnewAssistantMessage(""" 抱歉,暂时无法完成您的请求。 请稍后重试或联系客服。 """);}}

7.3 重试机制

重试策略配置

@ConfigurationpublicclassRetryConfig{@BeanpublicRetryTemplateagentRetryTemplate(){ExponentialBackOffPolicybackOff=newExponentialBackOffPolicy();backOff.setInitialInterval(1000);// 初始 1sbackOff.setMultiplier(2.0);// 指数 2xbackOff.setMaxInterval(30000);// 最大 30sbackOff.setMaxElapsedTime(120000);// 总共最多 2minSimpleRetryPolicyretryPolicy=newSimpleRetryPolicy();retryPolicy.setMaxAttempts(5);RetryTemplatetemplate=newRetryTemplate();template.setBackOffPolicy(backOff);template.setRetryPolicy(retryPolicy);returntemplate;}}

Agent 重试集成

@Service@Slf4jpublicclassRetryableAgentService{privatefinalRetryTemplateretryTemplate;privatefinalAgentErrorHandlererrorHandler;publicAssistantMessageexecuteWithRetry(ReactAgentagent,UserMessagemessage,RetryContextretryContext){returnretryTemplate.execute(context->{try{retryContext.setRetryCount(context.getRetryCount());log.info("Agent execution attempt {}",context.getRetryCount()+1);returnagent.call(message);}catch(Exceptione){log.warn("Agent call failed: {}",e.getMessage());thrownewAgentRetryException(e);}},context->{// 恢复策略log.error("All retries exhausted");returnerrorHandler.handleAgentError(context.getLastException(),buildErrorContext(retryContext));});}}

重试最佳实践

// 重试注意事项publicclassRetryBestPractices{// ✅ 应该重试:临时性错误publicbooleanshouldRetry(Exceptione){returneinstanceofTimeoutException||einstanceofSocketTimeoutException||einstanceofServiceUnavailableException||(e
http://www.jsqmd.com/news/717463/

相关文章:

  • 2026年3月mpp电力管直销厂家推荐,七孔梅花管/双壁波纹管/钢带波纹管/pe管/mpp电力管,mpp电力管厂家哪个好 - 品牌推荐师
  • 手把手教你用STM32F103C8T6的软件IIC驱动MPU6050(附完整代码与调试心得)
  • FastSpeech2代码实现原理:从Transformer到Variance Adaptor的深度解析
  • Linux安装Yi-Coder-1.5B:从源码编译到服务部署
  • 终极cocur/slugify高级配置指南:掌握正则表达式、大小写控制和分隔符定制技巧
  • AIGC工具平台-NovelAI小说自动撰写
  • 代码质量管理工具使用指南
  • 2026年照片抠图换背景操作记录:从一键去底到合成出图的完整方案
  • EAIA生产环境部署:如何设置定时任务和监控系统运行
  • GoCaptcha 性能优化实战:如何在高并发场景下保持验证码生成效率
  • 终极指南:如何用SketchUp STL插件实现完美3D打印转换
  • 别再手动录课表了!用WakeUp App+谷歌日历,5分钟搞定飞书课程表同步(2025亲测)
  • 拆解工厂物料管理四大核心难题:从采购到库存的工厂物料管理全流程优化
  • 终极指南:GreenDao数据库操作在MVP架构中的高效应用技巧
  • Windows虚拟显示器扩展终极指南:免费扩展工作空间的完整解决方案
  • 揭秘mpaland/printf:嵌入式系统的终极线程安全打印库,malloc-free设计如何实现?
  • Codex CLI教程(五) | MCP 之 Context7
  • 2026康宁市集能运营起来吗?是骗局吗:投资风险深度核查分析 - 栗子测评
  • 第2节:从Framework到Harness,Agent需要怎样的底层支撑?
  • Java 项目中的线程池到底该怎么配?
  • 什么是漏洞扫描?有哪些功能?
  • 别再让电机‘抽风’了!用Arduino和A4950实现直流减速电机的精准调速(附PID调参心得)
  • 2026康宁市集怎么样?康宁市集能不能买:社区市集投资前景与购买建议 - 栗子测评
  • 别再傻傻分不清了!STM32的SWD、JTAG和串口下载,到底该用哪个?(附ST-LINK、CH340选购指南)
  • Ruby FFI 性能优化完全攻略:基准测试与调优技巧
  • ComfyUI-Impact-Pack图像增强插件:为什么你的安装总是功能不全?完整解决方案来了
  • 如何快速将代码仓库转换为AI友好格式:gpt-repository-loader的完整指南
  • Geatpy并行化与分布式计算:大规模优化问题的解决方案
  • 秒杀产品支持加入购物车详解:从入门到实战全攻略
  • 什么是网络安全网络安全包括哪几个方面学完能做一名黑客吗?