5697 字
28 分钟

Agent 生产部署与 AgentOps:从 Demo 到可灰度、可回滚的长期系统

本文是 精英 Agent 工程师学习路线:从范式理解到生产级落地 阶段 12 的配套学习笔记。 核心结论:生产 Agent 不是“部署一个模型 API + FastAPI 容器”,而是一套可排队、可恢复、可限流、可观测、可评估、可灰度、可回滚的长期运行系统。AgentOps 的最终单位不是一次模型调用,而是一次经过验证的业务结果。


0. 学习目标与生产定义#

学完本文后,你应该能够:

  1. 设计同步/异步 Run API、Event Stream、取消和恢复协议;
  2. 用队列、租约、优先级、公平性和 Backpressure 管理长任务;
  3. 通过 Checkpoint、Outbox、幂等和对账实现 Durable Execution;
  4. 建立供应商无关 Model Gateway、能力路由、限流、熔断和降级;
  5. 明确 PostgreSQL、Redis、向量/图索引和对象存储的真相边界;
  6. 设计容器、Kubernetes Probe、优雅停机、迁移与自动扩缩;
  7. 用 SLI/SLO/Error Budget 管理质量、延迟、安全和成本;
  8. 把 Agent/Model/Prompt/Tool/Policy/Index/Memory/Eval 组合成发布 Manifest;
  9. 通过 Eval Gate、Shadow、Canary、灰度和自动/人工回滚发布;
  10. 建立 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 / Replay

1.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-runs
Idempotency-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.started
step.started/completed
model/tool progress(安全投影)
human.required
run.completed/failed/cancelled

Event 带 event_id + sequence,客户端重连用 Last-Event-ID 或等价游标。

2.4 取消#

POST /v1/agent-runs/{run_id}/cancel

取消停止新动作,传播到可取消子任务,记录无法撤销的外部副作用并继续必要对账。

2.5 Run Status#

created/queued/running
awaiting_input/confirmation/human
retry_scheduled
succeeded/failed/cancelled/budget_exhausted

3. 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: str

3.2 Delivery#

大多数队列提供 at-least-once。Worker 必须幂等,不能幻想消息只到一次。

3.3 Lease#

dequeue
-> acquire lease
-> heartbeat
-> execute/checkpoint
-> ack

Lease 过期后可重新投递;旧 Worker 的提交使用 token/CAS 防止覆盖。

3.4 Priority/Fairness#

critical human-resume
interactive user task
batch/report
maintenance/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 quota
queue oldest age/depth
worker capacity
provider token headroom
tool dependency health
risk/priority/deadline
estimated steps/tokens

3.8 Aging 与 Priority Inversion#

低优先级任务等待越久逐步提升有效优先级,防止永久饿死;但 Critical 人工恢复仍保留资源。高优先级任务依赖被低优先级任务占用的锁/连接时,需缩短临界区、分池或 priority inheritance,而不是只调队列数字。

3.9 Queue SLO#

depth
oldest age
time-to-start p50/p95/p99
deadline miss
redelivery/lease expiry
per-tenant fairness
DLQ age

Queue Depth 为 0 也可能是 Worker/Publisher 坏了;同时监控 accepted/started/completed 速率。


4. Durable Execution#

4.1 Checkpoint#

保存:

typed state/schema version
current node/completed steps
pending external operation
budget usage
pinned release manifest
human/confirmation state
last durable event sequence

4.2 Checkpoint 时机#

Run 创建
有副作用动作前
工具 Observation 后
状态迁移后
暂停/HITL 前
最终响应前

4.3 Outbox/Inbox#

DB transaction:
state transition
+ outbox event
commit
publisher sends idempotently
consumer inbox deduplicates event_id

4.4 Effectively Once#

at-least-once
+ idempotency
+ CAS
+ outbox/inbox
+ external reconciliation
= effectively-once business outcome

4.5 Resume Compatibility#

新 Worker 恢复旧 Checkpoint 前检查 state/workflow/tool schema migration。无法安全迁移则固定旧 Worker pool、人工或明确终止,不静默解释。

