前置阅读:建议先阅读 Cloudflare Workers AI 与 AI Gateway 入门。
关键概念:Workers AI 将 GPU 推理能力部署到全球 300+ 边缘节点,模型响应延迟可低至 50ms(相比中心云 API 的 200-800ms)。
² Workers AI 模型全矩阵
类别 模型 模型大小 延迟 (p50) 适用场景 文本生成 @hf/meta-llama/Llama-3.2-3B3B ~80ms 轻量对话、摘要 文本生成 @cf/mistral/mistral-7b7B ~150ms 复杂推理、代码生成 嵌入 @cf/baai/bge-base-en-v1.5109M ~25ms RAG 向量化 嵌入 @cf/baai/bge-large-en-v1.5326M ~45ms 高精度语义检索 语音识别 @cf/openai/whisper- ~200ms/15s 音频转录 图像生成 @cf/stabilityai/stable-diffusion-xl-base- ~5s 文生图 翻译 @cf/meta/m2m100-1.2b1.2B ~60ms 多语言翻译 模型命名规则:
@<publisher>/<org>/<model>。Cloudflare 负责模型下载、缓存和版本管理。³ 批量推理优化
单请求多次推理开销大,Workers AI 支持 batch key 合并:
// workers/batch-inference.ts export interface Env { AI: any; } async function batchEmbed( env: Env, texts: string[] ): Promise<number[][]> { const BATCH_SIZE = 100; // Workers AI 单请求上限 const embeddings: number[][] = []; for (let i = 0; i < texts.length; i += BATCH_SIZE) { const batch = texts.slice(i, i + BATCH_SIZE); const response = await env.AI.run("@cf/baai/bge-base-en-v1.5", { text: batch, }); embeddings.push(...response.data); } return embeddings; } // 实际应用:RAG 批量文档索引 export default { async fetch(request: Request, env: Env) { const { documents } = await request.json(); const start = Date.now(); const embeddings = await batchEmbed(env, documents); const duration = Date.now() - start; // 写入 Vectorize await env.VECTORIZE_INDEX.upsert( documents.map((doc, i) => ({ id: `doc_${i}`, values: embeddings[i], metadata: { text: doc.slice(0, 500) }, })) ); return Response.json({ indexed: documents.length, duration_ms: duration, avg_per_doc: duration / documents.length, }); }, };吞吐量优化技巧:
策略 效果 实现 并发请求 3-5x 吞吐 Promise.all(chunks.map(...))本地缓存嵌入 消除重复计算 Workers KV 缓存 hash→embedding 预热模型 消除冷启动 部署后发送预热请求 ⁴ AI Gateway 高级缓存策略
// workers/ai-gateway-advanced.ts interface GatewayConfig { endpoint: string; cache_strategy: "exact" | "semantic" | "none"; cache_ttl_seconds: number; rate_limit_rpm: number; fallback_models: string[]; } export class AIGatewayRouter { private cache: Cache; private requestCounts: Map<string, number[]> = new Map(); constructor(private config: GatewayConfig) { this.cache = caches.default; } async route(request: Request): Promise<Response> { const body = await request.clone().json(); const cacheKey = this.buildCacheKey(body); // 1. 精确缓存检查 if (this.config.cache_strategy === "exact") { const cached = await this.cache.match(cacheKey); if (cached) return cached; } // 2. 语义缓存(基于输入嵌入的相似度) if (this.config.cache_strategy === "semantic") { const similar = await this.findSemanticCache(body.prompt); if (similar) return new Response(JSON.stringify(similar)); } // 3. 限流检查 const now = Date.now(); const windowStart = now - 60_000; const requests = this.requestCounts.get(body.model) || []; const recent = requests.filter(t => t > windowStart); if (recent.length >= this.config.rate_limit_rpm) { // 触发降级:切换到备用模型 return this.fallback(request, body); } this.requestCounts.set(body.model, [...recent, now]); // 4. 主模型调用 const response = await fetch(this.config.endpoint, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${env.GATEWAY_TOKEN}` }, body: JSON.stringify(body), }); // 5. 缓存写入(只对确定性任务) if (this.config.cache_strategy !== "none" && body.temperature === 0) { await this.cache.put(cacheKey, response.clone()); } return response; } private buildCacheKey(body: any): Request { const key = `${body.model}:${JSON.stringify(body.messages)}`; return new Request(`https://cache.internal/${btoa(key)}`); } private async findSemanticCache(prompt: string): Promise<any | null> { // 使用 Vectorize 查找语义相似的历史查询 // 简化版伪代码 return null; } private async fallback(request: Request, body: any): Promise<Response> { for (const model of this.config.fallback_models) { try { const res = await fetch(this.config.endpoint, { method: "POST", headers: request.headers, body: JSON.stringify({ ...body, model }), }); if (res.ok) return res; } catch (e) { continue; } } return new Response("All models exhausted", { status: 503 }); } }⁵ 自定义模型部署
Workers AI 支持通过 Workers 运行自定义转换模型(ONNX Runtime / TensorFlow.js):
// workers/custom-model.ts // 使用 ONNX Runtime Web 运行自定义模型 import * as ort from "onnxruntime-web"; export default { async fetch(request: Request, env: Env) { const { input } = await request.json(); // 从 R2 加载模型 const modelBlob = await env.MODEL_BUCKET.get("custom-model.onnx"); if (!modelBlob) throw new Error("Model not found"); const modelArray = new Uint8Array(await modelBlob.arrayBuffer()); // 创建推理会话 const session = await ort.InferenceSession.create(modelArray); // 准备输入张量 const tensor = new ort.Tensor("float32", new Float32Array(input), [1, input.length]); // 推理 const results = await session.run({ input: tensor }); const output = results.output.data; return Response.json({ predictions: Array.from(output as Float32Array) }); }, };模型大小限制:
方案 模型大小上限 冷启动 适用 Workers AI Catalog 无限制(由 CF 托管) ~0ms(预热) 通用场景 ONNX Runtime (R2) 50MB (Worker bundle) 2-5s(模型加载) 小型定制模型 External API 无限制 网络延迟 超大模型 ⁶ 生产部署清单
# wrangler.toml [ai] binding = "AI" [[vectorize]] binding = "VECTORIZE_INDEX" index_name = "my-rag-index" [vars] CACHE_STRATEGY = "semantic" RATE_LIMIT_RPM = "60" FALLBACK_MODELS = "gpt-4o-mini,gemini-1.5-flash" # 配额监控 [[analytics_engine_datasets]] binding = "AI_METRICS" dataset = "ai_inference_logs"监控指标 告警阈值 来源 推理延迟 p99 > 500ms Workers Analytics 错误率 > 1% AI Gateway 日志 缓存命中率 < 30% 自定义计数器 成本/百万请求 > $5 AI Gateway计费
延伸阅读:
- Cloudflare Workers AI 与 AI Gateway 入门 — 基础概念与快速上手
- Cloudflare R2 对象存储实战 — 模型权重存储方案
- Vectorize 向量数据库 — RAG 检索层(如专题已扩展)
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。
「工具与平台」更多文章
Vercel Edge Config 完全指南:毫秒级配置下发与 A/B 测试驱动
深入 Vercel Edge Config 全局键值存储:与 Edge Functions / Middleware 的低延迟集成、A/B 测试与功能开关实现、多环境管理、版本控制与回滚策略,提供 TypeScript 端到端实现与性能基准。
Vercel Analytics 深度指南:Web Vitals 监控、真实用户性能与转化归因
全面解析 Vercel Analytics(真实用户监控 RUM)与 Speed Insights(Web Vitals)两大工具,覆盖安装集成、自定义事件追踪、性能瓶颈诊断、转化归因分析,以及与 Google Analytics 4 / Datadog 的对比选型。
Vercel AI SDK 深度实战:Tool Calling、Schema 流式输出与多模型路由
深入 Vercel AI SDK 三大核心包(ai / @ai-sdk/openai / @ai-sdk/react),覆盖 generateObject 结构化输出、streamText 工具调用流、多模型路由与回退、Server Action 集成等高级场景,提供端到端 TypeScript 实现。