一、为什么 Agent 需要专业的部署运维?
Agent 不是普通的 Web 服务。它有状态(记忆系统)、依赖外部 LLM API、需要 GPU 资源、调用链路长——这些特性让它的部署运维比传统服务复杂得多。
传统 Web 服务 vs Agent 服务
传统服务:
┌──────────┐ ┌──────────┐ ┌──────────┐
│ 负载均衡 │────▶│ 无状态 │────▶│ 数据库 │
│ │ │ 实例副本 │ │ │
└──────────┘ └──────────┘ └──────────┘
特点:水平扩展简单,重启无损
Agent 服务:
┌──────────┐ ┌──────────────────┐ ┌──────────┐
│ 负载均衡 │────▶│ Agent 实例 │────▶│ LLM API │
│ │ │ ├─ 记忆系统(有状态)│ ├──────────┤
│ │ │ ├─ 工具注册中心 │ │ 外部工具 │
│ │ │ ├─ 缓存(本地) │ ├──────────┤
│ │ │ └─ 会话上下文 │ │ 向量库 │
│ │ │ │ └──────────┘
└──────────┘ └──────────────────┘
特点:有状态,外部依赖多,重启成本高
部署运维的核心挑战:
|
挑战 |
说明 |
解决方案 |
|---|---|---|
|
有状态 |
记忆、会话上下文不能随意丢失 |
外部化存储 + 优雅关闭 |
|
外部依赖 |
LLM API 不稳定、工具有限流 |
熔断降级 + 重试退避 |
|
资源异构 |
部分 Agent 需要 GPU,部分不需要 |
节点亲和性调度 |
|
版本管理 |
Agent 行为由提示词决定,变化频繁 |
提示词版本化 + A/B 测试 |
|
成本控制 |
LLM 调用费用随流量线性增长 |
配额管理 + 预算告警 |
二、Docker 容器化
# Dockerfile
# 多阶段构建
FROM python:3.11-slim AS builder
WORKDIR /app
# 安装系统依赖
RUN apt-get update && apt-get install -y --no-install-recommends \
gcc \
build-essential \
&& rm -rf /var/lib/apt/lists/*
# 安装 Python 依赖
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# --- 运行阶段 ---
FROM python:3.11-slim
WORKDIR /app
# 运行时依赖(更轻量)
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# 从构建阶段复制
COPY --from=builder /usr/local/lib/python3.11/site-packages /usr/local/lib/python3.11/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin
# 复制应用代码
COPY . .
# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
CMD curl -f http://localhost:8080/health || exit 1
# 暴露端口
EXPOSE 8080
# 非 root 用户运行
RUN useradd -m -u 1000 agent && chown -R agent:agent /app
USER agent
# 启动命令
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "4"]
# docker-compose.yml
version: '3.8'
services:
agent-api:
build: .
image: agent-platform:latest
ports:
- "8080:8080"
environment:
- AGENT_ENV=production
- LLM_API_KEY=${LLM_API_KEY}
- REDIS_URL=redis://redis:6379
- VECTOR_DB_URL=http://vector-db:8000
volumes:
- agent-data:/app/data
- ./config:/app/config:ro
depends_on:
redis:
condition: service_healthy
vector-db:
condition: service_started
deploy:
resources:
limits:
cpus: '2'
memory: 4G
reservations:
cpus: '1'
memory: 2G
restart: unless-stopped
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
- redis-data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 5
deploy:
resources:
limits:
memory: 1G
vector-db:
image: qdrant/qdrant:latest
ports:
- "6333:6333"
volumes:
- vector-data:/qdrant/storage
environment:
- QDRANT_ALLOW_CORS=true
prometheus:
image: prom/prometheus:latest
ports:
- "9090:9090"
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
- prometheus-data:/prometheus
grafana:
image: grafana/grafana:latest
ports:
- "3000:3000"
environment:
- GF_SECURITY_ADMIN_PASSWORD=${GRAFANA_PASSWORD:-admin}
volumes:
- grafana-data:/var/lib/grafana
- ./grafana/dashboards:/etc/grafana/provisioning/dashboards
volumes:
agent-data:
redis-data:
vector-data:
prometheus-data:
grafana-data:
# deployment/container_config.py
class ContainerConfig:
"""
容器配置管理
管理 Agent 在容器中的运行配置
"""
@staticmethod
def get_production_config() -> Dict:
"""生产环境配置"""
return {
"server": {
"host": "0.0.0.0",
"port": 8080,
"workers": 4,
"max_connections": 100,
"keep_alive_timeout": 75,
},
"agent": {
"model": "deepseek-chat",
"temperature": 0.7,
"max_tokens": 4096,
"timeout_seconds": 120,
},
"memory": {
"backend": "redis",
"redis_url": os.getenv("REDIS_URL", "redis://localhost:6379"),
"session_ttl_hours": 24,
"max_sessions_per_user": 10,
},
"cache": {
"enabled": True,
"ttl_seconds": 600,
"max_size_mb": 1024,
},
"rate_limit": {
"enabled": True,
"requests_per_minute": 60,
"tokens_per_minute": 100000,
},
"logging": {
"level": "INFO",
"format": "json",
"output": ["stdout", "file"],
"file_path": "/var/log/agent/app.log",
},
}
三、Kubernetes 编排
# k8s/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: agent-platform
namespace: agent-system
labels:
app: agent-platform
version: v1
spec:
replicas: 3
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1
maxUnavailable: 0 # 零停机更新
selector:
matchLabels:
app: agent-platform
template:
metadata:
labels:
app: agent-platform
version: v1
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8080"
prometheus.io/path: "/metrics"
spec:
containers:
- name: agent
image: registry.example.com/agent-platform:v1.2.3
imagePullPolicy: Always
ports:
- containerPort: 8080
protocol: TCP
env:
- name: AGENT_ENV
value: "production"
- name: LLM_API_KEY
valueFrom:
secretKeyRef:
name: llm-secrets
key: api-key
- name: REDIS_URL
value: "redis://redis-service:6379"
- name: VECTOR_DB_URL
value: "http://vector-db-service:8000"
resources:
requests:
cpu: "1"
memory: "2Gi"
limits:
cpu: "2"
memory: "4Gi"
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
failureThreshold: 3
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 10
periodSeconds: 5
timeoutSeconds: 3
volumeMounts:
- name: config
mountPath: /app/config
readOnly: true
- name: data
mountPath: /app/data
volumes:
- name: config
configMap:
name: agent-config
- name: data
persistentVolumeClaim:
claimName: agent-data-pvc
---
apiVersion: v1
kind: Service
metadata:
name: agent-service
namespace: agent-system
spec:
selector:
app: agent-platform
ports:
- port: 80
targetPort: 8080
protocol: TCP
type: ClusterIP
# k8s/hpa.yaml - 自动扩缩容
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: agent-hpa
namespace: agent-system
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: agent-platform
minReplicas: 2
maxReplicas: 20
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Resource
resource:
name: memory
target:
type: Utilization
averageUtilization: 80
- type: Pods
pods:
metric:
name: agent_request_duration_ms
target:
type: AverageValue
averageValue: 2000 # 平均响应时间超过2秒就扩容
behavior:
scaleDown:
stabilizationWindowSeconds: 300
policies:
- type: Percent
value: 50
periodSeconds: 60
scaleUp:
stabilizationWindowSeconds: 0
policies:
- type: Percent
value: 100
periodSeconds: 15
- type: Pods
value: 4
periodSeconds: 15
selectPolicy: Max
# k8s/pdb.yaml - Pod 中断预算
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: agent-pdb
namespace: agent-system
spec:
minAvailable: 2 # 至少保持2个 Pod 可用
selector:
matchLabels:
app: agent-platform
# deployment/k8s_operator.py
class AgentOperator:
"""
Agent Kubernetes Operator
自定义控制器,管理 Agent 的生命周期
"""
def __init__(self, k8s_client):
self.client = k8s_client
self.warmup_pool = WarmupPool()
async def handle_scaling_event(self, event: Dict):
"""处理扩缩容事件"""
action = event.get("action")
replicas = event.get("replicas", 1)
if action == "scale_up":
await self._scale_up(replicas)
elif action == "scale_down":
await self._scale_down(replicas)
async def _scale_up(self, target_replicas: int):
"""扩容"""
# 1. 获取当前副本数
current = await self._get_current_replicas()
# 2. 计算需要新增的数量
needed = target_replicas - current
if needed <= 0:
return
# 3. 预热新 Pod(加载模型、填充缓存)
for i in range(needed):
pod_name = f"agent-warmup-{uuid.uuid4()[:8]}"
# 创建预热 Pod
await self._create_warmup_pod(pod_name)
# 等待预热完成
await self.warmup_pool.warm_up(pod_name)
# 加入生产流量
await self._add_to_service(pod_name)
async def _scale_down(self, target_replicas: int):
"""缩容"""
# 1. 优雅关闭
# - 停止接收新请求
# - 等待正在处理的请求完成
# - 持久化内存中的状态
# - 关闭连接
current = await self._get_current_replicas()
to_remove = current - target_replicas
if to_remove <= 0:
return
# 2. 选择要移除的 Pod(优先移除流量最小的)
candidates = await self._get_drain_candidates(to_remove)
for pod in candidates:
await self._graceful_shutdown(pod)
async def _graceful_shutdown(self, pod_name: str):
"""优雅关闭 Pod"""
# 1. 从 Service 摘除
await self._remove_from_service(pod_name)
# 2. 等待现有请求完成(最多30秒)
await asyncio.sleep(30)
# 3. 持久化内存状态
await self._persist_memory_state(pod_name)
# 4. 关闭连接
await self._close_connections(pod_name)
# 5. 删除 Pod
await self._delete_pod(pod_name)
class WarmupPool:
"""预热池"""
def __init__(self):
self.warm_pods: Set[str] = set()
async def warm_up(self, pod_name: str):
"""预热 Pod"""
# 1. 加载模型
await self._load_model(pod_name)
# 2. 填充常用缓存
await self._populate_cache(pod_name)
# 3. 建立连接池
await self._establish_connections(pod_name)
# 4. 运行健康检查
healthy = await self._health_check(pod_name)
if healthy:
self.warm_pods.add(pod_name)
async def _load_model(self, pod_name: str):
"""加载模型"""
# 模拟加载时间
await asyncio.sleep(10)
async def _populate_cache(self, pod_name: str):
"""填充缓存"""
# 从 Redis 加载热门缓存
pass
async def _establish_connections(self, pod_name: str):
"""建立连接"""
# 预连接到 LLM API、数据库等
pass
四、CI/CD 流水线
# .github/workflows/deploy.yml
name: Agent CI/CD Pipeline
on:
push:
branches: [main, develop]
paths:
- 'src/**'
- 'config/**'
- 'Dockerfile'
- 'requirements.txt'
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install pytest pytest-cov flake8 mypy
- name: Lint
run: flake8 src/ tests/
- name: Type check
run: mypy src/
- name: Run unit tests
run: pytest tests/unit/ --cov=src/ --cov-report=xml
- name: Run integration tests
run: pytest tests/integration/ --timeout=120
- name: Upload coverage
uses: codecov/codecov-action@v3
build:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Login to Registry
uses: docker/login-action@v2
with:
registry: registry.example.com
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
- name: Build and push
uses: docker/build-push-action@v4
with:
context: .
push: true
tags: |
registry.example.com/agent-platform:${{ github.sha }}
registry.example.com/agent-platform:latest
cache-from: type=registry,ref=registry.example.com/agent-platform:buildcache
cache-to: type=registry,ref=registry.example.com/agent-platform:buildcache,mode=max
deploy-staging:
needs: build
runs-on: ubuntu-latest
environment: staging
steps:
- uses: actions/checkout@v3
- name: Configure kubectl
uses: azure/setup-kubectl@v3
with:
version: 'latest'
- name: Deploy to staging
run: |
kubectl set image deployment/agent-platform \
agent=registry.example.com/agent-platform:${{ github.sha }} \
-n agent-staging
kubectl rollout status deployment/agent-platform \
-n agent-staging \
--timeout=5m
- name: Run smoke tests
run: |
# 冒烟测试
curl -f http://staging.agent.example.com/health
curl -f http://staging.agent.example.com/api/v1/test
deploy-production:
needs: deploy-staging
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v3
- name: Canary deploy (10%)
run: |
# 金丝雀发布:先升级10%的 Pod
kubectl set image deployment/agent-platform-canary \
agent=registry.example.com/agent-platform:${{ github.sha }} \
-n agent-production
- name: Wait for canary validation
run: sleep 300 # 观察5分钟
- name: Check canary metrics
run: |
# 检查错误率和响应时间
curl -f http://prometheus:9090/api/v1/query?query=...
- name: Full rollout
run: |
kubectl set image deployment/agent-platform \
agent=registry.example.com/agent-platform:${{ github.sha }} \
-n agent-production
kubectl rollout status deployment/agent-platform \
-n agent-production \
--timeout=10m
# deployment/release_manager.py
class ReleaseManager:
"""
发布管理器
管理 Agent 的版本发布、回滚和金丝雀发布
"""
def __init__(self):
self.releases: Dict[str, Release] = {}
self.canary_traffic = 0.1 # 金丝雀流量比例
async def create_release(self, version: str,
artifacts: Dict) -> 'Release':
"""创建发布"""
release = Release(
version=version,
artifacts=artifacts,
status="created",
created_at=datetime.now(),
)
self.releases[version] = release
return release
async def canary_deploy(self, release_version: str):
"""金丝雀发布"""
release = self.releases.get(release_version)
if not release:
raise ValueError(f"Release {release_version} not found")
# 1. 部署金丝雀实例
canary_replicas = max(1, int(self._get_total_replicas() * self.canary_traffic))
await self._deploy_canary(release, canary_replicas)
# 2. 路由少量流量到金丝雀
await self._route_canary_traffic(self.canary_traffic)
# 3. 监控金丝雀指标
monitoring_result = await self._monitor_canary(timeout_minutes=30)
if monitoring_result.passed:
# 4. 全量发布
await self._full_rollout(release)
release.status = "active"
else:
# 5. 回滚
await self._rollback_canary()
release.status = "rolled_back"
return release
async def rollback(self, target_version: str):
"""回滚到指定版本"""
# 1. 记录回滚原因
rollback_reason = await self._detect_rollback_reason()
# 2. 切换到旧版本镜像
await self._switch_image(target_version)
# 3. 等待稳定
await asyncio.sleep(60)
# 4. 验证回滚成功
healthy = await self._verify_health()
return {
"rolled_back_to": target_version,
"reason": rollback_reason,
"success": healthy,
}
async def _monitor_canary(self, timeout_minutes: int) -> 'MonitoringResult':
"""监控金丝雀"""
start = time.time()
result = MonitoringResult()
while time.time() - start < timeout_minutes * 60:
# 检查关键指标
metrics = await self._get_canary_metrics()
# 错误率超过基线
if metrics.error_rate > 0.01: # 1% 错误率阈值
result.passed = False
result.fail_reason = f"Error rate too high: {metrics.error_rate:.2%}"
return result
# 响应时间超过基线
if metrics.p95_latency > 5000: # 5秒阈值
result.passed = False
result.fail_reason = f"Latency too high: {metrics.p95_latency}ms"
return result
await asyncio.sleep(30) # 每30秒检查一次
result.passed = True
return result
五、生产环境监控告警
# prometheus.yml
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
- "alerts.yml"
scrape_configs:
- job_name: 'agent'
kubernetes_sd_configs:
- role: pod
namespaces:
names: ['agent-system']
relabel_configs:
- source_labels: [__meta_kubernetes_pod_label_app]
regex: agent-platform
action: keep
- source_labels: [__address__]
action: replace
regex: ([^:]+)(?::\d+)?
replacement: $1:8080
target_label: __address__
# alerts.yml
groups:
- name: agent-alerts
rules:
- alert: HighErrorRate
expr: rate(agent_errors_total[5m]) / rate(agent_requests_total[5m]) > 0.05
for: 5m
labels:
severity: critical
annotations:
summary: "Agent 错误率过高"
description: "错误率已达到 {{ $value | humanizePercentage }},超过 5% 阈值"
- alert: HighLatency
expr: histogram_quantile(0.95, rate(agent_request_duration_seconds_bucket[5m])) > 5
for: 5m
labels:
severity: warning
annotations:
summary: "Agent 响应时间过长"
description: "P95 响应时间已达 {{ $value }}s,超过 5s 阈值"
- alert: LLMApiFailure
expr: rate(llm_api_errors_total[5m]) > 0.1
for: 2m
labels:
severity: critical
annotations:
summary: "LLM API 调用失败率过高"
description: "LLM API 错误率 {{ $value | humanizePercentage }}"
- alert: MemoryFull
expr: agent_memory_usage_bytes / agent_memory_limit_bytes > 0.85
for: 10m
labels:
severity: warning
annotations:
summary: "Agent 内存即将耗尽"
description: "内存使用率 {{ $value | humanizePercentage }}"
- alert: CostSpike
expr: increase(llm_cost_total[1h]) > 100
for: 5m
labels:
severity: warning
annotations:
summary: "LLM 调用费用激增"
description: "过去1小时费用增加了 ${{ $value }}"
- alert: CacheHitRateDrop
expr: rate(cache_hits_total[30m]) / rate(cache_requests_total[30m]) < 0.3
for: 15m
labels:
severity: warning
annotations:
summary: "缓存命中率下降"
description: "缓存命中率降至 {{ $value | humanizePercentage }}"
# deployment/monitoring.py
class ProductionMonitor:
"""
生产环境监控
集成指标采集、告警、仪表盘
"""
def __init__(self, agent_id: str):
self.agent_id = agent_id
self.metrics = MetricsCollector()
self.alerts = AlertManager()
self.dashboard = GrafanaDashboard()
async def collect_metrics(self):
"""采集生产指标"""
while True:
# 业务指标
self.metrics.set_gauge("agent.active_sessions",
await self._count_active_sessions())
self.metrics.set_gauge("agent.queue_depth",
await self._get_queue_depth())
# 资源指标
self.metrics.set_gauge("agent.memory_usage_mb",
self._get_memory_usage())
self.metrics.set_gauge("agent.cpu_percent",
self._get_cpu_usage())
# LLM 指标
self.metrics.increment_counter("llm.requests_total",
self._get_llm_requests())
self.metrics.record_histogram("llm.latency_ms",
self._get_llm_latency())
# 成本指标
cost = self._calculate_running_cost()
self.metrics.set_gauge("cost.total_usd", cost)
await asyncio.sleep(15) # 15秒采集一次
async def check_alerts(self):
"""检查告警条件"""
while True:
snapshot = self.metrics.get_metrics_snapshot()
# 检查各项指标
checks = [
self._check_error_rate(snapshot),
self._check_latency(snapshot),
self._check_memory(snapshot),
self._check_cost(snapshot),
self._check_cache_hit_rate(snapshot),
]
for check in checks:
alert = await check
if alert:
await self.alerts.send_alert(alert)
await asyncio.sleep(30) # 30秒检查一次
async def _check_error_rate(self, snapshot: Dict) -> Optional[Alert]:
"""检查错误率"""
total = snapshot["counters"].get("interactions.total", 0)
errors = snapshot["counters"].get("interactions.failed", 0)
if total > 100 and errors / total > 0.05:
return Alert(
severity="critical",
title="High Error Rate",
message=f"Error rate: {errors/total:.2%}",
metric_value=errors/total,
threshold=0.05,
)
return None
async def _check_cost(self, snapshot: Dict) -> Optional[Alert]:
"""检查成本"""
hourly_cost = snapshot["gauges"].get("cost.hourly_usd", 0)
if hourly_cost > 50: # 每小时超过50美元
return Alert(
severity="warning",
title="Cost Spike",
message=f"Hourly cost: ${hourly_cost:.2f}",
metric_value=hourly_cost,
threshold=50,
)
return None
class AlertManager:
"""告警管理器"""
def __init__(self):
self.channels = [
SlackChannel(webhook_url=os.getenv("SLACK_WEBHOOK")),
EmailChannel(smtp_config=SMTPConfig(...)),
PagerDutyChannel(integration_key=os.getenv("PAGERDUTY_KEY")),
]
async def send_alert(self, alert: 'Alert'):
"""发送告警"""
for channel in self.channels:
try:
await channel.send(alert)
except Exception as e:
print(f"Failed to send alert via {channel.name}: {e}")
# 记录告警历史
await self._save_alert_history(alert)
async def escalate(self, alert: 'Alert'):
"""升级告警"""
if alert.severity == "critical" and alert.duration_minutes > 15:
# 通知值班工程师
await self._page_oncall(alert)
if alert.duration_minutes > 60:
# 通知团队负责人
await self._notify_manager(alert)
六、本讲坑位
|
# |
坑位 |
现象 |
解决方案 |
|---|---|---|---|
|
1 |
冷启动缓慢 |
新 Pod 首次请求超时(模型加载、缓存预热) |
预热池 + 就绪探针延迟 |
|
2 |
有状态迁移失败 |
缩容时丢失内存中的会话状态 |
外部化存储 + 优雅关闭钩子 |
|
3 |
金丝雀污染全局 |
金丝雀实例的错误影响了共享资源(如数据库) |
读写分离 + 资源隔离 |
|
4 |
配置漂移 |
不同环境的配置不一致导致行为差异 |
GitOps + 配置校验 |
|
5 |
LLM API 限流 |
扩容后并发请求超限,被 LLM 提供商限流 |
客户端限流 + 排队机制 |
|
6 |
版本兼容性 |
新 Agent 版本无法读取旧版本的序列化记忆 |
向前兼容 + 数据迁移脚本 |
七、下讲预告
第10讲(完结篇):Agent 的工程化落地——架构演进、团队协作与未来展望
我们将深入探讨:
- 从 MVP 到生产级的架构演进路线
- Agent 开发团队的组建与协作模式
- Agent 效果的评估体系(Eval)
- 行业落地案例分析
- Agent 技术的未来趋势
🧰 博主工具箱
- JSON 格式化:zz365.top 的 JSON 工具整理 Kubernetes 资源配置和 Prometheus 告警规则
- Base64 编解码:解码 Kubernetes Secret 中的敏感配置
- 文本差异对比:对比不同版本的 Deployment 配置差异
- 正则表达式测试:验证日志采集和告警规则的匹配模式
更多效率工具,欢迎访问我的个人主页:zz365.top
701




被折叠的 条评论
为什么被折叠?



