使用 agent-sre 交互式探索 AI Agent 的 SLO 与错误预算:Notebook 实战指南
发布时间:2026/9/18 13:42:24 作者:尧图编辑部 阅读量:1,286

使用 agent-sre 交互式探索 AI Agent 的 SLO 与错误预算Notebook 实战指南【免费下载链接】agent-governance-toolkitAI Agent Governance Toolkit — Policy enforcement, zero-trust identity, execution sandboxing, and reliability engineering for autonomous AI agents. Covers 10/10 OWASP Agentic Top 10.项目地址: https://gitcode.com/GitHub_Trending/ag/agent-governance-toolkit本指南以 agent-governance-toolkit 仓库中 agent-sre 模块的 notebooks/README.md 及其配套 slo-exploration.ipynb 为核心骨架讲解如何用 Jupyter Notebook 为 AI Agent 系统定义 SLOService Level Objective、模拟 200 次 agent 调用、计算 SLI、追踪错误预算error budget与燃烧速率burn rate并完成告警阈值检查与 what-if 场景分析。读完本文你将掌握 agent-sre 中 SLI/SLO/ErrorBudget 的完整编程模型以及一套可复制到生产环境的定义指标 → 记录事件 → 评估状态 → 触发告警闭环工作流。一、Notebook 概览为什么用交互式方式学习 SLOagent-sreAgent SRE是 agent-governance-toolkit 面向 AI Agent 可靠性工程的 Python 模块其 SLO 子系统把经典 SRE 方法论迁移到 agent 场景用 SLI 度量agent 表现如何用 SLO 定义什么叫可靠用错误预算回答还能容忍多少次失败。notebooks/README.md 目前提供一枚交互式 NotebookNotebookDescriptionslo-exploration.ipynb定义 SLO、模拟 agent 流量、可视化错误预算与燃烧速率该 Notebook 的完整实验流程共六步定义 SLO延迟/准确率/成本三种 SLI→ 模拟 200 次 agent 调用 → 计算 SLI 值与合规度 → 检查错误预算 → 可视化合规性、燃烧速率与延迟分布 → 检查告警阈值 → 运行 what-if 分析。每一步都配有可独立运行的单元格适合作为新手上手 agent-sre 的交互式训练场。二、环境准备与启动方式原文档列出的前置条件如下结合仓库当前状态有两点校准说明Python 版本原文档要求 Python ≥ 3.10但仓库 agent-governance-python/agent-sre/pyproject.toml 中requires-python 3.11建议按 ≥ 3.11 准备环境。安装方式原文档给出pip install agent-sre与pip install -e .两种方式。需要说明的是当前仓库中agent_sre包的 5.0.0 发布 wheel 已声明为弃用存根deprecation stub仅重定向到agent-governance-toolkit-cli5.0.0,6.0仓库内的src/agent_sre源码树仍作为事实标准被 CI 通过pip install -e .[dev]使用。因此从仓库根目录执行可编辑安装是稳妥做法pip install -e . # 在 agent-sre 目录内等价于 -e .[dev] 的核心安装 pip install matplotlib jupyter # 可视化与 Notebook 运行依赖 jupyter notebook notebooks/ # 启动 Notebook 服务打开 slo-exploration.ipynb启动后依次运行各单元格即可复现下述全部实验。三、第 1 步定义 SLO——三种 SLI 与 5% 错误预算Notebook 的第一段代码为代码评审 Agent定义了三种 SLI并组合进一个带错误预算的 SLOIndicatorTargetWindowDescriptionResponse Latency (p95)≤ 3 000 ms1 h95 分位延迟Tool-Call Accuracy≥ 99 %24 h工具选择正确率Cost per Task≤ $0.5024 h单任务平均美元成本import random import math import matplotlib.pyplot as plt from agent_sre import SLO, ErrorBudget from agent_sre.slo.indicators import ( CostPerTask, ResponseLatency, TaskSuccessRate, ToolCallAccuracy, ) from agent_sre.slo.objectives import ExhaustionAction, SLOStatus from agent_sre.slo.dashboard import SLODashboard random.seed(42) # --- SLI definitions --- latency_sli ResponseLatency(target_ms3000.0, percentile0.95, window1h) accuracy_sli ToolCallAccuracy(target0.99, window24h) cost_sli CostPerTask(target_usd0.50, window24h) # --- Error budget (5 %) --- budget ErrorBudget( total0.05, burn_rate_alert2.0, # 2× 正常燃烧 → 警告 burn_rate_critical10.0, # 10× 正常燃烧 → 严重 exhaustion_actionExhaustionAction.FREEZE_DEPLOYMENTS, ) # --- SLO --- slo SLO( namecode-review-agent, descriptionReliability targets for an AI code-review agent, indicators[latency_sli, accuracy_sli, cost_sli], error_budgetbudget, agent_idcode-review-agent, ) print(slo)源码层面的参数语义从源码看这三种 SLI 都在 src/agent_sre/slo/indicators.py 中实现继承自抽象基类SLI见 indicators.py时间窗口TimeWindow枚举indicators.py定义了1h / 6h / 24h / 7d / 30d五种标准窗口分别对应 3600、21600、86400、604800、2592000 秒current_value()只统计窗口内的测量值实现滑动窗口聚合。ResponseLatencyindicators.pypercentile0.95时current_value()返回窗口内延迟排序后的 p95 值其compliance()继承自基类——窗口内value target的测量占比注意延迟是上限型指标源码中SLIValue.is_good默认按value target判断延迟场景需要结合记录时的target元数据理解。ToolCallAccuracyindicators.py通过record_call(correct: bool)累积计数返回运行中的正确率。CostPerTaskindicators.py通过record_cost(cost_usd)累积总成本并返回平均单任务成本。ErrorBudget与SLO类定义在 src/agent_sre/slo/objectives.pyExhaustionActionobjectives.py提供四种耗尽动作ALERT通知、FREEZE_DEPLOYMENTS冻结部署、CIRCUIT_BREAK打开熔断器、THROTTLE限流降级。ErrorBudgetobjectives.py的关键属性total总预算比例、consumed已消耗、remaining_percent剩余百分比、is_exhausted是否耗尽、burn_rate(window_seconds)窗口内燃烧速率。其事件缓冲为deque(maxlenmax_events)默认max_events100_000防止长运行 SLO 内存无界增长。SLOobjectives.py若未显式传error_budget会用最严格指标的 target 自动推导total 1.0 - min(target)record_event(goodbool)在记录事件的同时触发一次evaluate()。四、第 2 步模拟 200 次 Agent 调用为了观察错误预算被消耗的过程Notebook 故意把成功率设置在目标值之下92% 任务成功 95% 预算、98.5% 工具准确率 99% 目标NUM_CALLS 200 latencies, accuracies_running, costs [], [], [] good_events, budget_remaining [], [] for i in range(NUM_CALLS): task_ok random.random() 0.92 # 92 % success (below 95 % budget) tool_ok random.random() 0.985 # 98.5 % accuracy (below 99 % target) latency_ms max(100, random.gauss(2400, 700)) cost_usd max(0.01, random.gauss(0.35, 0.15)) accuracy_sli.record_call(tool_ok) latency_sli.record_latency(latency_ms) cost_sli.record_cost(cost_usd) is_good task_ok and tool_ok slo.record_event(goodis_good) latencies.append(latency_ms) accuracies_running.append(accuracy_sli.current_value()) costs.append(cost_usd) good_events.append(is_good) budget_remaining.append(slo.error_budget.remaining_percent) print(fSimulated {NUM_CALLS} agent calls) print(f Good events: {sum(good_events)} / {NUM_CALLS}) print(f Bad events: {NUM_CALLS - sum(good_events)} / {NUM_CALLS})这段代码演示了 agent-sre 的两类记录通道SLI 通道record_call/record_latency/record_cost分别把单次测量写入各自 SLI 的测量存储供后续current_value()与compliance()聚合。预算通道slo.record_event(good...)把本次调用是否达标记入ErrorBudget的有界事件缓冲record_event内部还会调用evaluate()更新 SLO 状态见 objectives.py。random.seed(42)保证结果可复现这也是 Notebook 教学场景的关键设计同一份随机数据既用于基线也用于后续 what-if 重放。五、第 34 步计算 SLI 与错误预算报告读取指标值与合规度print(Indicator Summary) for ind in slo.indicators: val ind.current_value() comp ind.compliance() if val is not None and comp is not None: met ✅ if comp 0.95 else ❌ print(f {met} {ind.name}) print(f Value: {val:.4f}) print(f Target: {ind.target}) print(f Compliance: {comp:.1%})compliance()的语义见 indicators.py窗口内满足目标的测量数占比。Notebook 用0.95作为单指标合规度达标线与 5% 错误预算口径一致。评估 SLO 状态与错误预算status slo.evaluate() print(f SLO Status: {status.value}) print(f Budget Total: {slo.error_budget.total:.2%}) print(f Budget Consumed: {slo.error_budget.consumed}) print(f Budget Remaining: {slo.error_budget.remaining_percent:.1f}%) print(f Exhausted? {slo.error_budget.is_exhausted}) print(f Burn Rate (1 h): {slo.error_budget.burn_rate(3600):.1f}×) if status SLOStatus.EXHAUSTED: print( Budget exhausted — action: f{slo.error_budget.exhaustion_action.value}) elif status in (SLOStatus.CRITICAL, SLOStatus.WARNING): print( ⚠️ SLO at risk — consider slowing deployments) else: print( ✅ Budget healthy — keep shipping)SLOStatusobjectives.py共有五档HEALTHY / WARNING / CRITICAL / EXHAUSTED / UNKNOWN。evaluate()的状态判定优先级objectives.py为预算耗尽 →EXHAUSTED有 critical 级告警 →CRITICAL有 warning 级告警 →WARNING无任何指标数据 →UNKNOWN否则HEALTHY。燃烧速率的计算objectives.pyburn_rate (窗口内实际错误率) / (允许错误率 total / window_seconds)burn_rate 1.0表示按计划速率消耗预算 1.0表示消耗快于预期例如 2× 意味着预算将在窗口期的 1/2 时间内耗尽。六、第 5 步可视化——错误预算、延迟分布、准确率与燃烧Notebook 用matplotlib绘制 2×2 四联图fig, axes plt.subplots(2, 2, figsize(14, 10))6a 错误预算剩余曲线横轴为 Agent Call #纵轴为剩余百分比红线虚线标记y0预算耗尽线直观看到预算随坏事件单调下降。6b 延迟分布直方图30 个 bin 的直方图上叠加两条竖线——红色虚线为 3000 ms 目标线橙色虚线为实际 p95 值一眼判断 p95 是否越线。6c 运行中的工具准确率绿色曲线为累计准确率红色虚线为 99% 目标线set_ylim(0.9, 1.01)放大差异区间。6d 累计坏事件曲线crimson 色折线统计累计未达标事件数直接对应错误预算的消耗轨迹。这四张图与 docs/slo-reference.md 中SLO-Driven Workflows的运营节奏呼应周度看燃烧速率趋势、月度看预算消耗、季度回顾 SLO 定义。若需要将这种可视化固化为运维面板仓库还提供 dashboards/grafana/agent-slo-dashboard.json 等 Grafana 模板以及SLODashboardsrc/agent_sre/slo/dashboard.py——它支持register_slo()注册、take_snapshot()定时快照、health_summary()汇总健康度Notebook 中的手工循环恰好是它的交互式雏形。七、第 6 步告警阈值检查错误预算被快速消耗时需要尽早发现Notebook 的告警配置如下AlertThresholdSeverityFast burn2× normal rate⚠️ WarningCritical burn10× normal rate Criticalcurrent_burn slo.error_budget.burn_rate(3600) print(f Current burn rate (1 h): {current_burn:.1f}×) for alert in slo.error_budget.alerts(): firing alert.is_firing(current_burn) print(f { FIRING if firing else ok} {alert.name} f(threshold: {alert.rate:.0f}×, severity: {alert.severity})) firing_alerts slo.error_budget.firing_alerts() print(f → {len(firing_alerts)} alert(s) currently firing)底层实现中alerts()返回两条BurnRateAlertobjectives.pyburn_rate_warning2×warning与burn_rate_critical10×critical窗口均为 86400 秒24his_firing(current_burn_rate)即current_burn_rate rate。firing_alerts()则用当前 1h 燃烧速率过滤出正在触发的告警。若需要多窗口告警与多渠道路由docs/slo-reference.md 给出了扩展方案1h/14.4×、6h/6×、24h/3×、72h/1× 的四窗口组合以及经AlertManager将 P1/P2 路由到 PagerDuty、P3 路由到 Slack 的示例。八、第 7 步What-If 分析——延迟 20% 对预算的影响Notebook 最后一个实验回答一个典型容量问题如果延迟上涨 20%错误预算会怎样 做法是复用同一随机种子重放 200 次调用仅把每次延迟乘以1.20再对比基线与假设场景的 p95 延迟和剩余预算LATENCY_INCREASE 1.20 # 20 % wif_latency ResponseLatency(target_ms3000.0, percentile0.95, window1h) wif_accuracy ToolCallAccuracy(target0.99, window24h) wif_cost CostPerTask(target_usd0.50, window24h) wif_budget ErrorBudget(total0.05, burn_rate_alert2.0, burn_rate_critical10.0, exhaustion_actionExhaustionAction.FREEZE_DEPLOYMENTS) wif_slo SLO(namecode-review-agent-whatif, indicators[wif_latency, wif_accuracy, wif_cost], error_budgetwif_budget, agent_idcode-review-agent) random.seed(42) for i in range(NUM_CALLS): task_ok random.random() 0.92 tool_ok random.random() 0.985 latency_ms max(100, random.gauss(2400, 700)) * LATENCY_INCREASE cost_usd max(0.01, random.gauss(0.35, 0.15)) wif_accuracy.record_call(tool_ok) wif_latency.record_latency(latency_ms) wif_cost.record_cost(cost_usd) wif_slo.record_event(goodtask_ok and tool_ok) wif_budget_remaining.append(wif_slo.error_budget.remaining_percent)对比输出包含基线 vs 假设的 p95 延迟、基线 vs 假设的剩余预算百分比并绘制左右双联图左两条预算剩余曲线对比右两组延迟分布直方图叠加红色虚线标出 3000 ms 目标。这类同一流量、单一变量的重放方法可直接迁移到容量规划、模型升级预评估等场景也是 examples/canary_rollout.py 等金丝雀发布示例的思路原型。九、从 Notebook 到生产下一步路径Notebook 结尾给出的三条进阶路线均能在仓库中找到对应落地物调整耗尽策略把ExhaustionAction.FREEZE_DEPLOYMENTS换成CIRCUIT_BREAK或THROTTLE观察不同反应。CIRCUIT_BREAK可配合 src/agent_sre/cascade/circuit_breaker.py 与 src/agent_sre/incidents/circuit_breaker.py 使用为下游 agent 设置失败阈值与恢复超时防止级联故障。接入真实 Agent使用agent_sre.integrations.langchain.callback中的AgentSRECallbackcallback.py。该回调通过鸭子类型无侵入接入 LangChain 的callbacks[...]自动采集任务成功率、每次 chain/LLM 调用的延迟、按 token 估算的成本与工具调用成败Notebook 里手写的record_*循环在真实 Agent 上被它取代。CLI 版本examples/slo_alerting.pyexamples/slo_alerting.py把同一工作流压缩为脚本pip install agent-sre python examples/slo_alerting.py适合在 CI 或定时任务中输出文本版 SLO 报告。此外若要进一步体系化YAML 化 SLO仓库 specs/slos/ 提供base.yaml、batch_agent.yaml、critical_agent.yaml等模板可用agent_sre.slo.spec的load_slo_specs()与resolve_inheritance()spec.py加载并解析继承关系把 Notebook 中的 Python 定义固化为团队共享的配置文件。单元测试佐证Notebook 中所有 API 均有对应测试覆盖可参考 tests/unit/test_indicators.py 与 tests/unit/test_objectives.py了解各 SLI 聚合与预算状态的边界行为。完整概念地图SLO 设计原则、目标值选取100% 目标是不对的、按风险等级分层的目标表格见 docs/slo-reference.md。十、小结本指南完整复刻了slo-exploration.ipynb的实验主线从定义 p95 延迟、工具准确率、单任务成本三类 SLI 开始用 200 次带缺陷率的模拟调用驱动错误预算消耗再通过evaluate()状态机、燃烧速率告警与四联图可视化形成可观测 → 可预警 → 可决策的闭环最后用 what-if 重放验证单一变量变化对预算的影响。这套交互式流程既是学习 agent-sre SLO 模型最快的入口也是把 SRE 纪律引入 AI Agent 治理策略合规、零信任身份之外的第三个支柱——可靠性工程让继续上线与放慢节奏不再是拍脑袋决定而是由错误预算数据说了算。【免费下载链接】agent-governance-toolkitAI Agent Governance Toolkit — Policy enforcement, zero-trust identity, execution sandboxing, and reliability engineering for autonomous AI agents. Covers 10/10 OWASP Agentic Top 10.项目地址: https://gitcode.com/GitHub_Trending/ag/agent-governance-toolkit创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考