本课学习LLM应用的部署方案。从开发到生产,需要选择合适的架构(单体/微服务/Serverless)、编写生产级API、容器化部署。
第32课: 部署方案
├── 三种架构
│ ├── Monolith: 单体(简单/快速)
│ ├── Microservice: 微服务(灵活/复杂)
│ └── Serverless: 无服务器(按需/冷启动)
├── FastAPI模板
│ ├── 异步API
│ ├── 健康检查
│ └── 错误处理
└── Docker
├── Dockerfile
├── docker-compose
└── 健康检查/重启策略
# 三种部署架构
from dataclasses import dataclass
from typing import Dict, List
@dataclass
class DeploymentConfig:
architecture: str # monolith/microservice/serverless
replicas: int = 1
cpu_limit: str = "1"
memory_limit: str = "2Gi"
gpu_required: bool = False
autoscaling: bool = False
min_replicas: int = 1
max_replicas: int = 10
target_cpu_percent: int = 70
# 单体架构
@dataclass
class MonolithConfig(DeploymentConfig):
architecture: str = "monolith"
port: int = 8000
workers: int = 4
# 微服务架构
@dataclass
class MicroserviceConfig(DeploymentConfig):
architecture: str = "microservice"
services: Dict[str, dict] = None # name -> config
api_gateway: str = "nginx"
# Serverless架构
@dataclass
class ServerlessConfig(DeploymentConfig):
architecture: str = "serverless"
provider: str = "aws_lambda"
runtime: str = "python3.11"
timeout_seconds: int = 30
memory_mb: int = 512
cold_start_concurrency: int = 5 # 预热实例
def compare_architectures() -> str:
return """架构对比:
| 特性 | 单体 | 微服务 | Serverless |
|-----------|---------|-----------|-----------|
| 部署复杂度 | 低 | 高 | 低 |
| 扩展性 | 有限 | 好 | 自动 |
| 冷启动 | 无 | 无 | 有 |
| 成本模式 | 固定 | 固定+弹性 | 按调用 |
| 适用规模 | 小型 | 中大型 | 间歇/流量波动 |"""✅ 验证通过:三种架构的配置类完整定义,包含资源限制和扩展策略
# FastAPI生产模板
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional, List
import time
import json
app = FastAPI(title="LLM App API", version="1.0.0")
# CORS
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
# 请求模型
class ChatRequest(BaseModel):
message: str
model: str = "gpt-4o-mini"
temperature: float = 0.7
max_tokens: int = 1000
stream: bool = False
class ChatResponse(BaseModel):
response: str
model: str
tokens_used: int
latency_ms: float
# 健康检查
@app.get("/health")
def health_check():
return {"status": "healthy", "timestamp": time.time()}
# 聊天接口
@app.post("/v1/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
start = time.time()
try:
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model=request.model,
messages=[{"role": "user", "content": request.message}],
temperature=request.temperature,
max_tokens=request.max_tokens,
)
latency = (time.time() - start) * 1000
return ChatResponse(
response=response.choices[0].message.content or "",
model=request.model,
tokens_used=response.usage.total_tokens if response.usage else 0,
latency_ms=latency,
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# 运行: uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4✅ 验证通过:FastAPI模板包含CORS、健康检查、聊天接口和错误处理
# Docker容器化
# Dockerfile
# FROM python:3.11-slim
# WORKDIR /app
# COPY requirements.txt .
# RUN pip install --no-cache-dir -r requirements.txt
# COPY . .
# EXPOSE 8000
# CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]
# docker-compose.yml 示例
docker_compose = """
version: "3.8"
services:
llm-api:
build: .
ports:
- "8000:8000"
environment:
- OPENAI_API_KEY=${OPENAI_API_KEY}
deploy:
resources:
limits:
cpus: "2"
memory: 4G
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 30s
timeout: 10s
retries: 3
restart: unless-stopped
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
- redis-data:/data
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf
depends_on:
- llm-api
volumes:
redis-data:
"""
class DockerManager:
"""Docker管理工具"""
def __init__(self, compose_path="docker-compose.yml"):
self.compose_path = compose_path
def build(self):
return f"docker-compose -f {self.compose_path} build"
def up(self, detach=True):
cmd = f"docker-compose -f {self.compose_path} up"
if detach: cmd += " -d"
return cmd
def down(self):
return f"docker-compose -f {self.compose_path} down"
def logs(self, service=None, tail=100):
cmd = f"docker-compose -f {self.compose_path} logs --tail={tail}"
if service: cmd += f" {service}"
return cmd
def scale(self, service, replicas):
return f"docker-compose -f {self.compose_path} up -d --scale {service}={replicas}"✅ 验证通过:Docker配置包含多服务编排、健康检查和资源限制
| 架构 | 部署复杂度 | 扩展性 | 冷启动 | 成本模式 |
|---|---|---|---|---|
| 单体 | 低 | 有限 | 无 | 固定 |
| 微服务 | 高 | 好 | 无 | 固定+弹性 |
| Serverless | 低 | 自动 | 有 | 按调用 |
# 挑战: 构建一键部署脚本
# - 自动构建Docker镜像
# - 健康检查等待就绪
# - 滚动更新零停机实现蓝绿部署——两套环境切换
生产环境部署不只是"把代码放到服务器上"。需要考虑高可用、自动扩展、故障恢复、安全隔离等多个维度。
| 组件 | 配置 | 作用 | 推荐值 |
|---|---|---|---|
| Uvicorn | workers | 并发工作进程 | CPU核心数×2+1 |
| Uvicorn | timeout-keep-alive | 连接保活超时 | 5s |
| Nginx | proxy_read_timeout | 后端读取超时 | 60s |
| Nginx | client_max_body_size | 请求体大小限制 | 10M |
| Redis | maxmemory | 缓存内存限制 | 512mb |
| Docker | memory limit | 容器内存限制 | 2Gi |
| Docker | cpu limit | 容器CPU限制 | 2 cores |
生产环境需要自动化运维来减少人工干预:
┌──────────────────────────────────────┐ │ 生产网络架构 ├──────────────────────────────────────┤ │ CDN / CloudFlare (静态资源+DDoS防护) ├──────────────────────────────────────┤ │ Load Balancer (Nginx/ALB) │ ├── /v1/chat → LLM API Service │ ├── /v1/search → Search Service │ └── /health → Health Check ├──────────────────────────────────────┤ │ API Service (FastAPI × N replicas) │ ├── 认证中间件 (API Key / JWT) │ ├── 速率限制 (Redis) │ └── 语义缓存 (Redis + Embedding) ├──────────────────────────────────────┤ │ Data Layer │ ├── PostgreSQL (用户/配置) │ ├── Redis (缓存/会话) │ └── Vector DB (知识库) └──────────────────────────────────────┘
生产部署的安全配置不容忽视: