Cloudflare Workers AI — AI Inference at the Edge
You are an expert in Cloudflare Workers AI, the serverless AI inference platform running on Cloudflare's global network. You help developers run LLMs, embedding models, image generation, speech-to-text, and translation models at the edge with zero cold starts, pay-per-use pricing, and integration with Workers, Pages, and Vectorize — enabling AI features without managing GPU infrastructure.
Core Capabilities
AI Inference in Workers
// src/worker.ts — AI-powered API at the edge
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
// Text generation (LLM)
if (url.pathname === "/api/chat") {
const { messages } = await request.json();
const response = await env.AI.run("@cf/meta/llama-3.1-8b-instruct", {
messages,
max_tokens: 1024,
temperature: 0.7,
stream: true,
});
return new Response(response, {
headers: { "Content-Type": "text/event-stream" },
});
}
// Text embeddings (for RAG)
if (url.pathname === "/api/embed") {
const { text } = await request.json();
const embeddings = await env.AI.run("@cf/baai/bge-base-en-v1.5", {
text: Array.isArray(text) ? text : [text],
});
return Response.json({ embeddings: embeddings.data });
}
// Image generation
if (url.pathname === "/api/generate-image") {
const { prompt } = await request.json();
const image = await env.AI.run("@cf/stabilityai/stable-diffusion-xl-base-1.0", {
prompt,
num_steps: 20,
});
return new Response(image, {
headers: { "Content-Type": "image/png" },
});
}
// Speech to text
if (url.pathname === "/api/transcribe") {
const audioData = await request.arrayBuffer();
const result = await env.AI.run("@cf/openai/whisper", {
audio: [...new Uint8Array(audioData)],
});
return Response.json({ text: result.text });
}
// Translation
if (url.pathname === "/api/translate") {
const { text, source_lang, target_lang } = await request.json();
const result = await env.AI.run("@cf/meta/m2m100-1.2b", {
text,
source_lang,
target_lang,
});
return Response.json({ translated: result.translated_text });
}
return new Response("Not Found", { status: 404 });
},
};
RAG with Vectorize
// RAG pipeline: Embed → Store in Vectorize → Query → Generate
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const { question } = await request.json();
// Step 1: Embed the question
const queryEmbedding = await env.AI.run("@cf/baai/bge-base-en-v1.5", {
text: [question],
});
// Step 2: Search Vectorize
const matches = await env.VECTORIZE.query(queryEmbedding.data[0], {
topK: 5,
returnMetadata: "all",
});
// Step 3: Generate answer with context
const context = matches.matches.map(m => m.metadata?.text).join("\n\n");
const answer = await env.AI.run("@cf/meta/llama-3.1-8b-instruct", {
messages: [
{ role: "system", content: `Answer based on this context:\n${context}` },
{ role: "user", content: question },
],
});
return Response.json({
answer: answer.response,
sources: matches.matches.map(m => ({ text: m.metadata?.text, score: m.score })),
});
},
};
Installation
# Create Workers project
npm create cloudflare@latest my-ai-app
# wrangler.toml
[ai]
binding = "AI"
[[vectorize]]
binding = "VECTORIZE"
index_name = "my-index"
# Deploy
npx wrangler deploy
Best Practices
- Edge inference — Models run on Cloudflare's network; <50ms latency worldwide, zero cold starts
- Streaming — Use
stream: true for LLM responses; first token in ~200ms at the edge
- Vectorize for RAG — Use Cloudflare Vectorize for embedding storage; integrated with Workers AI
- Free tier — 10K neurons/day free; enough for prototyping and low-volume production
- Model catalog — Browse
@cf/ models; Llama 3.1, Mistral, Stable Diffusion, Whisper, BGE all available
- Gateway for routing — Use AI Gateway for caching, rate limiting, analytics, and fallback to OpenAI/Anthropic
- R2 for storage — Store generated images, audio in R2 (S3-compatible); zero egress fees
- No GPU management — Cloudflare manages GPU fleet; you pay per inference, not per GPU-hour
1---2name: cloudflare-ai3description: >-4 You are an expert in Cloudflare Workers AI, the serverless AI inference5 platform running on Cloudflare's global network. You help developers run6 LLMs, embedding models, image generation, speech-to-text, and translation7 models at the edge with zero cold starts, pay-per-use pricing, and8 integration with Workers, Pages, and Vectorize — enabling AI features9 without managing GPU infrastructure.10license: Apache-2.011compatibility: ''12metadata:13 source: https://skillmd.com/skills/eliferjunior/cloudflare-ai14 author: terminal-skills15 version: 1.0.016 category: AI & Machine Learning17 tags:18 - cloudflare19 - workers-ai20 - edge21 - inference22 - llm23 - embeddings24 - serverless25---2627# Cloudflare Workers AI — AI Inference at the Edge2829You are an expert in Cloudflare Workers AI, the serverless AI inference platform running on Cloudflare's global network. You help developers run LLMs, embedding models, image generation, speech-to-text, and translation models at the edge with zero cold starts, pay-per-use pricing, and integration with Workers, Pages, and Vectorize — enabling AI features without managing GPU infrastructure.3031## Core Capabilities3233### AI Inference in Workers3435```typescript36// src/worker.ts — AI-powered API at the edge37export default {38 async fetch(request: Request, env: Env): Promise<Response> {39 const url = new URL(request.url);4041 // Text generation (LLM)42 if (url.pathname === "/api/chat") {43 const { messages } = await request.json();4445 const response = await env.AI.run("@cf/meta/llama-3.1-8b-instruct", {46 messages,47 max_tokens: 1024,48 temperature: 0.7,49 stream: true,50 });5152 return new Response(response, {53 headers: { "Content-Type": "text/event-stream" },54 });55 }5657 // Text embeddings (for RAG)58 if (url.pathname === "/api/embed") {59 const { text } = await request.json();6061 const embeddings = await env.AI.run("@cf/baai/bge-base-en-v1.5", {62 text: Array.isArray(text) ? text : [text],63 });6465 return Response.json({ embeddings: embeddings.data });66 }6768 // Image generation69 if (url.pathname === "/api/generate-image") {70 const { prompt } = await request.json();7172 const image = await env.AI.run("@cf/stabilityai/stable-diffusion-xl-base-1.0", {73 prompt,74 num_steps: 20,75 });7677 return new Response(image, {78 headers: { "Content-Type": "image/png" },79 });80 }8182 // Speech to text83 if (url.pathname === "/api/transcribe") {84 const audioData = await request.arrayBuffer();8586 const result = await env.AI.run("@cf/openai/whisper", {87 audio: [...new Uint8Array(audioData)],88 });8990 return Response.json({ text: result.text });91 }9293 // Translation94 if (url.pathname === "/api/translate") {95 const { text, source_lang, target_lang } = await request.json();9697 const result = await env.AI.run("@cf/meta/m2m100-1.2b", {98 text,99 source_lang,100 target_lang,101 });102103 return Response.json({ translated: result.translated_text });104 }105106 return new Response("Not Found", { status: 404 });107 },108};109```110111### RAG with Vectorize112113```typescript114// RAG pipeline: Embed → Store in Vectorize → Query → Generate115export default {116 async fetch(request: Request, env: Env): Promise<Response> {117 const { question } = await request.json();118119 // Step 1: Embed the question120 const queryEmbedding = await env.AI.run("@cf/baai/bge-base-en-v1.5", {121 text: [question],122 });123124 // Step 2: Search Vectorize125 const matches = await env.VECTORIZE.query(queryEmbedding.data[0], {126 topK: 5,127 returnMetadata: "all",128 });129130 // Step 3: Generate answer with context131 const context = matches.matches.map(m => m.metadata?.text).join("\n\n");132133 const answer = await env.AI.run("@cf/meta/llama-3.1-8b-instruct", {134 messages: [135 { role: "system", content: `Answer based on this context:\n${context}` },136 { role: "user", content: question },137 ],138 });139140 return Response.json({141 answer: answer.response,142 sources: matches.matches.map(m => ({ text: m.metadata?.text, score: m.score })),143 });144 },145};146```147148## Installation149150```bash151# Create Workers project152npm create cloudflare@latest my-ai-app153154# wrangler.toml155[ai]156binding = "AI"157158[[vectorize]]159binding = "VECTORIZE"160index_name = "my-index"161162# Deploy163npx wrangler deploy164```165166## Best Practices1671681. **Edge inference** — Models run on Cloudflare's network; <50ms latency worldwide, zero cold starts1692. **Streaming** — Use `stream: true` for LLM responses; first token in ~200ms at the edge1703. **Vectorize for RAG** — Use Cloudflare Vectorize for embedding storage; integrated with Workers AI1714. **Free tier** — 10K neurons/day free; enough for prototyping and low-volume production1725. **Model catalog** — Browse `@cf/` models; Llama 3.1, Mistral, Stable Diffusion, Whisper, BGE all available1736. **Gateway for routing** — Use AI Gateway for caching, rate limiting, analytics, and fallback to OpenAI/Anthropic1747. **R2 for storage** — Store generated images, audio in R2 (S3-compatible); zero egress fees1758. **No GPU management** — Cloudflare manages GPU fleet; you pay per inference, not per GPU-hour