Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.
Python aianthropicautomationclaude-codeclaude-skillscloudflaredevtoolsproductivityreactskillstailwindvite
refactor(cloudflare-workers-ai): Knowledge-gap audit - Add 21 major 2025 updates, trim to 341 lines
Jez6ed7d91e8f0a
diff --git a/skills/cloudflare-workers-ai/SKILL.md b/skills/cloudflare-workers-ai/SKILL.mdindex ecf1bd54..51ff71c6 100644--- a/skills/cloudflare-workers-ai/SKILL.md+++ b/skills/cloudflare-workers-ai/SKILL.md@@ -1,447 +1,206 @@---name: cloudflare-workers-aidescription: |- Run LLMs and AI models on Cloudflare's global GPU network with Workers AI. Includes Llama, Flux image generation,- BGE embeddings, and streaming support with AI Gateway for caching and logging.-- Use when: implementing LLM inference, generating images with Flux/Stable Diffusion, building RAG with embeddings,- streaming AI responses, using AI Gateway for cost tracking, or troubleshooting AI_ERROR, rate limits, model not- found, token limits, or neurons exceeded.-- Keywords: workers ai, cloudflare ai, ai bindings, llm workers, @cf/meta/llama, workers ai models,- ai inference, cloudflare llm, ai streaming, text generation ai, ai embeddings, image generation ai,- workers ai rag, ai gateway, llama workers, flux image generation, stable diffusion workers,- vision models ai, ai chat completion, AI_ERROR, rate limit ai, model not found, token limit exceeded,- neurons exceeded, ai quota exceeded, streaming failed, model unavailable, workers ai hono,- ai gateway workers, vercel ai sdk workers, openai compatible workers, workers ai vectorize+ Run LLMs and AI models on Cloudflare's global GPU network with Workers AI. Includes Llama 4, Gemma 3, Mistral 3.1,+ Flux image generation, BGE embeddings (2x faster, 2025), streaming support, and AI Gateway for cost tracking.++ Use when: implementing LLM inference, generating images, building RAG with embeddings, streaming AI responses,+ using AI Gateway, troubleshooting max_tokens defaults (breaking change 2025), BGE pooling parameter (not backwards+ compatible), or handling AI_ERROR, rate limits, model deprecations, token limits.++ Keywords: workers ai, cloudflare ai, ai bindings, llm workers, @cf/meta/llama-4-scout, @cf/google/gemma-3-12b-it,+ @cf/mistralai/mistral-small-3.1-24b-instruct, @cf/openai/gpt-oss-120b, workers ai models, ai inference,+ cloudflare llm, ai streaming, text generation ai, ai embeddings, bge pooling cls mean, image generation ai,+ workers ai rag, ai gateway, llama workers, flux image generation, deepgram aura, leonardo image generation,+ vision models ai, ai chat completion, AI_ERROR, rate limit ai, model not found, max_tokens breaking change,+ bge pooling backwards compatibility, model deprecations october 2025, token limit exceeded, neurons exceeded,+ workers ai hono, ai gateway workers, vercel ai sdk workers, openai compatible workers, workers ai vectorize,+ workers-ai-provider v2, ai sdk v5, lora adapters rank 32license: MIT----# Cloudflare Workers AI - Complete Reference--Production-ready knowledge domain for building AI-powered applications with Cloudflare Workers AI.+# Cloudflare Workers AI**Status**: Production Ready ✅-**Last Updated**: 2025-10-21+**Last Updated**: 2025-11-25**Dependencies**: cloudflare-worker-base (for Worker setup)-**Latest Versions**: [email protected], @cloudflare/[email protected]-----+**Latest Versions**: [email protected], @cloudflare/[email protected]-## Table of Contents--1. [Quick Start (5 minutes)](#quick-start-5-minutes)-2. [Workers AI API Reference](#workers-ai-api-reference)-3. [Model Selection Guide](#model-selection-guide)-4. [Common Patterns](#common-patterns)-5. [AI Gateway Integration](#ai-gateway-integration)-6. [Rate Limits & Pricing](#rate-limits--pricing)-7. [Production Checklist](#production-checklist)+**Recent Updates (2025)**:+- **April 2025 - Performance**: Llama 3.3 70B 2-4x faster (speculative decoding, prefix caching), BGE embeddings 2x faster+- **April 2025 - Breaking Changes**: max_tokens now correctly defaults to 256 (was not respected), BGE pooling parameter (cls NOT backwards compatible with mean)+- **2025 - New Models (14)**: Mistral 3.1 24B (vision+tools), Gemma 3 12B (128K context), EmbeddingGemma 300M, Llama 4 Scout, GPT-OSS 120B/20B, Qwen models (QwQ 32B, Coder 32B), Leonardo image gen, Deepgram Aura 2, Whisper v3 Turbo, IBM Granite, Nova 3+- **2025 - Platform**: Context windows API change (tokens not chars), unit-based pricing with per-model granularity, workers-ai-provider v2.0.0 (AI SDK v5), LoRA rank up to 32 (was 8), 100 adapters per account+- **October 2025**: Model deprecations (use Llama 4, GPT-OSS instead)----## Quick Start (5 minutes)--### 1. Add AI Binding--**wrangler.jsonc:**-```jsonc-{- "ai": {- "binding": "AI"- }-}-```--### 2. Run Your First Model+## Quick Start (5 Minutes)```typescript-export interface Env {- AI: Ai;-}+// 1. Add AI binding to wrangler.jsonc+{ "ai": { "binding": "AI" } }+// 2. Run model with streaming (recommended)export default {async fetch(request: Request, env: Env): Promise<Response> {- const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {- prompt: 'What is Cloudflare?',+ const stream = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {+ messages: [{ role: 'user', content: 'Tell me a story' }],+ stream: true, // Always stream for text generation!});- return Response.json(response);+ return new Response(stream, {+ headers: { 'content-type': 'text/event-stream' },+ });},};```-### 3. Add Streaming (Recommended)--```typescript-const stream = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {- messages: [{ role: 'user', content: 'Tell me a story' }],- stream: true, // Always use streaming for text generation!-});--return new Response(stream, {- headers: { 'content-type': 'text/event-stream' },-});-```--**Why streaming?**-- Prevents buffering large responses in memory-- Faster time-to-first-token-- Better user experience for long-form content-- Avoids Worker timeout issues+**Why streaming?** Prevents buffering in memory, faster time-to-first-token, avoids Worker timeout issues.----## Workers AI API Reference+## API Reference-### `env.AI.run()`--Run an AI model inference.--**Signature:**```typescript-async env.AI.run(+env.AI.run(model: string,inputs: ModelInputs,options?: { gateway?: { id: string; skipCache?: boolean } }): Promise<ModelOutput | ReadableStream>```-**Parameters:**--- `model` (string, required) - Model ID (e.g., `@cf/meta/llama-3.1-8b-instruct`)-- `inputs` (object, required) - Model-specific inputs-- `options` (object, optional) - Additional options- - `gateway` (object) - AI Gateway configuration- - `id` (string) - Gateway ID- - `skipCache` (boolean) - Skip AI Gateway cache--**Returns:**--- Non-streaming: `Promise<ModelOutput>` - JSON response-- Streaming: `ReadableStream` - Server-sent events stream-----### Text Generation Models--**Input Format:**-```typescript-{- messages?: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>;- prompt?: string; // Deprecated, use messages- stream?: boolean; // Default: false- max_tokens?: number; // Max tokens to generate- temperature?: number; // 0.0-1.0, default varies by model- top_p?: number; // 0.0-1.0- top_k?: number;-}-```--**Output Format (Non-Streaming):**-```typescript-{- response: string; // Generated text-}-```--**Example:**-```typescript-const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {- messages: [- { role: 'system', content: 'You are a helpful assistant.' },- { role: 'user', content: 'What is TypeScript?' },- ],- stream: false,-});--console.log(response.response);-```-------### Text Embeddings Models--**Input Format:**-```typescript-{- text: string | string[]; // Single text or array of texts-}-```--**Output Format:**-```typescript-{- shape: number[]; // [batch_size, embedding_dimensions]- data: number[][]; // Array of embedding vectors-}-```--**Example:**-```typescript-const embeddings = await env.AI.run('@cf/baai/bge-base-en-v1.5', {- text: ['Hello world', 'Cloudflare Workers'],-});--console.log(embeddings.shape); // [2, 768]-console.log(embeddings.data[0]); // [0.123, -0.456, ...]-```-------### Image Generation Models--**Input Format:**-```typescript-{- prompt: string; // Text description- num_steps?: number; // Default: 20- guidance?: number; // CFG scale, default: 7.5- strength?: number; // For img2img, default: 1.0- image?: number[][]; // For img2img (base64 or array)-}-```--**Output Format:**-- Binary image data (PNG/JPEG)--**Example:**-```typescript-const imageStream = await env.AI.run('@cf/black-forest-labs/flux-1-schnell', {- prompt: 'A beautiful sunset over mountains',-});--return new Response(imageStream, {- headers: { 'content-type': 'image/png' },-});-```-------### Vision Models--**Input Format:**-```typescript-{- messages: Array<{- role: 'user' | 'assistant';- content: Array<{ type: 'text' | 'image_url'; text?: string; image_url?: { url: string } }>;- }>;-}-```--**Example:**-```typescript-const response = await env.AI.run('@cf/meta/llama-3.2-11b-vision-instruct', {- messages: [- {- role: 'user',- content: [- { type: 'text', text: 'What is in this image?' },- { type: 'image_url', image_url: { url: 'data:image/png;base64,iVBOR...' } },- ],- },- ],-});-```-------## Model Selection Guide+## Model Selection Guide (Updated 2025)### Text Generation (LLMs)-| Model | Best For | Rate Limit | Size |-|-------|----------|------------|------|-| `@cf/meta/llama-3.1-8b-instruct` | General purpose, fast | 300/min | 8B |-| `@cf/meta/llama-3.2-1b-instruct` | Ultra-fast, simple tasks | 300/min | 1B |-| `@cf/qwen/qwen1.5-14b-chat-awq` | High quality, complex reasoning | 150/min | 14B |-| `@cf/deepseek-ai/deepseek-r1-distill-qwen-32b` | Coding, technical content | 300/min | 32B |-| `@hf/thebloke/mistral-7b-instruct-v0.1-awq` | Fast, efficient | 400/min | 7B |--### Text Embeddings--| Model | Dimensions | Best For | Rate Limit |-|-------|-----------|----------|------------|-| `@cf/baai/bge-base-en-v1.5` | 768 | General purpose RAG | 3000/min |-| `@cf/baai/bge-large-en-v1.5` | 1024 | High accuracy search | 1500/min |-| `@cf/baai/bge-small-en-v1.5` | 384 | Fast, low storage | 3000/min |+| Model | Best For | Rate Limit | Size | Notes |+|-------|----------|------------|------|-------|+| **2025 Models** |+| `@cf/meta/llama-4-scout-17b-16e-instruct` | Latest Llama, general purpose | 300/min | 17B | NEW 2025 |+| `@cf/openai/gpt-oss-120b` | Largest open-source GPT | 300/min | 120B | NEW 2025 |+| `@cf/openai/gpt-oss-20b` | Smaller open-source GPT | 300/min | 20B | NEW 2025 |+| `@cf/google/gemma-3-12b-it` | 128K context, 140+ languages | 300/min | 12B | NEW 2025, vision |+| `@cf/mistralai/mistral-small-3.1-24b-instruct` | Vision + tool calling | 300/min | 24B | NEW 2025 |+| `@cf/qwen/qwq-32b` | Reasoning, complex tasks | 300/min | 32B | NEW 2025 |+| `@cf/qwen/qwen2.5-coder-32b-instruct` | Coding specialist | 300/min | 32B | NEW 2025 |+| `@cf/qwen/qwen3-30b-a3b-fp8` | Fast quantized | 300/min | 30B | NEW 2025 |+| `@cf/ibm-granite/granite-4.0-h-micro` | Small, efficient | 300/min | Micro | NEW 2025 |+| **Performance (2025)** |+| `@cf/meta/llama-3.3-70b-instruct-fp8-fast` | 2-4x faster (2025 update) | 300/min | 70B | Speculative decoding |+| `@cf/meta/llama-3.1-8b-instruct-fp8-fast` | Fast 8B variant | 300/min | 8B | - |+| **Standard Models** |+| `@cf/meta/llama-3.1-8b-instruct` | General purpose | 300/min | 8B | - |+| `@cf/meta/llama-3.2-1b-instruct` | Ultra-fast, simple tasks | 300/min | 1B | - |+| `@cf/deepseek-ai/deepseek-r1-distill-qwen-32b` | Coding, technical | 300/min | 32B | - |++### Text Embeddings (2x Faster - 2025)++| Model | Dimensions | Best For | Rate Limit | Notes |+|-------|-----------|----------|------------|-------|+| `@cf/google/embeddinggemma-300m` | 768 | Best-in-class RAG | 3000/min | **NEW 2025** |+| `@cf/baai/bge-base-en-v1.5` | 768 | General RAG (2x faster) | 3000/min | **pooling: "cls"** recommended |+| `@cf/baai/bge-large-en-v1.5` | 1024 | High accuracy (2x faster) | 1500/min | **pooling: "cls"** recommended |+| `@cf/baai/bge-small-en-v1.5` | 384 | Fast, low storage (2x faster) | 3000/min | **pooling: "cls"** recommended |+| `@cf/qwen/qwen3-embedding-0.6b` | 768 | Qwen embeddings | 3000/min | NEW 2025 |++**CRITICAL (2025)**: BGE models now support `pooling: "cls"` parameter (recommended) but NOT backwards compatible with `pooling: "mean"` (default).### Image Generation-| Model | Best For | Rate Limit | Speed |+| Model | Best For | Rate Limit | Notes ||-------|----------|------------|-------|-| `@cf/black-forest-labs/flux-1-schnell` | High quality, photorealistic | 720/min | Fast |-| `@cf/stabilityai/stable-diffusion-xl-base-1.0` | General purpose | 720/min | Medium |-| `@cf/lykon/dreamshaper-8-lcm` | Artistic, stylized | 720/min | Fast |+| `@cf/black-forest-labs/flux-1-schnell` | High quality, photorealistic | 720/min | - |+| `@cf/leonardo/lucid-origin` | Leonardo AI style | 720/min | NEW 2025 |+| `@cf/leonardo/phoenix-1.0` | Leonardo AI variant | 720/min | NEW 2025 |+| `@cf/stabilityai/stable-diffusion-xl-base-1.0` | General purpose | 720/min | - |### Vision Models-| Model | Best For | Rate Limit |-|-------|----------|------------|-| `@cf/meta/llama-3.2-11b-vision-instruct` | Image understanding | 720/min |-| `@cf/unum/uform-gen2-qwen-500m` | Fast image captioning | 720/min |-----+| Model | Best For | Rate Limit | Notes |+|-------|----------|------------|-------|+| `@cf/meta/llama-3.2-11b-vision-instruct` | Image understanding | 720/min | - |+| `@cf/google/gemma-3-12b-it` | Vision + text (128K context) | 300/min | NEW 2025 |-## Common Patterns+### Audio Models (2025)-### Pattern 1: Chat Completion with History--```typescript-app.post('/chat', async (c) => {- const { messages } = await c.req.json<{- messages: Array<{ role: string; content: string }>;- }>();-- const response = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {- messages,- stream: true,- });-- return new Response(response, {- headers: { 'content-type': 'text/event-stream' },- });-});-```+| Model | Type | Rate Limit | Notes |+|-------|------|------------|-------|+| `@cf/deepgram/aura-2-en` | Text-to-speech (English) | 720/min | NEW 2025 |+| `@cf/deepgram/aura-2-es` | Text-to-speech (Spanish) | 720/min | NEW 2025 |+| `@cf/deepgram/nova-3` | Speech-to-text (+ WebSocket) | 720/min | NEW 2025 |+| `@cf/openai/whisper-large-v3-turbo` | Speech-to-text (faster) | 720/min | NEW 2025 |----### Pattern 2: RAG (Retrieval Augmented Generation)--```typescript-// Step 1: Generate embeddings-const embeddings = await env.AI.run('@cf/baai/bge-base-en-v1.5', {- text: [userQuery],-});+## Common Patterns-const vector = embeddings.data[0];+### RAG (Retrieval Augmented Generation)-// Step 2: Search Vectorize-const matches = await env.VECTORIZE.query(vector, { topK: 3 });+```typescript+// 1. Generate embeddings+const embeddings = await env.AI.run('@cf/baai/bge-base-en-v1.5', { text: [userQuery] });-// Step 3: Build context from matches+// 2. Search Vectorize+const matches = await env.VECTORIZE.query(embeddings.data[0], { topK: 3 });const context = matches.matches.map((m) => m.metadata.text).join('\n\n');-// Step 4: Generate response with context+// 3. Generate with contextconst response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {messages: [- {- role: 'system',- content: `Answer using this context:\n${context}`,- },+ { role: 'system', content: `Answer using this context:\n${context}` },{ role: 'user', content: userQuery },],stream: true,});--return new Response(response, {- headers: { 'content-type': 'text/event-stream' },-});```----### Pattern 3: Structured Output with Zod+### Structured Output with Zod```typescriptimport { z } from 'zod';-const RecipeSchema = z.object({- name: z.string(),- ingredients: z.array(z.string()),- instructions: z.array(z.string()),- prepTime: z.number(),-});--app.post('/recipe', async (c) => {- const { dish } = await c.req.json<{ dish: string }>();-- const response = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {- messages: [- {- role: 'user',- content: `Generate a recipe for ${dish}. Return ONLY valid JSON matching this schema: ${JSON.stringify(RecipeSchema.shape)}`,- },- ],- });-- // Parse and validate- const recipe = RecipeSchema.parse(JSON.parse(response.response));+const Schema = z.object({ name: z.string(), items: z.array(z.string()) });- return c.json(recipe);+const response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {+ messages: [{+ role: 'user',+ content: `Generate JSON matching: ${JSON.stringify(Schema.shape)}`+ }],});-```-------### Pattern 4: Image Generation + R2 Storage-```typescript-app.post('/generate-image', async (c) => {- const { prompt } = await c.req.json<{ prompt: string }>();-- // Generate image- const imageStream = await c.env.AI.run('@cf/black-forest-labs/flux-1-schnell', {- prompt,- });-- const imageBytes = await new Response(imageStream).bytes();-- // Store in R2- const key = `images/${Date.now()}.png`;- await c.env.BUCKET.put(key, imageBytes, {- httpMetadata: { contentType: 'image/png' },- });-- return c.json({- success: true,- url: `https://your-domain.com/${key}`,- });-});+const validated = Schema.parse(JSON.parse(response.response));```---## AI Gateway Integration-AI Gateway provides caching, logging, and analytics for AI requests.+Provides caching, logging, cost tracking, and analytics for AI requests.-**Setup:**```typescriptconst response = await env.AI.run('@cf/meta/llama-3.1-8b-instruct',{ prompt: 'Hello' },- {- gateway: {- id: 'my-gateway', // Your gateway ID- skipCache: false, // Use cache- },- }+ { gateway: { id: 'my-gateway', skipCache: false } });-```-**Benefits:**-- ✅ **Cost Tracking** - Monitor neurons usage per request-- ✅ **Caching** - Reduce duplicate inference costs-- ✅ **Logging** - Debug and analyze AI requests-- ✅ **Rate Limiting** - Additional layer of protection-- ✅ **Analytics** - Request patterns and performance--**Access Gateway Logs:**-```typescript+// Access logs and send feedbackconst gateway = env.AI.gateway('my-gateway');-const logId = env.AI.aiGatewayLogId;--// Send feedback-await gateway.patchLog(logId, {+await gateway.patchLog(env.AI.aiGatewayLogId, {feedback: { rating: 1, comment: 'Great response' },});```+**Benefits:** Cost tracking, caching (reduces duplicate inference), logging, rate limiting, analytics.+----## Rate Limits & Pricing+## Rate Limits & Pricing (Updated 2025)### Rate Limits (per minute)@@ -451,48 +210,56 @@ await gateway.patchLog(logId, {| **Text Embeddings** | 3000/min | BGE-large: 1500/min || **Image Generation** | 720/min | All image models || **Vision Models** | 720/min | Image understanding |+| **Audio (TTS/STT)** | 720/min | Deepgram, Whisper || **Translation** | 720/min | M2M100, Opus MT || **Classification** | 2000/min | Text classification |-| **Speech Recognition** | 720/min | Whisper models |-### Pricing (Neurons-Based)+### Pricing (Unit-Based, Billed in Neurons - 2025)**Free Tier:**- 10,000 neurons per day- Resets daily at 00:00 UTC-**Paid Tier:**-- $0.011 per 1,000 neurons+**Paid Tier ($0.011 per 1,000 neurons):**- 10,000 neurons/day included- Unlimited usage above free allocation-**Example Costs:**--| Model | Input (1M tokens) | Output (1M tokens) |-|-------|-------------------|-------------------|-| Llama 3.2 1B | $0.027 | $0.201 |-| Llama 3.1 8B | $0.088 | $0.606 |-| BGE-base embeddings | $0.005 | N/A |-| Flux image generation | ~$0.011/image | N/A |+**2025 Model Costs (per 1M tokens):**++| Model | Input | Output | Notes |+|-------|-------|--------|-------|+| **2025 Models** |+| Llama 4 Scout 17B | $0.270 | $0.850 | NEW 2025 |+| GPT-OSS 120B | $0.350 | $0.750 | NEW 2025 |+| GPT-OSS 20B | $0.200 | $0.300 | NEW 2025 |+| Gemma 3 12B | $0.345 | $0.556 | NEW 2025 |+| Mistral 3.1 24B | $0.351 | $0.555 | NEW 2025 |+| Qwen QwQ 32B | $0.660 | $1.000 | NEW 2025 |+| Qwen Coder 32B | $0.660 | $1.000 | NEW 2025 |+| IBM Granite Micro | $0.017 | $0.112 | NEW 2025 |+| EmbeddingGemma 300M | $0.012 | N/A | NEW 2025 |+| Qwen3 Embedding 0.6B | $0.012 | N/A | NEW 2025 |+| **Performance (2025)** |+| Llama 3.3 70B Fast | $0.293 | $2.253 | 2-4x faster |+| Llama 3.1 8B FP8 Fast | $0.045 | $0.384 | Fast variant |+| **Standard Models** |+| Llama 3.2 1B | $0.027 | $0.201 | - |+| Llama 3.1 8B | $0.282 | $0.827 | - |+| Deepseek R1 32B | $0.497 | $4.881 | - |+| BGE-base (2x faster) | $0.067 | N/A | 2025 speedup |+| BGE-large (2x faster) | $0.204 | N/A | 2025 speedup |+| **Image Models (2025)** |+| Flux 1 Schnell | $0.0000528 per 512x512 tile | - |+| Leonardo Lucid | $0.006996 per 512x512 tile | NEW 2025 |+| Leonardo Phoenix | $0.005830 per 512x512 tile | NEW 2025 |+| **Audio Models (2025)** |+| Deepgram Aura 2 | $0.030 per 1k chars | NEW 2025 |+| Deepgram Nova 3 | $0.0052 per audio min | NEW 2025 |+| Whisper v3 Turbo | $0.0005 per audio min | NEW 2025 |----## Production Checklist--### Before Deploying--- [ ] **Enable AI Gateway** for cost tracking and logging-- [ ] **Implement streaming** for all text generation endpoints-- [ ] **Add rate limit retry** with exponential backoff-- [ ] **Validate input length** to prevent token limit errors-- [ ] **Set appropriate timeouts** (Workers: 30s CPU default, 5m max)-- [ ] **Monitor neurons usage** in Cloudflare dashboard-- [ ] **Test error handling** for model unavailable, rate limits-- [ ] **Add input sanitization** to prevent prompt injection-- [ ] **Configure CORS** if using from browser-- [ ] **Plan for scale** - upgrade to Paid plan if needed--### Error Handling+## Error Handling with Retry```typescriptasync function runAIWithRetry(@@ -508,17 +275,14 @@ async function runAIWithRetry(return await env.AI.run(model, inputs);} catch (error) {lastError = error as Error;- const message = lastError.message.toLowerCase();- // Rate limit - retry with backoff- if (message.includes('429') || message.includes('rate limit')) {- const delay = Math.pow(2, i) * 1000; // Exponential backoff- await new Promise((resolve) => setTimeout(resolve, delay));+ // Rate limit - retry with exponential backoff+ if (lastError.message.toLowerCase().includes('rate limit')) {+ await new Promise((resolve) => setTimeout(resolve, Math.pow(2, i) * 1000));continue;}- // Other errors - throw immediately- throw error;+ throw error; // Other errors - fail immediately}}@@ -526,104 +290,52 @@ async function runAIWithRetry(}```-### Monitoring--```typescript-app.use('*', async (c, next) => {- const start = Date.now();-- await next();-- // Log AI usage- console.log({- path: c.req.path,- duration: Date.now() - start,- logId: c.env.AI.aiGatewayLogId,- });-});-```----## OpenAI Compatibility-Workers AI supports OpenAI-compatible endpoints.--**Using OpenAI SDK:**```typescriptimport OpenAI from 'openai';const openai = new OpenAI({apiKey: env.CLOUDFLARE_API_KEY,- baseURL: `https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/ai/v1`,+ baseURL: `https://api.cloudflare.com/client/v4/accounts/${env.ACCOUNT_ID}/ai/v1`,});// Chat completions-const completion = await openai.chat.completions.create({+await openai.chat.completions.create({model: '@cf/meta/llama-3.1-8b-instruct',messages: [{ role: 'user', content: 'Hello!' }],});--// Embeddings-const embeddings = await openai.embeddings.create({- model: '@cf/baai/bge-base-en-v1.5',- input: 'Hello world',-});```-**Endpoints:**-- `/v1/chat/completions` - Text generation-- `/v1/embeddings` - Text embeddings+**Endpoints:** `/v1/chat/completions`, `/v1/embeddings`----## Vercel AI SDK Integration--```bash-npm install workers-ai-provider ai-```+## Vercel AI SDK Integration (workers-ai-provider v2.0.0)```typescript-import { createWorkersAI } from 'workers-ai-provider';+import { createWorkersAI } from 'workers-ai-provider'; // v2.0.0 with AI SDK v5import { generateText, streamText } from 'ai';const workersai = createWorkersAI({ binding: env.AI });-// Generate text-const result = await generateText({+// Generate or stream+await generateText({model: workersai('@cf/meta/llama-3.1-8b-instruct'),prompt: 'Write a poem',});--// Stream text-const stream = streamText({- model: workersai('@cf/meta/llama-3.1-8b-instruct'),- prompt: 'Tell me a story',-});```----## Limits Summary--| Feature | Limit |-|---------|-------|-| Concurrent requests | No hard limit (rate limits apply) |-| Max input tokens | Varies by model (typically 2K-128K) |-| Max output tokens | Varies by model (typically 512-2048) |-| Streaming chunk size | ~1 KB |-| Image size (output) | ~5 MB |-| Request timeout | Workers timeout applies (30s default, 5m max CPU) |-| Daily free neurons | 10,000 |-| Rate limits | See "Rate Limits & Pricing" section |------## References- [Workers AI Docs](https://developers.cloudflare.com/workers-ai/)- [Models Catalog](https://developers.cloudflare.com/workers-ai/models/)- [AI Gateway](https://developers.cloudflare.com/ai-gateway/)- [Pricing](https://developers.cloudflare.com/workers-ai/platform/pricing/)-- [Limits](https://developers.cloudflare.com/workers-ai/platform/limits/)-- [REST API](https://developers.cloudflare.com/workers-ai/get-started/rest-api/)+- [Changelog](https://developers.cloudflare.com/workers-ai/changelog/)+- [LoRA Adapters](https://developers.cloudflare.com/workers-ai/features/fine-tunes/loras/)+- **MCP Tool**: Use `mcp__cloudflare-docs__search_cloudflare_documentation` for latest docs