LangGraph deployment/durable execution 与 Temporal 提供不同层级的持久工作流能力。[S1] 框架不能替代业务工具幂等和对账。


5. Model Gateway 与路由#

5.1 统一协议#

ModelRequest
ModelEvent
Usage
Error Taxonomy
Cancellation

Provider 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: str

5.3 Route 约束#

结构化输出/工具/上下文能力
数据地域/隐私
模型允许用途
当前 quota/error/latency
质量层级
成本

5.4 Fallback Chain#

primary reasoning model
-> equivalent provider/model
-> smaller model for safe subset
-> deterministic rule/read-only
-> human

Fallback 必须重新计算 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 class
TTFT/total latency
tokens/sec
rate-limit headroom
schema/tool-call validity
safety/refusal distribution
cost

Health 不是只有 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 violations
quality delta
cost/latency delta
provider concentration
fallback load

路由本身也有 Release Manifest、Eval 与回滚。


6. Rate Limit、Quota 与租户公平#

6.1 层级#

global
provider/model
tenant
user
agent/workflow
tool
risk class

6.2 资源维度#

requests/minute
tokens/minute
concurrent runs
tool calls
retrieval queries
cost/day

6.3 Reservation#

长 Run 开始前预留估算预算,执行中按实际结算;无法预留则排队/降级,避免运行到高风险写步骤才发现 quota 耗尽。

6.4 Provider 429#

尊重 Retry-After,指数退避 + jitter,总 deadline 内重试。多 Worker 共享 provider limiter,避免各自重试形成惊群。

OpenAI Rate Limits/Production Best Practices 可作为供应商调用治理参考。[S2]


7. 存储职责#

存储适合不适合
PostgreSQLRun/State/Audit refs/版本/幂等大对象全文
Redisqueue/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 cache
embedding cache
retrieval cache
tool read-result cache
model semantic/exact cache(谨慎)
context package cache

8.2 Key#

tenant
identity/ACL fingerprint
normalized input
model/prompt/tool/policy/index versions
locale/time bucket

8.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 build
non-root
minimal base
locked dependencies/SBOM/signature
read-only filesystem where possible
no embedded secret

9.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 concurrency
queue depth/oldest age
active leases
CPU/memory
provider 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/memory
sandbox isolation
network policy
deadline
checkpoint requirement
GPU/model locality

Scheduler 按 Runtime Class 路由,不让高风险代码任务进入普通 API Pod。


10. SLI、SLO 与 Error Budget#

10.1 SLI#

Verified Task Success
Correct/Unsafe Action
Availability
Run/Queue Latency
Checkpoint Recovery
Human Escalation
Cost per Verified Success
Trace/Audit Completeness

10.2 SLO 示例#

window: 28d
slos:
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: true
then:
- 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 明确 preliminarymatured window。


11. Observability 与 AgentOps#

11.1 Trace#

关联:

Run/Step/Attempt
Model/Prompt/Route
Tool/MCP/A2A
State/Checkpoint
Policy/HITL
RAG/Memory
Cost/Latency/Error

11.2 Metrics#

runs_total{status,agent_version}
run_duration_seconds
queue_oldest_age_seconds
model_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/SLO
Runtime:queue/worker/checkpoint/retry
Model:route/latency/token/error
Tools:success/unknown outcome/dependency
Quality:eval/failure slices/regressions

11.6 OpenTelemetry#

GenAI conventions 仍处 Development,内部事件协议应稳定并固定映射版本。[S5]


12. Version Registry 与 Release Manifest#

12.1 版本对象#

Agent/Workflow
Model/Adapter/Tokenizer
Prompt Bundle
Tool/MCP/Skill Registry
Policy/Guardrail
RAG Index
Memory Schema/Write Policy
Evaluator/Dataset
Runtime/Container

12.2 Manifest#

release: orderflow-agent@3.2.0
runtime_image: sha256:...
workflow: refund@7
model_route: support-default@9
prompt_bundle: support@12
tool_registry: orderflow@42
policy_bundle: refund-cn@18
rag_index: policy-2026-07-15.3
memory_policy: user-profile@5
eval_dataset: orderflow-eval@2026-07-15.3
eval_report: eval://orderflow/3.2.0
created_at: 2026-07-15T10:00:00Z

12.3 Compatibility#

Registry 声明兼容矩阵和迁移。Prompt 引用旧 Tool 字段、Workflow 读取旧 State 都应在发布前失败。

12.4 Immutable#

Manifest/Digest 不覆盖;部署切 pointer。回滚到完整组合,不只换模型。

12.5 在途 Run 策略#

发布前按变更分类:

Compatible:旧 Run 可由新 Worker 恢复
Pinned:旧 Run 必须继续使用旧 Manifest
Migrate:运行显式 State Migration
Drain:等待旧 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: bool

Migration 在副本上运行、通过 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
-> full

13.2 Shadow#

候选不执行真实副作用,比较轨迹/决策/成本。对动态工具使用隔离 Environment。

13.3 Canary#

stable user/tenant bucketing
低风险/只读先行
强 HITL
自动 stop/rollback thresholds

13.4 Rollback#

触发:

critical safety
SLO burn
task success regression
cost/latency spike
dependency error
trace/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/cache
Embedding/Rerank
Tool/API
Vector/Graph/DB/Object storage
Queue/Compute
Observability/Eval
Human Review

14.2 关键分母#

Cost per Verified Success
Cost per Resolved Ticket
Cost per Safe Automated Action
Marginal Cost of Reflection/Multi-Agent

14.3 控制手段#

Context selection/compaction
Tool candidate pruning
Model routing/cascade
Cache/batch
stop/no-progress
parallelism only when useful
offline/nightly eval scheduling

14.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: str

14.7 Pricing Version#

供应商价格变化后,同一 token 用量的成本不同。保存 pricing table version,支持同时报告实际账单成本与标准化单位成本。

14.8 Savings Guardrail#

成本优化候选必须同时满足:

critical safety unchanged
verified success within budget
human escalation not increased materially
latency 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: str

15.2 自动收集#

terminal failure
unsafe/policy block
human override
high cost/latency
fallback
unknown outcome
user correction

15.3 Replay 类型#

Dry Replay:不调用外部写工具
Fixture Replay:在模拟环境完整执行
Shadow Replay:新版本对历史输入运行
Time-travel:从 checkpoint/旧 state fork

15.4 安全#

Replay 默认禁用真实副作用,使用 tokenized/synthetic data,严格访问和保留。

15.5 进入 Regression#

Triage -> 最小复现 -> Gold/断言 -> Dataset Snapshot -> CI Gate。


16. OrderFlow 生产蓝图#

16.1 Pools#

api-pool
interactive-worker-pool
batch-worker-pool
high-risk-action-pool
eval/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 hooks

16.3 Degradation#

故障降级
强模型不可用等价 fallback/只读规则/人工
RAG 不可用不做基于规则的写动作
Redis 不可用DB/queue fallback 或拒绝新长 Run
Audit 不可用高风险写 fail closed
Policy 不可用deny/human
Human queue 满排队/告知,不自动批准

16.4 SLO#

退款查询 verified success
确认前错误写 = 0
重复退款 = 0
first meaningful event p95
queue age p95
final-state verification coverage
cost per resolved request

17. Capacity Planning#

17.1 Little’s Law#

concurrency ≈ throughput × average time in system

Agent Run 变长会放大在途状态、连接、队列与 DB 压力。

17.2 Workload Model#

arrival rate by scenario/tenant
steps/model/tool calls per run
service time distribution
token distribution
human wait exclusion/inclusion
burst factor

17.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/Checkpoint
Audit
Business Idempotency
Memory/RAG Canonical
Index Projection
Artifact

定义恢复点/时间。

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/scenario
3. SLO/queue/provider/tool/DB 状态
4. first divergent Span/State
5. 是否有安全/副作用
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 outcomes
Weekly:failure clusters/cost/fallback/human queue
Monthly:model/tool/policy/index drift + dependency updates
Quarterly:DR/security/rollback drill + retention review

