前置阅读:建议先阅读 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计费
Workers AI 与其他推理平台对比
| 维度 | Workers AI | OpenAI API | AWS SageMaker | Replicate |
|---|---|---|---|---|
| 部署方式 | 边缘函数(Serverless) | 中心云 API | 自建实例 | Serverless |
| 延迟 (p50) | 25-150ms | 200-800ms | 100-500ms | 300-1000ms |
| 冷启动 | 无 | 无 | 分钟级 | 秒级 |
| 模型选择 | Catalog + 自定义 | 有限 | 任意 | 社区模型 |
| 定价模式 | 按请求次数 | 按 Token | 按实例时间 | 按推理时间 |
| 数据隐私 | 数据不出边缘节点 | 传输到 OpenAI | 数据留在 AWS | 传输到 Replicate |
| 适用场景 | 低延迟实时推理 | 通用 LLM | 大模型微调 | 快速实验 |
成本优化策略
| 策略 | 节省比例 | 适用场景 |
|---|---|---|
| AI Gateway 缓存 | 20-40% | 重复查询(FAQ、分类) |
| 批量推理 | 10-20% | 文档索引、批量分类 |
| 模型降级 | 30-50% | 非关键路径(摘要、建议) |
| 边缘缓存嵌入 | 50-80% | RAG 检索重复文档 |
总结
Workers AI 的核心价值在于将推理能力下沉到边缘:全球 300+ 节点意味着用户请求在地理上就近处理,延迟比中心云降低一个数量级。AI Gateway 的多级缓存和智能路由进一步提升了可靠性和成本效率。对于需要低延迟、高并发的 AI 应用场景(如实时推荐、内容审核、代码补全),Workers AI 是极具竞争力的选择。企业用户可以从 AI Gateway 的逻辑缓存入手,快速降低推理成本,随后根据业务需求引入语义缓存和模型降级策略,逐步构建成熟的边缘 AI 服务架构。长远来看,边缘推理将成为 AI 应用的标准配置,Workers AI 的竞争优势在于其全球化节点覆盖和与 Cloudflare 生态的深度整合,开发者可以充分利用这一点构建低延迟、高可用的智能应用。
延伸阅读:
- Cloudflare Workers AI 与 AI Gateway 入门 — 基础概念与快速上手
- Cloudflare R2 对象存储实战 — 模型权重存储方案
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。