Cloudflare Workers AI 高级实战:自定义模型部署、批量推理与 AI Gateway 缓存策略

深入 Cloudflare Workers AI 生产级应用:Workers AI Catalog 模型量化原理、批量推理优化、AI Gateway 多级缓存与智能限流、自定义模型 Workers AI 部署(TensorFlow.js / ONNX Runtime),含完整 TypeScript 实现与成本基准。

前置阅读:建议先阅读 Cloudflare Workers AI 与 AI Gateway 入门

关键概念:Workers AI 将 GPU 推理能力部署到全球 300+ 边缘节点,模型响应延迟可低至 50ms(相比中心云 API 的 200-800ms)。

  1. ² Workers AI 模型全矩阵

    类别模型模型大小延迟 (p50)适用场景
    文本生成@hf/meta-llama/Llama-3.2-3B3B~80ms轻量对话、摘要
    文本生成@cf/mistral/mistral-7b7B~150ms复杂推理、代码生成
    嵌入@cf/baai/bge-base-en-v1.5109M~25msRAG 向量化
    嵌入@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 负责模型下载、缓存和版本管理。

  2. ³ 批量推理优化

    单请求多次推理开销大,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
    预热模型消除冷启动部署后发送预热请求
  3. ⁴ 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 });
      }
    }
    
  4. ⁵ 自定义模型部署

    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无限制网络延迟超大模型
  5. ⁶ 生产部署清单

    # 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> 500msWorkers Analytics
    错误率> 1%AI Gateway 日志
    缓存命中率< 30%自定义计数器
    成本/百万请求> $5AI Gateway计费

延伸阅读

← 上一篇

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「工具与平台」更多文章