【架构实战】AI网关设计:流量治理、内容安全与可观测性
> **本文是「架构实战·第二季」第二十篇**。上一篇我们讲了 LLM 评测,本篇回到架构层——AI 网关的工程实现。 --- ## 引子:网关挂了,全公司 LLM 应用都停了 去年双 11 凌晨 1 点,告警: ``` [CRITICAL] AI 网关连接池耗尽,新请求全部 502 ``` 排查 30 分钟才定位:是上游一个 LLM 服务变慢,所有连接被占,新请求全 502。**而下游 5 个业务都受影响。** 教训是:AI 网关必须有完整的"自我保护"机制——限流、熔断、降级、隔离,缺一不可。 --- ## 一、AI 网关的核心职责 ### 1.1 五大职责 ``` ┌─────────────────────────────────────┐ │ AI 网关 │ │ │ │ 1. 流量治理(限流、熔断、降级) │ │ 2. 内容安全(输入/输出过滤) │ │ 3. 协议适配(OpenAI / Anthropic) │ │ 4. 成本控制(Token 预算、计费) │ │ 5. 可观测(日志、Trace、指标) │ └─────────────────────────────────────┘ ``` ### 1.2 与传统 API 网关的区别 | 维度 | 传统 API 网关 | AI 网关 | |------|-------------|---------| | 协议 | HTTP/REST | OpenAI 兼容 + SSE | | 限流 | QPS | Token/min | | 鉴权 | OAuth/JWT | + API Key 用量限制 | | 路由 | URL | + 模型路由 | | 降级 | 503 | 自动切备模型 | | 计费 | 请求数 | Token 数 | | 内容检查 | 不需要 | 必选 | | 缓存 | 不常见 | 重要 | --- ## 二、流量治理 ### 2.1 Token 限流 ```python class TokenRateLimiter: """基于 token 的滑动窗口限流""" def __init__(self, redis_client): self.redis = redis_client def check(self, key: str, tokens: int, limit_per_min: int) -> bool: """ 滑动窗口算法 key: 限流维度(如 user_id, business, model) tokens: 预估本次请求的 token 数 limit_per_min: 每分钟 token 上限 """ now = time.time() window_start = now - 60 # 1 分钟窗口 # Lua 脚本保证原子性 lua_script = """ local key = KEYS[1] local now = tonumber(ARGV[1]) local window_start = tonumber(ARGV[2]) local tokens = tonumber(ARGV[3]) local limit = tonumber(ARGV[4]) -- 清理窗口外的记录 redis.call('ZREMRANGEBYSCORE', key, 0, window_start) -- 当前窗口内总 token local used = 0 local records = redis.call('ZRANGE', key, 0, -1, 'WITHSCORES') for i = 2, #records, 2 do used = used + tonumber(records[i]) end if used + tokens > limit then return 0 end -- 记录本次 redis.call('ZADD', key, now, now .. ':' .. tokens) redis.call('EXPIRE', key, 60) return 1 """ result = self.redis.eval( lua_script, 1, f"ratelimit:token:{key}", now, window_start, tokens, limit_per_min ) return result == 1 ``` ### 2.2 多级限流 ```python class MultiLevelLimiter: def check(self, user_id, business, model, tokens): # 1. 用户级 if not self.user_limiter.check(f"user:{user_id}", tokens, USER_LIMIT): return LimiterResult(blocked="user") # 2. 业务级 if not self.business_limiter.check(f"biz:{business}", tokens, BIZ_LIMIT): return LimiterResult(blocked="business") # 3. 模型级(避免单模型被打爆) if not self.model_limiter.check(f"model:{model}", tokens, MODEL_LIMIT): return LimiterResult(blocked="model") # 4. 全局级 if not self.global_limiter.check("global", tokens, GLOBAL_LIMIT): return LimiterResult(blocked="global") return LimiterResult(allowed=True) ``` ### 2.3 熔断 ```python class CircuitBreaker: """断路器:上游失败率超阈值时自动熔断""" def __init__(self, model: str): self.model = model self.failure_count = 0 self.success_count = 0 self.state = "closed" # closed / open / half_open self.opened_at = None self.failure_threshold = 10 self.recovery_timeout = 30 # 30s 后尝试半开 def call(self, fn, *args, **kwargs): if self.state == "open": if time.time() - self.opened_at > self.recovery_timeout: self.state = "half_open" else: raise CircuitOpenError(f"{self.model} circuit open") try: result = fn(*args, **kwargs) self.on_success() return result except Exception as e: self.on_failure() raise def on_success(self): if self.state == "half_open": self.state = "closed" self.failure_count = 0 self.success_count += 1 def on_failure(self): self.failure_count += 1 if self.failure_count >= self.failure_threshold: self.state = "open" self.opened_at = time.time() logger.error(f"Circuit opened: {self.model}") ``` ### 2.4 降级 ```python class FallbackChain: """降级链:主模型失败 → 备用模型 → 兜底""" def __init__(self): self.chain = [ ("gpt-4o", self.call_openai), ("claude-3.5-sonnet", self.call_anthropic), ("qwen-72b-local", self.call_local), ("gpt-4o-mini", self.call_cheap_model), # 终极兜底 ] self.breakers = {model: CircuitBreaker(model) for model, _ in self.chain} async def call(self, messages, **kwargs): last_error = None for model, fn in self.chain: try: # 检查熔断 return self.breakers[model].call(fn, messages, **kwargs) except (CircuitOpenError, Exception) as e: last_error = e logger.warning(f"降级 {model} → 下一级: {e}") metrics.counter("fallback", tags={"from": model}).inc() continue # 全失败 → 返回通用回复 return self.ultimate_fallback(last_error) def ultimate_fallback(self, error): return { "error": "service_unavailable", "fallback_message": "抱歉,系统繁忙,请稍后再试。", "original_error": str(error) } ``` ### 2.5 灰度发布 ```python class CanaryRouter: def route(self, user_id, model_group): """根据权重路由""" weights = model_group["weights"] # {"v1": 0.9, "v2": 0.1} # 用 user_id 哈希保证同一用户走同一版本 h = int(hashlib.md5(f"{user_id}:{model_group['name']}".encode()).hexdigest(), 16) % 100 cumulative = 0 for version, weight in weights.items(): cumulative += int(weight * 100) if h Tuple[bool, str]: # 1. 快速关键词( Tuple[bool, str]: # 1. 敏感词 for word in self.SENSITIVE_WORDS: if word in output: return False, "抱歉,我无法回答该问题。" # 2. PII 过滤 output = self.pii_filter.mask(output) # 3. 内容安全(关键场景) if self.requires_llm_check(output): is_safe = await self.llm_safety_check(output) if not is_safe: return False, "抱歉,我无法回答该问题。" return True, output ``` ### 3.3 合规检查 ```python class ComplianceChecker: """合规检查:GDPR、PIPL 等""" def check_user_data(self, user_id, request): # 1. 用户是否同意数据使用 consent = get_user_consent(user_id) if not consent.get("ai_processing"): return False # 2. 是否跨境传输 if is_cross_border(request): if not consent.get("cross_border"): return False return True ``` --- ## 四、可观测性 ### 4.1 三件套:日志、指标、Trace ```python class ObservableGateway: def __init__(self): self.logger = StructuredLogger() self.metrics = MetricsClient() self.tracer = Tracer() async def call_llm(self, request): # 1. Trace 启动 with self.tracer.start_span("llm_call") as span: span.set_attribute("model", request.model) span.set_attribute("user_id", request.user_id) # 2. 记录开始 start = time.time() try: # 3. 限流检查 if not self.limiter.check(request.user_id, request.tokens): self.metrics.counter("ratelimit.blocked").inc() raise RateLimitError() # 4. 调用 LLM response = await self.llm.call(request) # 5. 记录指标 self.metrics.histogram("llm.duration").observe(time.time() - start) self.metrics.counter("llm.tokens", tags={"direction": "input"}).inc(response.input_tokens) self.metrics.counter("llm.tokens", tags={"direction": "output"}).inc(response.output_tokens) self.metrics.counter("llm.cost").inc(calculate_cost(request.model, ...)) # 6. 结构化日志 self.logger.info("llm_call", extra={ "model": request.model, "user_id": request.user_id, "input_tokens": response.input_tokens, "output_tokens": response.output_tokens, "cost": calculate_cost(...), "duration": time.time() - start }) return response except Exception as e: self.metrics.counter("llm.error", tags={"error": type(e).__name__}).inc() span.record_exception(e) raise ``` ### 4.2 关键指标 ```promql # 请求 gateway_request_total{model, business, status} gateway_request_duration_seconds{model, business} gateway_request_in_flight{model} # Token gateway_input_tokens_total{model, business} gateway_output_tokens_total{model, business} # 限流 gateway_ratelimit_blocked_total{dimension, key} gateway_breaker_state{model} # 0=closed, 1=open, 2=half_open # 降级 gateway_fallback_total{from_model, to_model, reason} # 成本 gateway_cost_usd{model, business} gateway_cost_per_request{model} # 内容安全 gateway_input_blocked_total{reason} gateway_output_blocked_total{reason} ``` ### 4.3 Trace ```python from opentelemetry import trace from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter class TracedGateway: def __init__(self): # 配置 OTLP exporter otlp_exporter = OTLPSpanExporter(endpoint="otel-collector:4317") trace.get_tracer_provider().add_span_processor( BatchSpanProcessor(otlp_exporter) ) async def call(self, request): with trace.get_tracer("ai-gateway").start_as_current_span("gateway_request") as span: span.set_attribute("model", request.model) span.set_attribute("user.id", request.user_id) # 限流 span with trace.get_tracer("ai-gateway").start_as_current_span("ratelimit"): self.limiter.check(...) # 内容安全 span with trace.get_tracer("ai-gateway").start_as_current_span("input_guard"): await self.input_guard.check(request.messages) # LLM call span with trace.get_tracer("ai-gateway").start_as_current_span("llm_call") as llm_span: llm_span.set_attribute("model", request.model) response = await self.llm.call(request) llm_span.set_attribute("tokens.input", response.input_tokens) llm_span.set_attribute("tokens.output", response.output_tokens) # 输出检查 span with trace.get_tracer("ai-gateway").start_as_current_span("output_guard"): await self.output_guard.check(response.content) return response ``` --- ## 五、性能与高可用 ### 5.1 连接池管理 ```python class ConnectionPoolManager: def __init__(self): self.pools = {} # {model: aiohttp.ClientSession} async def get_session(self, model: str): if model not in self.pools: timeout = aiohttp.ClientTimeout(total=60) connector = aiohttp.TCPConnector( limit=100, # 总连接数 limit_per_host=50, # 单 host 连接数 ttl_dns_cache=300, keepalive_timeout=30 ) self.pools[model] = aiohttp.ClientSession( timeout=timeout, connector=connector ) return self.pools[model] ``` ### 5.2 高可用部署 ```yaml # docker-compose.yml version: '3.5' services: ai-gateway: image: ai-gateway:latest deploy: replicas: 3 # 多个副本 ports: - "8080:8080" environment: - REDIS_URL=redis://redis:6379 - OTEL_EXPORTER_OTLP_ENDPOINT=otel-collector:4317 healthcheck: test: ["CMD", "curl", "-f", "http://localhost:8080/health"] interval: 10s timeout: 3s retries: 3 ``` ### 5.3 网关自身熔断 ```python class GatewaySelfProtection: """网关自己也要保护""" def __init__(self): self.semaphore = asyncio.Semaphore(1000) # 最大并发 self.circuit = CircuitBreaker("gateway") async def handle(self, request): async with self.semaphore: # 限流 if not self.limiter.check(...): return 429 # 调用 try: return await self.circuit.call(self.llm.call, request) except CircuitOpenError: return 503 ``` --- ## 六、成本控制 ### 6.1 Token 计费 ```python PRICING = { "gpt-4o": {"input": 2.5, "output": 10.0}, "gpt-4o-mini": {"input": 0.15, "output": 0.6}, "claude-3.5-sonnet": {"input": 3.0, "output": 15.0}, "qwen-72b-local": {"input": 0, "output": 0}, } def calculate_cost(model, input_tokens, output_tokens): p = PRICING.get(model, {"input": 0, "output": 0}) return input_tokens / 1e6 * p["input"] + output_tokens / 1e6 * p["output"] ``` ### 6.2 预算告警 ```python class BudgetController: def check(self, business: str, cost: float) -> bool: used = get_month_used(business) budget = get_business_budget(business) if used + cost > budget * 0.9: send_alert(f"业务 {business} 预算即将用完") if used + cost > budget: return False return True ``` --- ## 七、实战:从零搭建 AI 网关 ### 7.1 技术选型 | 组件 | 选型 | |------|------| | 框架 | FastAPI(异步、性能好) | | 限流 | Redis + Lua | | 熔断 | 自研或 pybreaker | | 缓存 | Redis + GPTCache | | 可观测 | OpenTelemetry + Prometheus | | 部署 | Docker + K8s | ### 7.2 核心实现 ```python from fastapi import FastAPI, HTTPException from pydantic import BaseModel app = FastAPI(title="AI Gateway") class ChatRequest(BaseModel): model: str messages: list temperature: float = 0.7 max_tokens: int = 1000 user_id: str = None business: str = "default" @app.post("/v1/chat/completions") async def chat_completions(request: ChatRequest): # 1. 限流 if not gateway.limiter.check(request.user_id, estimated_tokens(request)): raise HTTPException(429, "Rate limit exceeded") # 2. 输入检查 safe, reason = await gateway.input_guard.check(request.messages) if not safe: raise HTTPException(400, f"Input blocked: {reason}") # 3. 路由 actual_model = gateway.route(request.model, request.user_id) # 4. 调用(含降级) try: response = await gateway.fallback_chain.call( actual_model, request.messages ) except Exception as e: raise HTTPException(500, str(e)) # 5. 输出检查 safe, sanitized = await gateway.output_guard.check(response.content) # 6. 记录 gateway.metrics.record(actual_model, request, response, sanitized) return { "model": actual_model, "content": sanitized, "usage": response.usage } ``` ### 7.3 部署 ```yaml # k8s deployment apiVersion: apps/v1 kind: Deployment metadata: name: ai-gateway spec: replicas: 3 template: spec: containers: - name: gateway image: ai-gateway:latest resources: requests: cpu: 1000m memory: 1Gi limits: cpu: 2000m memory: 2Gi ports: - containerPort: 8080 readinessProbe: httpGet: path: /health port: 8080 ``` --- ## 八、踩坑提示 ### 坑 1:网关变慢导致雪崩 **症状**:网关 P99 延迟 10s,所有连接被占。 **解决**: - 严格的 timeout 配置(10-30s); - semaphore 限制并发; - 定期压测网关。 ### 坑 2:缓存导致回答过期 **症状**:用户问"今天天气"被缓存成昨天的。 **解决**: - 含时间词的请求不缓存; - TTL 短( **作者**:架构实战 第二季 > **版本**:v1.0 > **最后更新**:2026-10 > **全文约 6000 字**