Workers AI
Use this skill when adding AI inference to a Worker. Separate model selection, prompt design, cost control, and observability.
Decision rules
- Use Workers AI when operational simplicity, binding-based access, and Cloudflare-native deployment matter.
- Use AI Gateway when requests need centralized observability, caching, rate controls, fallback, or multi-provider routing.
- Use external model providers when required model quality, fine-tuning, modalities, or SLAs exceed Workers AI's fit.
- Do not assume edge inference is automatically low latency for every model or geography; measure.
Binding
{
"ai": { "binding": "AI" }
}
export interface Env {
AI: Ai;
}
Text generation pattern
export async function answerQuestion(env: Env, question: string) {
const response = await env.AI.run("@cf/meta/llama-3.1-8b-instruct", {
messages: [
{ role: "system", content: "Answer clearly and concisely. Do not invent facts." },
{ role: "user", content: question }
],
max_tokens: 512
});
return response;
}
Verify model IDs and parameter names against the current model catalog.
Embeddings pattern
export async function embed(env: Env, text: string) {
const result = await env.AI.run("@cf/baai/bge-base-en-v1.5", { text });
return result.data[0];
}
Prompt safety and output shape
- Put invariant rules in the system message.
- Include the user's task and constraints explicitly.
- For JSON output, ask for a schema and validate the result after parsing.
- Never trust model output for authorization, billing, or safety-critical decisions without deterministic checks.
- Add token caps and refusal/unknown behavior.
Observability
Log:
- Model name.
- Request ID.
- Tenant/user ID hash or safe identifier.
- Prompt class, not necessarily full prompt text.
- Token counts where available.
- Latency and error type.
- Fallback path.
Cost controls
- Summarize or retrieve context before generation.
- Set
max_tokens.
- Cache deterministic or public AI results where safe.
- Use smaller/cheaper models for classification and routing.
- Avoid sending entire documents when chunks will do.
Anti-patterns
- Blindly forwarding user input and trusting the answer.
- Using generation for deterministic validation that should be code.
- No model fallback or user-visible error strategy.
- No token budget.
- RAG prompt includes retrieved text but answer is not constrained to it.
1---2name: workers-ai3description: Write Cloudflare Workers AI and AI Gateway code for model inference, prompts, streaming, token budgets, model selection, observability, and fallback design. Use when adding LLM, embeddings, summarization, classification, or generation to Workers.4---5# Workers AI67Use this skill when adding AI inference to a Worker. Separate model selection, prompt design, cost control, and observability.89## Decision rules1011- Use Workers AI when operational simplicity, binding-based access, and Cloudflare-native deployment matter.12- Use AI Gateway when requests need centralized observability, caching, rate controls, fallback, or multi-provider routing.13- Use external model providers when required model quality, fine-tuning, modalities, or SLAs exceed Workers AI's fit.14- Do not assume edge inference is automatically low latency for every model or geography; measure.1516## Binding1718```jsonc19{20 "ai": { "binding": "AI" }21}22```2324```ts25export interface Env {26 AI: Ai;27}28```2930## Text generation pattern3132```ts33export async function answerQuestion(env: Env, question: string) {34 const response = await env.AI.run("@cf/meta/llama-3.1-8b-instruct", {35 messages: [36 { role: "system", content: "Answer clearly and concisely. Do not invent facts." },37 { role: "user", content: question }38 ],39 max_tokens: 51240 });4142 return response;43}44```4546Verify model IDs and parameter names against the current model catalog.4748## Embeddings pattern4950```ts51export async function embed(env: Env, text: string) {52 const result = await env.AI.run("@cf/baai/bge-base-en-v1.5", { text });53 return result.data[0];54}55```5657## Prompt safety and output shape5859- Put invariant rules in the system message.60- Include the user's task and constraints explicitly.61- For JSON output, ask for a schema and validate the result after parsing.62- Never trust model output for authorization, billing, or safety-critical decisions without deterministic checks.63- Add token caps and refusal/unknown behavior.6465## Observability6667Log:6869- Model name.70- Request ID.71- Tenant/user ID hash or safe identifier.72- Prompt class, not necessarily full prompt text.73- Token counts where available.74- Latency and error type.75- Fallback path.7677## Cost controls7879- Summarize or retrieve context before generation.80- Set `max_tokens`.81- Cache deterministic or public AI results where safe.82- Use smaller/cheaper models for classification and routing.83- Avoid sending entire documents when chunks will do.8485## Anti-patterns8687- Blindly forwarding user input and trusting the answer.88- Using generation for deterministic validation that should be code.89- No model fallback or user-visible error strategy.90- No token budget.91- RAG prompt includes retrieved text but answer is not constrained to it.