Agent 生产部署与 AgentOps:从 Demo 到可灰度、可回滚的长期系统
本文是 精英 Agent 工程师学习路线:从范式理解到生产级落地 阶段 12 的配套学习笔记。 核心结论:生产 Agent 不是“部署一个模型 API + FastAPI 容器”,而是一套可排队、可恢复、可限流、可观测、可评估、可灰度、可回滚的长期运行系统。AgentOps 的最终单位不是一次模型调用,而是一次经过验证的业务结果。
0. 学习目标与生产定义
学完本文后,你应该能够:
- 设计同步/异步 Run API、Event Stream、取消和恢复协议;
- 用队列、租约、优先级、公平性和 Backpressure 管理长任务;
- 通过 Checkpoint、Outbox、幂等和对账实现 Durable Execution;
- 建立供应商无关 Model Gateway、能力路由、限流、熔断和降级;
- 明确 PostgreSQL、Redis、向量/图索引和对象存储的真相边界;
- 设计容器、Kubernetes Probe、优雅停机、迁移与自动扩缩;
- 用 SLI/SLO/Error Budget 管理质量、延迟、安全和成本;
- 把 Agent/Model/Prompt/Tool/Policy/Index/Memory/Eval 组合成发布 Manifest;
- 通过 Eval Gate、Shadow、Canary、灰度和自动/人工回滚发布;
- 建立 Failure Collector、Replay、成本治理、灾备和事故 Runbook。
本文所说“生产级”至少满足:
可部署可恢复可验证可限流可观测可审计可灰度可回滚可持续维护1. 生产架构全景
Clients -> API Gateway / Auth / WAF / Rate Limit -> Agent Run API -> Sync Fast Path -> Durable Queue / Scheduler -> Agent Runtime Workers -> Model Gateway -> Providers / Self-hosted Models -> Tool/MCP/A2A Gateway -> Business Services -> RAG/Memory Services -> HITL Service
State & Data PostgreSQL / Redis / Object Store / Vector & Graph Index
Control Plane Registry / Policy / Config / Release / Routing / Budget / Kill Switch
Evidence Plane Trace / Metrics / Logs / Audit / Eval / Failure Store / Replay1.1 Control/Data/Evidence Plane
Control:允许怎样运行Data/Execution:正在怎样运行Evidence:刚才究竟怎样运行、是否成功1.2 三类请求
| 类型 | 例子 | 运行方式 |
|---|---|---|
| Fast sync | 分类、简单 FAQ | 请求内完成,严格 deadline |
| Interactive stream | 多步查询、逐步输出 | Run + SSE/WebSocket |
| Durable async | 报告、代码、跨系统审批 | Queue + Checkpoint + callback/poll |
不能用一个 60 秒 HTTP 请求承载所有恢复语义。
2. Run API:先创建任务,再传输进度
2.1 创建
POST /v1/agent-runsIdempotency-Key: req-user1-20260715-001
{ "thread_id": "thread_01J...", "agent": "orderflow", "input": {"message": "订单三天没发货,我要退款"}, "response_mode": "stream"}{ "run_id": "run_01J...", "status": "queued", "events_url": "/v1/agent-runs/run_01J/events", "status_url": "/v1/agent-runs/run_01J"}2.2 幂等创建
Idempotency-Key 绑定 tenant、user、agent、normalized input hash 与时间窗口。重复请求返回同一 Run,不创建两次任务。
2.3 Events
run.startedstep.started/completedmodel/tool progress(安全投影)human.requiredrun.completed/failed/cancelledEvent 带 event_id + sequence,客户端重连用 Last-Event-ID 或等价游标。
2.4 取消
POST /v1/agent-runs/{run_id}/cancel取消停止新动作,传播到可取消子任务,记录无法撤销的外部副作用并继续必要对账。
2.5 Run Status
created/queued/runningawaiting_input/confirmation/humanretry_scheduledsucceeded/failed/cancelled/budget_exhausted3. Queue、Scheduler 与 Backpressure
3.1 Queue Item
from pydantic import BaseModel
class WorkItem(BaseModel): work_id: str run_id: str step_id: str attempt: int tenant_id: str priority: int risk_class: str available_at: str deadline_at: str required_worker_pool: str idempotency_key: str3.2 Delivery
大多数队列提供 at-least-once。Worker 必须幂等,不能幻想消息只到一次。
3.3 Lease
dequeue-> acquire lease-> heartbeat-> execute/checkpoint-> ackLease 过期后可重新投递;旧 Worker 的提交使用 token/CAS 防止覆盖。
3.4 Priority/Fairness
critical human-resumeinteractive user taskbatch/reportmaintenance/replay再按 tenant quota/weighted fair queue,避免大租户饿死小租户。
3.5 Backpressure
当 queue wait、provider 429、tool latency 或 DB saturation 超阈值:
拒绝/延迟低优先级新任务返回 Retry-After降低 fan-out/并发暂停 batch/replay降级只读/人工3.6 DLQ
DLQ 不是永久垃圾桶。保存 failure reason、attempts、versions、last checkpoint;设 Owner、告警、保留与 redrive 流程。Redrive 前修复根因/幂等,不批量盲重放。
3.7 Admission Decision
class AdmissionDecision(BaseModel): decision: Literal["accept", "queue", "degrade", "reject"] queue_class: str | None estimated_start_at: str | None reserved_budget: dict degradation_profile: str | None retry_after_seconds: int | None reason_codes: list[str]输入:
tenant/user quotaqueue oldest age/depthworker capacityprovider token headroomtool dependency healthrisk/priority/deadlineestimated steps/tokens3.8 Aging 与 Priority Inversion
低优先级任务等待越久逐步提升有效优先级,防止永久饿死;但 Critical 人工恢复仍保留资源。高优先级任务依赖被低优先级任务占用的锁/连接时,需缩短临界区、分池或 priority inheritance,而不是只调队列数字。
3.9 Queue SLO
deptholdest agetime-to-start p50/p95/p99deadline missredelivery/lease expiryper-tenant fairnessDLQ ageQueue Depth 为 0 也可能是 Worker/Publisher 坏了;同时监控 accepted/started/completed 速率。
4. Durable Execution
4.1 Checkpoint
保存:
typed state/schema versioncurrent node/completed stepspending external operationbudget usagepinned release manifesthuman/confirmation statelast durable event sequence4.2 Checkpoint 时机
Run 创建有副作用动作前工具 Observation 后状态迁移后暂停/HITL 前最终响应前4.3 Outbox/Inbox
DB transaction: state transition + outbox eventcommit
publisher sends idempotentlyconsumer inbox deduplicates event_id4.4 Effectively Once
at-least-once+ idempotency+ CAS+ outbox/inbox+ external reconciliation= effectively-once business outcome4.5 Resume Compatibility
新 Worker 恢复旧 Checkpoint 前检查 state/workflow/tool schema migration。无法安全迁移则固定旧 Worker pool、人工或明确终止,不静默解释。
LangGraph deployment/durable execution 与 Temporal 提供不同层级的持久工作流能力。[S1] 框架不能替代业务工具幂等和对账。
5. Model Gateway 与路由
5.1 统一协议
ModelRequestModelEventUsageError TaxonomyCancellationProvider SDK 留在 Adapter。
5.2 Route Input
class ModelRouteRequest(BaseModel): purpose: str required_capabilities: list[str] data_classification: str region: str latency_budget_ms: int cost_budget_usd: float context_tokens: int risk_level: str5.3 Route 约束
结构化输出/工具/上下文能力数据地域/隐私模型允许用途当前 quota/error/latency质量层级成本5.4 Fallback Chain
primary reasoning model-> equivalent provider/model-> smaller model for safe subset-> deterministic rule/read-only-> humanFallback 必须重新计算 capability/risk,不能把高风险任务无条件交给弱模型。
5.5 Circuit Breaker
按 provider/model/region/error class 隔离:
closed -> open -> half-open -> closed不要因单个租户 invalid request 打开全局 breaker。
5.6 Hedging
并发请求多个模型可降尾延迟,但会增加成本、配额与数据外发,并可能重复工具提议。仅用于无副作用模型调用,取消 loser,并记录所有 usage。
5.7 研究启发
RouteLLM 研究用偏好数据学习强/弱模型路由;FrugalGPT 探索模型级联以降低成本。[P1] [P2] 生产路由还必须加入合规、能力和安全硬约束。
5.8 Provider Health
request/error by error classTTFT/total latencytokens/secrate-limit headroomschema/tool-call validitysafety/refusal distributioncostHealth 不是只有 HTTP 5xx;模型仍返回 200 但 Schema/工具质量突降也应隔离。
5.9 Route Outcome
class RouteOutcome(BaseModel): route_id: str route_version: str selected_model: str alternatives_considered: list[str] hard_constraints: list[str] selection_reasons: list[str] fallback_used: bool verified_task_success: bool | None usage: dict将延迟到达的业务 Outcome 回连 Route,才能训练/校准路由,而不只优化即时模型分数。
5.10 Route Shadow
新路由策略先对同一请求离线/Shadow 产生选择,比较:
constraint violationsquality deltacost/latency deltaprovider concentrationfallback load路由本身也有 Release Manifest、Eval 与回滚。
6. Rate Limit、Quota 与租户公平
6.1 层级
globalprovider/modeltenantuseragent/workflowtoolrisk class6.2 资源维度
requests/minutetokens/minuteconcurrent runstool callsretrieval queriescost/day6.3 Reservation
长 Run 开始前预留估算预算,执行中按实际结算;无法预留则排队/降级,避免运行到高风险写步骤才发现 quota 耗尽。
6.4 Provider 429
尊重 Retry-After,指数退避 + jitter,总 deadline 内重试。多 Worker 共享 provider limiter,避免各自重试形成惊群。
OpenAI Rate Limits/Production Best Practices 可作为供应商调用治理参考。[S2]
7. 存储职责
| 存储 | 适合 | 不适合 |
|---|---|---|
| PostgreSQL | Run/State/Audit refs/版本/幂等 | 大对象全文 |
| Redis | queue/cache/rate/lease/SSE window | 唯一业务真相 |
| Object Store | 原始 Artifact/Trace payload/报告 | 高频小事务 |
| Vector/Search | 可重建检索投影 | 唯一 Canonical Source |
| Graph | 关系投影 | 无图查询场景 |
7.1 PostgreSQL
事务、约束、CAS、索引、迁移、备份。核心查询字段不要全部塞 JSONB。
7.2 Redis
Key 包含 environment/tenant/version,明确 TTL、eviction、cache stampede 和 failover 语义。
7.3 Object Reference
大型/敏感结果通过签名短期 URL 或受控服务读取,不把永久公网 URL 放 Trace。
7.4 Projection Lag
Canonical -> Vector/Graph/Analytics 使用 Outbox;监控 watermark/lag/repair。
8. Cache:缓存正确性优先
8.1 类型
deterministic function cacheembedding cacheretrieval cachetool read-result cachemodel semantic/exact cache(谨慎)context package cache8.2 Key
tenantidentity/ACL fingerprintnormalized inputmodel/prompt/tool/policy/index versionslocale/time bucket8.3 不缓存
高风险写结果作为“可再次执行”含动态权限且 key 不完整的数据高度个性化敏感响应未验证的模型输出8.4 Stampede
singleflight/lease、jittered TTL、stale-while-revalidate(只限允许陈旧的数据)。
8.5 Invalidation
Policy/ACL/Index/Tool 版本变化时通过版本化 Key 自然失效;紧急撤回支持 denylist/epoch bump。
9. Container 与 Kubernetes
9.1 Image
multi-stage buildnon-rootminimal baselocked dependencies/SBOM/signatureread-only filesystem where possibleno embedded secret9.2 Probes
startup:慢初始化是否完成liveness:进程是否需要重启readiness:当前是否能接新流量Readiness 可以检查关键配置/队列/DB;不要因非关键外部模型短暂失败让所有 Pod 反复重启。Kubernetes 官方 Probe 文档见 [S3]。
9.3 Graceful Shutdown
readiness=false停止领取新 Work等待/Checkpoint 当前 Step释放 lease/连接flush critical audit/outbox在 termination grace 内退出9.4 Migration
独立 Job 执行,遵循 expand-migrate-contract:先兼容新旧 schema,再迁移数据,最后删除旧字段。多个 Pod 不同时跑 migration。
9.5 HPA/KEDA 指标
HTTP concurrencyqueue depth/oldest ageactive leasesCPU/memoryprovider quota headroom仅按 CPU 扩容可能越扩越触发模型 429。
9.6 Disruption
PodDisruptionBudget、topology spread、anti-affinity 与足够 termination grace,避免升级同时中断全部长 Run。[S3]
9.7 Worker Autoscaling
近似所需 Worker:
workers ≈ arrival_rate × avg_service_time / target_utilization长尾、不同 Worker Pool 和外部 quota 需要分别建模。Scale-out 前确认 Provider/DB/Tool 还有 headroom;否则增加 Pod 只会增加排队和 429。
9.8 Scale-to-zero
适合低频 batch/eval pool;交互/高风险恢复 pool 通常保留 warm capacity。冷启动需计算镜像、模型/依赖加载、连接建立与首次请求延迟。
9.9 Runtime Class
不同任务声明:
cpu/memorysandbox isolationnetwork policydeadlinecheckpoint requirementGPU/model localityScheduler 按 Runtime Class 路由,不让高风险代码任务进入普通 API Pod。
10. SLI、SLO 与 Error Budget
10.1 SLI
Verified Task SuccessCorrect/Unsafe ActionAvailabilityRun/Queue LatencyCheckpoint RecoveryHuman EscalationCost per Verified SuccessTrace/Audit Completeness10.2 SLO 示例
window: 28dslos: verified_task_success: ">= 99.0% for eligible refund queries" unsafe_action_rate: "0 for critical cases" api_availability: ">= 99.9%" interactive_p95: "<= 8s to first meaningful event" queue_p95: "<= 20s" recovery_success: ">= 99.5%"10.3 Error Budget
质量/可用性预算消耗过快时:
冻结高风险功能扩张降级/回滚新版本优先可靠性工作增加人工门禁Google Cloud SLO Monitoring 与 AWS Generative AI Lens 提供 SLO/生成式 AI Well-Architected 的公开工程参考。[S4]
10.4 Burn Rate
短/长窗口告警,既捕获快速事故,也捕获慢性退化。安全零容忍指标直接告警/遏制,不等 Error Budget。
10.5 SLO 分母
明确 eligible、user-cancel、policy-deny、environment outage 是否计入;不能为了好看排除系统导致的失败。
10.6 Error Budget Policy
if: - critical_safety_incident: truethen: - disable_high_risk_writes - rollback_latest_release - page_security_and_business_owner
if: - success_slo_burn_rate_1h: "> 14.4"then: - halt_rollout - route_to_stable_release
if: - monthly_error_budget_remaining: "< 25%"then: - freeze_non_reliability_changes - require_extra_canary阈值需按团队 SLO 计算;示例数字不是通用标准。
10.7 Quality SLO 的延迟
部分 Outcome 数天后到达。实时使用 proxy SLI(Verifier、首次解决),最终以退款成功/工单重开/用户复联校正。Dashboard 明确 preliminary 与 matured window。
11. Observability 与 AgentOps
11.1 Trace
关联:
Run/Step/AttemptModel/Prompt/RouteTool/MCP/A2AState/CheckpointPolicy/HITLRAG/MemoryCost/Latency/Error11.2 Metrics
runs_total{status,agent_version}run_duration_secondsqueue_oldest_age_secondsmodel_calls_total{provider,model,status}tool_calls_total{tool,status}checkpoint_recovery_total{status}cost_usd_total{tenant,agent}eval_task_success{release}避免 user/run ID 作为 Metric label。
11.3 Logs
结构化、带 trace/run、错误码和安全分类;原始 Prompt/工具敏感结果用受控引用。
11.4 Audit
高风险动作完整记录主体、委派、资源、Policy、确认、工具和最终结果;与可采样 Trace 分离。
11.5 Dashboard
Executive:success/safety/cost/SLORuntime:queue/worker/checkpoint/retryModel:route/latency/token/errorTools:success/unknown outcome/dependencyQuality:eval/failure slices/regressions11.6 OpenTelemetry
GenAI conventions 仍处 Development,内部事件协议应稳定并固定映射版本。[S5]
12. Version Registry 与 Release Manifest
12.1 版本对象
Agent/WorkflowModel/Adapter/TokenizerPrompt BundleTool/MCP/Skill RegistryPolicy/GuardrailRAG IndexMemory Schema/Write PolicyEvaluator/DatasetRuntime/Container12.2 Manifest
release: orderflow-agent@3.2.0runtime_image: sha256:...workflow: refund@7model_route: support-default@9prompt_bundle: support@12tool_registry: orderflow@42policy_bundle: refund-cn@18rag_index: policy-2026-07-15.3memory_policy: user-profile@5eval_dataset: orderflow-eval@2026-07-15.3eval_report: eval://orderflow/3.2.0created_at: 2026-07-15T10:00:00Z12.3 Compatibility
Registry 声明兼容矩阵和迁移。Prompt 引用旧 Tool 字段、Workflow 读取旧 State 都应在发布前失败。
12.4 Immutable
Manifest/Digest 不覆盖;部署切 pointer。回滚到完整组合,不只换模型。
12.5 在途 Run 策略
发布前按变更分类:
Compatible:旧 Run 可由新 Worker 恢复Pinned:旧 Run 必须继续使用旧 ManifestMigrate:运行显式 State MigrationDrain:等待旧 Run 完成再下线Terminate/Human:无法安全迁移12.6 State Migration
class StateMigrationResult(BaseModel): from_schema: str to_schema: str migrated_state_ref: str preserved_effect_refs: list[str] warnings: list[str] validation_passed: boolMigration 在副本上运行、通过 invariant/fixture 后 CAS 替换;保留旧 Checkpoint 供回滚/取证。
12.7 Registry Garbage Collection
旧版本只有在:
无在途 Run/Replay 保留需求回滚窗口结束Audit/合规保留满足Artifact/Checkpoint 依赖解除后才能退役。删除镜像/Prompt/Tool 过早会让历史 Run 不可复现。
13. Eval Gate 与发布策略
13.1 Pipeline
lint/unit/contract-> scenario eval-> adversarial/regression-> cost/latency-> manifest/sign-> shadow-> canary-> progressive rollout-> full13.2 Shadow
候选不执行真实副作用,比较轨迹/决策/成本。对动态工具使用隔离 Environment。
13.3 Canary
stable user/tenant bucketing低风险/只读先行强 HITL自动 stop/rollback thresholds13.4 Rollback
触发:
critical safetySLO burntask success regressioncost/latency spikedependency errortrace/audit gap回滚后进行中 Run 按 pinned manifest 完成或迁移/终止;不能让一半 Step 使用旧工具、一半使用新 Policy。
13.5 Feature Flag
按 agent capability/tenant/risk 控制新 Planner、Memory、Tool 或 Model Route;Flag 也有 Owner、expiry 和审计,避免永久分叉。
14. 成本治理
14.1 成本模型
Model input/output/reasoning/cacheEmbedding/RerankTool/APIVector/Graph/DB/Object storageQueue/ComputeObservability/EvalHuman Review14.2 关键分母
Cost per Verified SuccessCost per Resolved TicketCost per Safe Automated ActionMarginal Cost of Reflection/Multi-Agent14.3 控制手段
Context selection/compactionTool candidate pruningModel routing/cascadeCache/batchstop/no-progressparallelism only when usefuloffline/nightly eval scheduling14.4 Budget
Run/tenant/agent/day 设置软硬预算;软阈值降模型/减少反思,硬阈值停止低优先级并告警。
14.5 Chargeback/Showback
按 tenant/product/agent/scenario 分摊,但共享基础设施采用清晰规则。成本标签不能包含敏感高基数数据。
14.6 Cost Ledger
class CostEntry(BaseModel): run_id: str step_id: str | None tenant_id: str category: Literal[ "model", "embedding", "rerank", "tool", "compute", "storage", "observability", "human" ] provider: str units: dict amount_usd: float pricing_version: str occurred_at: str14.7 Pricing Version
供应商价格变化后,同一 token 用量的成本不同。保存 pricing table version,支持同时报告实际账单成本与标准化单位成本。
14.8 Savings Guardrail
成本优化候选必须同时满足:
critical safety unchangedverified success within budgethuman escalation not increased materiallylatency SLO将任务提前失败或转人工不算模型成本优化。
AI Agents That Matter 强调同时考虑准确性与成本、避免不可靠比较。[P3]
15. Failure Collector 与 Replay
15.1 Failure Envelope
class FailureEnvelope(BaseModel): failure_id: str run_id: str trace_id: str first_failure_code: str contributing_codes: list[str] release_manifest: str checkpoint_ref: str environment_refs: list[str] data_classification: str occurred_at: str15.2 自动收集
terminal failureunsafe/policy blockhuman overridehigh cost/latencyfallbackunknown outcomeuser correction15.3 Replay 类型
Dry Replay:不调用外部写工具Fixture Replay:在模拟环境完整执行Shadow Replay:新版本对历史输入运行Time-travel:从 checkpoint/旧 state fork15.4 安全
Replay 默认禁用真实副作用,使用 tokenized/synthetic data,严格访问和保留。
15.5 进入 Regression
Triage -> 最小复现 -> Gold/断言 -> Dataset Snapshot -> CI Gate。
16. OrderFlow 生产蓝图
16.1 Pools
api-poolinteractive-worker-poolbatch-worker-poolhigh-risk-action-pooleval/replay-pool高风险 Tool Adapter 独立身份/网络/配额。
16.2 主链路
Gateway Auth-> Create Run/Queue-> Worker loads pinned Manifest/Checkpoint-> read tools + RuleRAG-> Policy/HITL-> high-risk action pool executes idempotently-> verify final state-> event/trace/audit/eval hooks16.3 Degradation
| 故障 | 降级 |
|---|---|
| 强模型不可用 | 等价 fallback/只读规则/人工 |
| RAG 不可用 | 不做基于规则的写动作 |
| Redis 不可用 | DB/queue fallback 或拒绝新长 Run |
| Audit 不可用 | 高风险写 fail closed |
| Policy 不可用 | deny/human |
| Human queue 满 | 排队/告知,不自动批准 |
16.4 SLO
退款查询 verified success确认前错误写 = 0重复退款 = 0first meaningful event p95queue age p95final-state verification coveragecost per resolved request17. Capacity Planning
17.1 Little’s Law
concurrency ≈ throughput × average time in systemAgent Run 变长会放大在途状态、连接、队列与 DB 压力。
17.2 Workload Model
arrival rate by scenario/tenantsteps/model/tool calls per runservice time distributiontoken distributionhuman wait exclusion/inclusionburst factor17.3 Bottleneck
Provider quota、工具 API、DB connections、reranker GPU、human review 都可能先于 CPU 饱和。
17.4 Load Test
使用 stub/sandbox Provider 与 Tool,避免对真实外部系统产生费用/副作用;另做小规模真实依赖容量验证。
17.5 Tail
按 p95/p99 与 queue oldest age 容量规划,不只看平均。
18. Backup、DR 与多区域
18.1 RPO/RTO
分别为:
Run/CheckpointAuditBusiness IdempotencyMemory/RAG CanonicalIndex ProjectionArtifact定义恢复点/时间。
18.2 Backup
加密、访问隔离、定期 restore test。未测试恢复的备份不算可用。
18.3 Projection
向量/图索引可从 Canonical 重建,DR 重点是 Manifest/Parser/Embedding 版本和重建时间。
18.4 Multi-region
考虑:
数据驻留身份/Policy 一致Run affinity跨区状态复制重复执行风险模型/工具区域能力高风险写使用单一 home region 或全局幂等协调,避免双主重复。
18.5 DR Drill
模拟 region/provider/DB/queue 失败,验证切换、在途 Run、回退能力、Audit 和用户通知。
19. Incident Response 与 Runbook
19.1 诊断顺序
1. 用户/业务影响与严重级别2. 哪个 Release/tenant/scenario3. SLO/queue/provider/tool/DB 状态4. first divergent Span/State5. 是否有安全/副作用6. 遏制/回滚/降级19.2 Kill Switch
按 model/agent/tool/MCP/Skill/policy/tenant/risk 快速禁用;测试权限和演练。
19.3 Evidence
保全 Trace、Audit、Manifest、Checkpoint、环境状态;避免自动清理覆盖。
19.4 Recovery
回滚/修复对账外部状态补偿/通知最小回归shadow/canary 恢复19.5 Postmortem
根因、促成因素、控制为何失败、检测为何迟、行动项 Owner/期限。不要只写“模型幻觉”。
19.6 Maintenance Cadence
Daily:SLO/critical alerts/DLQ/unknown outcomesWeekly:failure clusters/cost/fallback/human queueMonthly:model/tool/policy/index drift + dependency updatesQuarterly:DR/security/rollback drill + retention review19.7 Toil
重复手工重放、标注、对账和回滚应被测量。自动化优先减少高风险、频繁、可标准化 Toil,但保留审批和验证边界。
19.8 Action Tracking
Postmortem 行动项进入普通工程系统,具备 Owner、优先级、期限、验证方法和关闭证据;“加强监控”不是可验收行动。
20. 大厂与平台方案对照
| 方案 | 公开能力 | 可借鉴 | 需自行补齐 |
|---|---|---|---|
| Google Agent Platform/Engine | 托管 Runtime、scale/session/memory/eval 等平台能力 | runtime/control-plane 分层 | 业务事务/可迁移性 |
| Azure AI Foundry Agent Service | 托管 Agent、工具、身份/企业集成 | Azure 治理 | 业务 Eval/Policy |
| AWS Bedrock AgentCore | Agent runtime/identity/memory/gateway 等 | 云生产组件组合 | 领域状态/成本验证 |
| LangSmith Deployment | LangGraph 应用部署/持久运行 | graph runtime/observability | 业务幂等/安全 |
| Temporal | Durable execution | 长任务/重试/signal | 模型/Context/Eval |
| LiteLLM/Cloudflare/Azure AI Gateway | 多模型 proxy、rate、cache/observability 等 | 统一模型入口 | 领域路由质量 |
| Kubernetes | probe、HPA、PDB、rollout | 通用运行底座 | Agent 状态语义 |
官方入口见 [S1] 到 [S7]。平台能力降低基础设施工作,不会自动提供正确的业务成功条件与事故闭环。
21. 前沿论文的生产启发
| 工作 | 关注 | AgentOps 落点 |
|---|---|---|
| RouteLLM [P1] | 质量/成本模型路由 | 约束下动态 Route |
| FrugalGPT [P2] | 模型级联 | cascade + budget |
| AI Agents That Matter [P3] | 成本与可靠比较 | cost per success、paired eval |
| vLLM [P4] | PagedAttention/KV 管理 | 自托管吞吐与容量 |
| SGLang [P5] | structured LLM program execution | 多调用/结构执行优化 |
| ServerlessLLM [P6] | 低延迟 serverless serving | 冷启动/权重加载设计 |
| SWE-agent [P7] | ACI 对 Agent 表现影响 | Tool/Runtime 接口治理 |
| AgentBench [P8] | 多环境 Agent 评估 | 发布前环境级验证 |
推理服务论文主要优化模型 Serving,不会解决 Agent 的业务状态、工具副作用和 Policy。
22. Failure Taxonomy
| 编号 | 失败 | 示例 | 首要层 |
|---|---|---|---|
| O01 | Admission | 无 backpressure 过载 | Gateway/Scheduler |
| O02 | Queue | 不公平/任务饿死 | Scheduler |
| O03 | Lease | 双 Worker 提交 | Runtime |
| O04 | Checkpoint | 无法恢复/版本不兼容 | State Store |
| O05 | Model Route | 能力/合规错误 | Gateway |
| O06 | Retry Storm | 429 时全体重试 | Limit/Backoff |
| O07 | Cache Leak | key 缺 ACL/tenant | Cache |
| O08 | Migration | 新旧 schema 不兼容 | Release |
| O09 | Probe | 依赖抖动导致重启 | Kubernetes |
| O10 | Rollout | 混用 Manifest 版本 | Control Plane |
| O11 | Cost | reflection/multi-agent 爆炸 | Budget |
| O12 | Trace Gap | 无法定位失败 | Observability |
| O13 | Replay Side Effect | 历史任务重放真实退款 | Replay Sandbox |
| O14 | DR Duplicate | 多区重复写 | Idempotency/Region |
23. 常见反模式
23.1 HTTP 请求内跑完整长任务
断线、超时、恢复和取消语义混乱。
23.2 Redis 是唯一状态源
TTL/eviction/failover 后丢失关键 Run/Audit。
23.3 失败就换模型
错误可能来自 Tool/Policy/Context;Fallback 还可能降安全能力。
23.4 自动重试所有写操作
产生重复副作用;先幂等/对账。
23.5 只按 CPU 扩容
瓶颈常是 provider quota/queue/tool/DB/human。
23.6 只回滚 Prompt/Model
Release 是完整 Manifest 组合。
23.7 Dashboard 等于 AgentOps
没有 Eval/Failure/Replay/Release/Incident 闭环,只是看图。
23.8 成本按 Run 平均
早失败系统看起来更便宜;使用单位 Verified Success。
24. 项目目录与实践任务
app/ api/ runs.py events.py runtime/ scheduler.py worker.py leases.py checkpoint.py recovery.py gateway/ model.py routing.py limiter.py circuit_breaker.py ops/ registry.py release.py failure_collector.py replay.py cost.py slo.py observability/ tracing.py metrics.py audit.py deployment/ migrations/ manifests/infra/ docker/ kubernetes/ dashboards/ alerts/docs/ deployment.md maintenance_playbook.md disaster_recovery.md incident_runbooks/实践顺序:
1. Run API + typed state + idempotency2. Queue/lease/backpressure3. Checkpoint/outbox/recovery4. Model Gateway/limit/fallback5. PostgreSQL/Redis/Index 责任边界6. Container/probes/graceful shutdown7. Trace/metrics/audit/cost8. Release Manifest + Eval CI Gate9. Shadow/canary/rollback10. Failure Replay + DR/incident drill25. 达标检查清单
Runtime
- Run API 支持幂等、事件重连、取消和状态查询;
- Queue 有租约、优先级、公平和 Backpressure;
- Checkpoint/Outbox/Inbox 支持恢复;
- 写工具 outcome_unknown 会对账;
- 旧 Checkpoint 有版本兼容策略。
Gateway/Data
- Model Route 同时考虑能力、合规、质量、延迟和成本;
- Rate/Quota 在全局、租户、Agent、Tool 多层执行;
- PostgreSQL/Redis/Object/Index 真相边界清楚;
- Cache key 包含 tenant/ACL/versions;
- Fallback 同时降低不支持的权限。
Deploy/SLO
- Image 锁定、签名、非 root、无 Secret;
- startup/liveness/readiness 与 graceful shutdown 正确;
- Migration expand-contract;
- HPA 结合 queue/provider quota;
- SLO 覆盖质量、安全、延迟、恢复、成本和证据完整性。
Release/AgentOps
- Release Manifest 关联所有版本;
- Eval Hard Gate -> Shadow -> Canary -> 灰度;
- 回滚完整组合并处理在途 Run;
- Failure 自动沉淀并安全 Replay;
- 有 Kill Switch、DR restore 和 Incident 演练;
- 成本按 Verified Success 管理。
26. 面试与架构评审问题
- 同步、流式和 Durable Run 如何选择?
- at-least-once Queue 如何避免重复业务动作?
- Checkpoint 与业务事务的边界是什么?
- Model Gateway 路由为什么不能只看价格和 Benchmark?
- Fallback 为什么需要重新计算权限?
- Cache key 为什么要包含 ACL 和版本?
- Kubernetes readiness/liveness/startup 如何区分?
- Agent SLO 为什么要包含 Verified Task Success?
- Release Manifest 为什么比单独模型版本重要?
- 如何安全 Replay 一次退款失败?
- Cost per Run 为什么可能误导?
- Region 故障时如何避免重复退款?
27. 参考资料与延伸阅读
以下资料用于核对生产实践、平台能力与研究方向。托管产品和 SDK 会演进;生产发布需固定版本、区域、配额和数据政策。
官方生产与平台方案
[S1] Durable Agent Runtime
- LangSmith Deployment;
- Temporal documentation;
- LangGraph Durable execution。
[S2] Provider Production Guides
- OpenAI Production best practices;
- OpenAI Rate limits。
[S3] Kubernetes Runtime
- Kubernetes Liveness, Readiness and Startup Probes;
- Kubernetes Horizontal Pod Autoscaling;
- Kubernetes Disruptions。
[S4] SLO 与 Well-Architected
- Google Cloud SLO monitoring;
- AWS Generative AI Lens。
[S5] Observability
[S6] Model Gateway
- LiteLLM Proxy;
- Cloudflare AI Gateway;
- Microsoft AI gateway in Azure API Management。
[S7] 托管 Agent 平台与 Gateway
- Google Cloud Agent Platform scale;
- Microsoft Azure AI Foundry Agent Service;
- AWS Bedrock AgentCore。
论文与系统研究
[P1] RouteLLM
- Ong et al., RouteLLM: Learning to Route LLMs with Preference Data, 2024。
[P2] FrugalGPT
[P3] AI Agents That Matter
- Kapoor et al., AI Agents That Matter, 2024。
[P4] vLLM
- Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention, SOSP 2023。
[P5] SGLang
- Zheng et al., SGLang: Efficient Execution of Structured Language Model Programs, 2023。
[P6] ServerlessLLM
- Fu et al., ServerlessLLM: Low-Latency Serverless Inference for Large Language Models, OSDI 2024。
[P7] SWE-agent
- Yang et al., SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering, NeurIPS 2024。
[P8] AgentBench
- Liu et al., AgentBench: Evaluating LLMs as Agents, ICLR 2024。
28. 阶段总结
AgentOps 的闭环不是“有 Dashboard”,而是:
请求可进入有界队列;任务可持久化和恢复;模型/工具可路由、限流、熔断和降级;状态和副作用可幂等对账;发布组合有完整 Manifest;变更先 Eval,再 Shadow/Canary;失败可收集、最小复现和 Replay;事故可遏制、回滚、恢复和回归。一次线上失败的标准处理路径应能明确执行:
查 SLO/告警-> 定位 Release/Run/first divergent Span-> 判断安全和业务影响-> Kill Switch/降级/回滚-> 对账外部状态-> 最小复现-> 修复并加入 Regression-> Eval Gate-> Shadow/Canary-> 监控恢复并完成 Postmortem能稳定完成这条链路,Agent 才真正从 Demo 变成可长期维护的生产系统。