Workers AI + AI Gateway

Enterprise AI with security, caching, cost control & observability

๐Ÿ›ก๏ธ
Prompt Injection
OWASP LLM01 detection
๐Ÿ’ฐ
Cost Control
Token budgets & pricing
โšก
Semantic Cache
Hash-based deduplication
๐Ÿ”„
Fallback Chain
Auto model failover
๐Ÿ”’
DLP
PII & secrets detection
๐Ÿ“Š
Analytics
Request observability

๐Ÿงช Test AI Gateway

โœ“ Clean prompt ๐Ÿ”„ Cache test (repeat) โš ๏ธ PII test โš ๏ธ Secrets test ๐Ÿšซ Jailbreak ๐Ÿšซ Injection ๐Ÿšซ Extraction

๐Ÿ“ก Live Analysis

Estimated Tokens 0
Security Risk Low
Cache Probability 0%
Semantic Hash -

๐Ÿ“– How It Works

Integration
Security Layer
Caching
Fallback
// AI Gateway integration in ~10 lines
const response = await env.AI.run(
  "@cf/meta/llama-3.1-8b-instruct",
  { messages, max_tokens: 500 },
  {
    gateway: {
      id: "demo-gateway",
      skipCache: false,
      // Caching, rate limiting, logging handled automatically
    }
  }
);
// Multi-layer security checks
const security = analyzePrompt(prompt);

// 1. Prompt Injection Detection (OWASP LLM01)
if (security.promptInjection.detected) {
  return blocked("Injection attempt", security.patterns);
}

// 2. Jailbreak Detection
if (security.jailbreak.detected) {
  return blocked("Jailbreak", security.technique);
}

// 3. DLP - PII & Secrets
if (security.dlp.blocked) {
  return blocked("Sensitive data", security.dlp.detected);
}
// Semantic caching with hash-based deduplication
function analyzeCaching(prompt) {
  // Normalize: lowercase, sort words, remove punctuation
  const normalized = normalizePrompt(prompt);
  
  // Generate semantic hash
  const hash = computeHash(normalized);
  
  // Cache key for AI Gateway
  return {
    cacheKey: `ai-gateway:${hash}`,
    semanticHash: hash,
    // Similar prompts hit same cache entry!
    // "What is Workers?" === "what workers is?"
  };
}
// Automatic fallback chain
const FALLBACK_CHAIN = [
  { model: "@cf/meta/llama-3.1-8b-instruct", provider: "workers-ai" },
  { model: "@cf/meta/llama-3.1-70b-instruct", provider: "workers-ai" },
  { model: "gpt-3.5-turbo", provider: "openai" },
];

async function runWithFallback(prompt) {
  for (const { model, provider } of FALLBACK_CHAIN) {
    try {
      return await runModel(model, provider, prompt);
    } catch (e) {
      console.log(`${model} failed, trying next...`);
    }
  }
  throw new Error("All models failed");
}

๐Ÿ’ฐ Pricing Reference

Model Input ($/1M) Output ($/1M)
@cf/meta/llama-3.1-8b-instruct $0.00 $0.00
@cf/meta/llama-3.1-70b-instruct $0.00 $0.00
@cf/mistral/mistral-7b-instruct-v0.2 $0.00 $0.00
gpt-3.5-turbo $0.50 $1.50
gpt-4 $30.00 $60.00
gpt-4-turbo $10.00 $30.00
claude-3-opus $15.00 $75.00
claude-3-sonnet $3.00 $15.00

โœ“ Workers AI models are included free with Workers Paid plan