19.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 AgentCoreAgent runtime/identity/memory/gateway 等云生产组件组合领域状态/成本验证
LangSmith DeploymentLangGraph 应用部署/持久运行graph runtime/observability业务幂等/安全
TemporalDurable execution长任务/重试/signal模型/Context/Eval
LiteLLM/Cloudflare/Azure AI Gateway多模型 proxy、rate、cache/observability 等统一模型入口领域路由质量
Kubernetesprobe、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#

编号失败示例首要层
O01Admission无 backpressure 过载Gateway/Scheduler
O02Queue不公平/任务饿死Scheduler
O03Lease双 Worker 提交Runtime
O04Checkpoint无法恢复/版本不兼容State Store
O05Model Route能力/合规错误Gateway
O06Retry Storm429 时全体重试Limit/Backoff
O07Cache Leakkey 缺 ACL/tenantCache
O08Migration新旧 schema 不兼容Release
O09Probe依赖抖动导致重启Kubernetes
O10Rollout混用 Manifest 版本Control Plane
O11Costreflection/multi-agent 爆炸Budget
O12Trace Gap无法定位失败Observability
O13Replay Side Effect历史任务重放真实退款Replay Sandbox
O14DR 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 + idempotency
2. Queue/lease/backpressure
3. Checkpoint/outbox/recovery
4. Model Gateway/limit/fallback
5. PostgreSQL/Redis/Index 责任边界
6. Container/probes/graceful shutdown
7. Trace/metrics/audit/cost
8. Release Manifest + Eval CI Gate
9. Shadow/canary/rollback
10. Failure Replay + DR/incident drill

25. 达标检查清单#

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. 面试与架构评审问题#

  1. 同步、流式和 Durable Run 如何选择?
  2. at-least-once Queue 如何避免重复业务动作?
  3. Checkpoint 与业务事务的边界是什么?
  4. Model Gateway 路由为什么不能只看价格和 Benchmark?
  5. Fallback 为什么需要重新计算权限?
  6. Cache key 为什么要包含 ACL 和版本?
  7. Kubernetes readiness/liveness/startup 如何区分?
  8. Agent SLO 为什么要包含 Verified Task Success?
  9. Release Manifest 为什么比单独模型版本重要?
  10. 如何安全 Replay 一次退款失败?
  11. Cost per Run 为什么可能误导?
  12. Region 故障时如何避免重复退款?

27. 参考资料与延伸阅读#

以下资料用于核对生产实践、平台能力与研究方向。托管产品和 SDK 会演进;生产发布需固定版本、区域、配额和数据政策。

官方生产与平台方案#

[S1] Durable Agent Runtime#

[S2] Provider Production Guides#

[S3] Kubernetes Runtime#

[S4] SLO 与 Well-Architected#

[S5] Observability#

[S6] Model Gateway#

[S7] 托管 Agent 平台与 Gateway#

论文与系统研究#

[P1] RouteLLM#

[P2] FrugalGPT#

[P3] AI Agents That Matter#

[P4] vLLM#

[P5] SGLang#

[P6] ServerlessLLM#

[P7] SWE-agent#

[P8] AgentBench#


28. 阶段总结#

AgentOps 的闭环不是“有 Dashboard”,而是:

请求可进入有界队列;
任务可持久化和恢复;
模型/工具可路由、限流、熔断和降级;
状态和副作用可幂等对账;
发布组合有完整 Manifest;
变更先 Eval,再 Shadow/Canary;
失败可收集、最小复现和 Replay;
事故可遏制、回滚、恢复和回归。

一次线上失败的标准处理路径应能明确执行:

查 SLO/告警
-> 定位 Release/Run/first divergent Span
-> 判断安全和业务影响
-> Kill Switch/降级/回滚
-> 对账外部状态
-> 最小复现
-> 修复并加入 Regression
-> Eval Gate
-> Shadow/Canary
-> 监控恢复并完成 Postmortem

能稳定完成这条链路,Agent 才真正从 Demo 变成可长期维护的生产系统。

Agent 生产部署与 AgentOps:从 Demo 到可灰度、可回滚的长期系统
https://jupiter-ws.cn/posts/agent/agentops-production-maintenance/
作者
Jupiter
发布于
2026-04-25
许可协议
CC BY-NC-SA 4.0