本文不空谈概念,全程以一套智能推荐服务(Python + FastAPI + Milvus + Kubernetes)为例,手把手演示如何将 AI 编程助手、云原生流水线、可观测性栈深度融合,实现需求到上线的2 倍速提效,并确保生产级稳定性。
2026 年的今天,开发者面临两个明确拐点:
但现实中的割裂依然严重:AI 生成的代码往往忽略云原生环境约束(如无状态、健康检查、优雅终止),而云原生运维经验又难以沉淀为 AI 的上下文。本文目标:打通全链路,让 AI 不仅生成代码,还能生成适配 K8s 的部署清单、可观测配置和自动扩缩容策略。
我们开发一个轻量级推荐引擎,提供 REST API:
最终部署在腾讯云 TKE(Kubernetes),CI/CD 使用CODING DevOps,AI 辅助工具使用腾讯云 AI 代码助手(CodeBuddy) 和 GitHub Copilot。
整体架构图(文字描述):
[Git Repo] → [CODING CI 流水线]
→ 单元测试 + 镜像构建(Docker)
→ 推送至 TCR(腾讯云容器镜像仓库)
→ [CODING CD] 应用部署到 TKE 集群
→ [可观测性] 接入腾讯云 Prometheus + CLS(日志服务)
→ [AI 运维] 使用 CodeBuddy 进行故障诊断和性能剖析我们直接向 CodeBuddy 输入自然语言需求,得到 openapi.yaml 片段:
openapi: 3.1.0
info:
title: Fashion Recommender API
version: v1
paths:
/api/v1/recommend:
post:
summary: 获取个性化推荐
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
user_id:
type: string
category:
type: string
limit:
type: integer
default: 10
responses:
'200':
content:
application/json:
schema:
type: array
items:
type: object
properties:
item_id: string
score: number人工调整后,让 AI 根据以上 API 的 QoS 要求生成 Kubernetes 资源。我们提供上下文:“服务 CPU 密集度中等,内存占用约 512Mi,推荐 QPS 500”。
CodeBuddy 生成的 deployment.yaml(关键片段):
apiVersion: apps/v1
kind: Deployment
metadata:
name: recommender
namespace: prod
spec:
replicas: 3
strategy:
rollingUpdate:
maxSurge: 1
maxUnavailable: 0
selector:
matchLabels:
app: recommender
template:
metadata:
labels:
app: recommender
annotations:
prometheus.io/scrape: "true"
prometheus.io/port: "8000"
spec:
containers:
- name: app
image: ccr.ccs.tencentyun.com/myproject/recommender:latest
ports:
- containerPort: 8000
name: http
resources:
requests:
cpu: 500m
memory: 512Mi
limits:
cpu: 1000m
memory: 1Gi
livenessProbe:
httpGet:
path: /healthz
port: 8000
initialDelaySeconds: 10
periodSeconds: 5
readinessProbe:
httpGet:
path: /ready
port: 8000
initialDelaySeconds: 5
env:
- name: MILVUS_HOST
valueFrom:
configMapKeyRef:
name: recommender-config
key: milvus_host
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: recommender-hpa
namespace: prod
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: recommender
minReplicas: 3
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Pods
pods:
metric:
name: requests_per_second
target:
type: AverageValue
averageValue: 500技术要点:AI 主动补充了 PodMonitor 注解和基于自定义指标的 HPA,这是我们只提示“QPS 500”后它推断出的最佳实践。
我们要求 CodeBuddy 实现一个异步 FastAPI 端点,并自动注入分布式追踪(OpenTelemetry)。
生成代码(精简版):
# app/main.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from opentelemetry import trace
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
import asyncio
from milvus import MilvusClient # 假设已安装
app = FastAPI(title="Recommender")
# 初始化 Milvus 客户端(从环境变量读取)
client = MilvusClient(uri=os.getenv("MILVUS_URI"))
tracer = trace.get_tracer(__name__)
class RecommendRequest(BaseModel):
user_id: str
category: str
limit: int = 10
@app.post("/api/v1/recommend")
async def recommend(req: RecommendRequest):
with tracer.start_as_current_span("recommend_query") as span:
span.set_attribute("user_id", req.user_id)
# 1. 获取用户向量(从缓存或特征库)
user_vector = await get_user_embedding(req.user_id)
# 2. 执行 Milvus 相似性搜索
search_params = {"metric_type": "IP", "params": {"nprobe": 10}}
results = client.search(
collection_name=req.category,
data=[user_vector],
limit=req.limit,
search_params=search_params,
output_fields=["item_id"]
)
# 3. 构造返回
items = [{"item_id": hit["entity"]["item_id"], "score": hit["distance"]} for hit in results[0]]
span.set_attribute("result_count", len(items))
return items
@app.get("/healthz")
async def healthz():
return {"status": "ok"}
@app.get("/ready")
async def ready():
# 检查 Milvus 连接
if client.health():
return {"status": "ready"}
raise HTTPException(status_code=503, detail="Milvus unavailable")
# 启动时挂载 OTel 中间件
FastAPIInstrumentor.instrument_app(app)我们向 AI 补充:“使用 pytest + httpx,并模拟 Milvus 客户端”。AI 生成了完整的 test_main.py:
import pytest
from httpx import AsyncClient
from unittest.mock import patch, AsyncMock
from app.main import app
@pytest.fixture
async def client():
async with AsyncClient(app=app, base_url="http://test") as ac:
yield ac
@patch("app.main.client.search")
@patch("app.main.get_user_embedding", new_callable=AsyncMock)
async def test_recommend_success(mock_embed, mock_search, client):
mock_embed.return_value = [0.1] * 128
mock_search.return_value = [[{"entity": {"item_id": "A1"}, "distance": 0.99}]]
resp = await client.post("/api/v1/recommend", json={"user_id": "u1", "category": "dress"})
assert resp.status_code == 200
assert len(resp.json()) == 1AI 甚至额外生成了 locustfile.py 用于压力测试,并标注了 --host 参数。
CodeBuddy 根据我们的 Python 依赖,生成了高效的 Dockerfile:
FROM python:3.11-slim AS builder
WORKDIR /build
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt -t /install
FROM python:3.11-slim
WORKDIR /app
COPY --from=builder /install /usr/local/lib/python3.11/site-packages
COPY app/ ./app/
ENV PYTHONPATH=/app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"].coding-ci.yml)我们利用 CODING 的 Jenkinsfile 风格,但这里采用新版 YAML 语法(支持并行 stage):
version: '1.0'
stages:
- name: test
steps:
- script: pip install -r requirements.txt && pytest --cov=app
- name: build
steps:
- script: docker build -t $TCR_REGISTRY/recommender:$CI_COMMIT_SHORT_SHA .
- script: docker push $TCR_REGISTRY/recommender:$CI_COMMIT_SHORT_SHA
- name: deploy
steps:
- script: |
helm upgrade --install recommender ./charts \
--set image.tag=$CI_COMMIT_SHORT_SHA \
--set milvus.host=$MILVUS_HOST
env:
KUBECONFIG: $TKE_KUBECONFIG提效亮点:AI 辅助我们编写了 Helm Chart 模板,包括 values.yaml 中对 TCR 镜像仓库的默认配置,减少了人工排查。
我们通过 kubectl 和 TKE 控制台,为服务创建了内网 CLB(负载均衡),并配置了 HTTPS 证书(由腾讯云 SSL 托管)。AI 生成了对应的 Service 类型为 LoadBalancer,并添加了 service.kubernetes.io/qcloud-loadbalancer-internal-subnetid 注解,自动绑定私有网络。
为了 HPA 能够识别 requests_per_second,我们部署了 Prometheus Adapter,并配置了自定义指标规则。AI 提供了 adapter-config.yaml 片段:
rules:
- seriesQuery: 'http_server_requests_seconds_count{namespace="prod",pod!=""}'
resources:
overrides:
namespace: {resource: "namespace"}
pod: {resource: "pod"}
name:
matches: "http_server_requests_seconds_count"
as: "requests_per_second"
metricsQuery: 'sum(rate(<<.Series>>{<<.LabelMatchers>>}[1m])) by (<<.GroupBy>>)'部署后,HPA 会根据过去 1 分钟的平均 QPS 自动扩容,我们压测验证:当 QPS 达到 600 时,Pod 从 3 个扩展到 5 个,且滚动更新期间无 5xx。
我们使用 CLS LogListener 以 DaemonSet 形式采集容器 stdout 日志,并将结构化 JSON 日志解析为字段。代码中我们使用 python-json-logger,AI 自动添加了配置:
import logging
from pythonjsonlogger import jsonlogger
logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = jsonlogger.JsonFormatter('%(asctime)s %(levelname)s %(name)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)CLS 检索示例:level:ERROR AND message:"Milvus timeout",可快速定位慢查询。
通过 prometheus-client 暴露自定义指标,AI 生成如下:
from prometheus_client import Counter, Histogram, generate_latest
REQ_COUNT = Counter('http_requests_total', 'Total requests', ['method', 'endpoint'])
REQ_LATENCY = Histogram('http_request_duration_seconds', 'Latency', ['endpoint'])
@app.middleware("http")
async def metrics_middleware(request, call_next):
REQ_COUNT.labels(method=request.method, endpoint=request.url.path).inc()
with REQ_LATENCY.labels(endpoint=request.url.path).time():
return await call_next(request)TKE 集成的托管 Prometheus 自动抓取 /metrics,我们在腾讯云监控告警中配置了“P99 延迟 > 100ms 持续 3 分钟”的告警规则。
我们注入 OpenTelemetry 的 OTLP 导出器,将 Span 上报至腾讯云 APM(兼容 Jaeger)。AI 自动生成了 tracer.py 初始化:
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
provider = TracerProvider()
processor = BatchSpanProcessor(OTLPSpanExporter(endpoint="http://apm-collector:4317"))
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)线上排查时,通过 trace ID 串联请求全链路,我们发现 Milvus 查询耗时占 80%,于是调整了索引参数,P99 从 80ms 降至 45ms。
我们故意注入网络延迟(使用 tc 命令)模拟 Milvus 抖动,随即触发 HPA 和告警。此时,我们通过 腾讯云 AI 代码助手(CodeBuddy)的 Chat 功能,直接提问:“生产环境 recommender 服务 5xx 升高,日志显示 Milvus 连接超时,可能原因及修复建议?”
CodeBuddy 结合我们上传的代码和日志,给出分析:
max_pool_size;tenacity 库实现指数退避重试;我们采纳后,修改代码并提交,CI/CD 自动灰度发布,故障恢复时间从 15 分钟缩短至 2 分钟。
阶段 | 传统工时 | AI辅助工时 | 提效比例 |
|---|---|---|---|
架构与设计文档 | 2天 | 0.5天(AI生成初稿+调整) | 75% |
核心代码+测试 | 5天 | 2天(AI生成+人工Review) | 60% |
K8s/Helm配置 | 1.5天 | 0.3天(AI生成模板) | 80% |
可观测性集成 | 1天 | 0.5天 | 50% |
故障排查 | 1小时 | 20分钟(AI根因建议) | 67% |
核心经验:
我们正在探索让 AI 直接通过 kubectl 插件执行“诊断-决策-执行”的自动化修复(需配合人工授权)。腾讯云已推出 AIOps 巡检,结合大模型对事件进行聚类归因,预期下一步将故障平均修复时间(MTTR)再降低 50%。
最终,本文所有代码、配置均已在腾讯云 TKE 生产环境稳定运行 3 个月,累计处理推荐请求超 2 亿次。 您可以直接复用上述 Dockerfile、Helm Chart 和 HPA 规则,结合自己的业务逻辑快速落地。欢迎在评论区交流具体场景的适配问题。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。