Cloudflare AI Gateway
Guia de Arquitectura: AI Gateway + Workers AI para Aplicaciones Enterprise
Sección titulada «Guia de Arquitectura: AI Gateway + Workers AI para Aplicaciones Enterprise»Version: 1.0.0 | Marzo 2026 Framework: AI Software Factory OS v7.7 Stack: Cloudflare (Workers, AI Gateway, Workers AI, D1, R2, Vectorize, KV, Durable Objects) Prerequisito: Cloudflare_Agents_Integration_Guide.md, Deployment_Strategy_Guide.md
1. Vision General
Sección titulada «1. Vision General»Esta guia define la arquitectura de referencia para aplicaciones enterprise que usan AI como componente central, desplegadas en Cloudflare edge. El patron separa responsabilidades en 4 capas: el Worker orquesta, AI Gateway controla, Workers AI ejecuta, y el Data Layer persiste.
Principio clave: La seleccion de modelos se ajusta en tiempo real desde el dashboard de AI Gateway sin tocar codigo de la aplicacion.
2. Arquitectura de 4 Capas
Sección titulada «2. Arquitectura de 4 Capas»CLIENTES (Browser / Mobile / API) │ ▼┌─────────────────────────────────────────────────────────┐│ CLOUDFLARE EDGE ││ ││ CAPA 1: Worker (App Layer — orquestador) ││ ├── Auth & Session ││ ├── Intent Classifier (tier: light/medium/heavy/agent) ││ ├── Context Builder (RAG si aplica) ││ └── Response Formatter ││ │ ││ CAPA 2: AI Gateway (Control Plane) ││ ├── Cache Layer (30-50% reduccion costos) ││ ├── Rate Limiting (por usuario/org) ││ ├── Budget Limits (por dia/semana/org) ││ ├── DLP Guard (PII scanning pre/post) ││ ├── Dynamic Routing (model selection sin codigo) ││ ├── Guardrails (content safety) ││ ├── Analytics (tokens, costos, latencia) ││ └── Logging (audit trail completo) ││ │ ││ CAPA 3: Model Providers ││ ├── Workers AI (primary — Llama, Qwen, DeepSeek) ││ ├── OpenAI (fallback) ││ ├── Anthropic (fallback) ││ └── Google (fallback) ││ │ ││ CAPA 4: Data Layer ││ ├── D1 (SQL — datos transaccionales) ││ ├── R2 (Object Storage — docs, audio, imagenes) ││ ├── Vectorize (Vector DB — embeddings para RAG) ││ ├── KV (Cache — sesiones, config, respuestas) ││ └── Durable Objects (State — sessions, rate limiters) │└─────────────────────────────────────────────────────────┘3. Capa 1: Worker — Intent Classification
Sección titulada «3. Capa 1: Worker — Intent Classification»El Worker clasifica cada operacion en un tier que determina que modelo usar:
| Tier | Operaciones | Modelo recomendado | Costo aprox. |
|---|---|---|---|
light | FAQ, navegacion, autocomplete, traduccion | Qwen3 30B / Llama 3.1 8B | $0.05/M tokens |
medium | Resumir registro, draft email, clasificar ticket | Llama 3.3 70B | $0.20/M tokens |
heavy | Analizar reporte, generar documento, soporte diagnostico | GPT-OSS 120B / GPT-4o | $0.50-2.50/M tokens |
reasoning | Razonamiento complejo, diagnostico, analisis multi-paso | DeepSeek R1 32B | $0.30/M tokens |
agent | Flujos multi-step con herramientas | Modelo tier heavy + tool calling | Variable |
embed | Embeddings para busqueda semantica | BGE-M3 | $0.01/M tokens |
speech | Transcripcion de audio | Whisper v3 Turbo | $0.006/min |
vision | Lectura de documentos/imagenes | Llama 3.2 Vision | $0.10/M tokens |
tts | Texto a voz | Kokoro TTS | $0.015/1K chars |
Regla del framework: El ai_partition_map.yaml del proyecto define que operaciones usan AI.
El Intent Classifier es la implementacion runtime de esa particion.
Ejemplo de implementacion
Sección titulada «Ejemplo de implementacion»// Mapa de operaciones a tiersconst INTENT_MAP: Record<string, Intent> = { // Operaciones simples (modelo barato) faq: { tier: "light", cache: true, rag: false }, navigation: { tier: "light", cache: true, rag: false }, translate: { tier: "light", cache: true, rag: false },
// Operaciones medias summarize: { tier: "medium", cache: false, rag: true }, classify_ticket: { tier: "light", cache: false, rag: false }, search_semantic: { tier: "embed", cache: false, rag: true },
// Operaciones complejas analyze_report: { tier: "heavy", cache: false, rag: true }, generate_report: { tier: "heavy", cache: false, rag: true },
// Media transcribe: { tier: "speech", cache: false, rag: false }, read_document: { tier: "vision", cache: false, rag: false },};4. Capa 2: AI Gateway — Control Plane
Sección titulada «4. Capa 2: AI Gateway — Control Plane»AI Gateway es el control plane de todas las llamadas a modelos AI. Se configura desde el dashboard de Cloudflare, sin cambiar codigo.
Features de control
Sección titulada «Features de control»| Feature | Funcion | Beneficio |
|---|---|---|
| Cache | Respuestas identicas desde cache | -30-50% costos, latencia ~5ms |
| Rate Limiting | Max requests/min por usuario/org | Previene abuso |
| Budget Limit | Max $/dia por org/usuario | Costos predecibles |
| DLP Guard | Escanea prompts/respuestas por PII | Compliance OWASP ASI-01 |
| Guardrails | Safety check pre/post modelo | Content safety |
| Dynamic Routing | Seleccion de modelo por condiciones | Optimizacion costo/calidad |
| Analytics | Dashboard tokens/costos/latencia | Visibilidad total |
| Logging | Audit trail de cada request | Compliance ISO 42001 |
| Retries | Re-intento automatico si modelo falla | Resiliencia |
| Fallbacks | Workers AI → OpenAI → Anthropic | Disponibilidad 99.9%+ |
| OTEL Tracing | Export a Datadog/Grafana | Observabilidad enterprise |
| Stripe Integration | Reportar uso a Stripe | Facturacion per-tenant |
Dynamic Routing — Seleccion de modelo sin codigo
Sección titulada «Dynamic Routing — Seleccion de modelo sin codigo»Request con metadata: { tier: "light", orgId: "poli-001" } │ ▼ ┌─ tier == "light"? ─┐ │ YES │ NO ▼ ▼ Budget OK? tier == "heavy"? │ YES │ YES ▼ ▼ Qwen3 30B GPT-OSS 120B │ falla? │ falla? ▼ ▼ Llama 3.1 8B Llama 3.3 70B │ falla? ▼ OpenAI GPT-4oEl poder: cambiar modelo, ajustar budgets, agregar fallbacks — desde el dashboard, sin deploy, sin PR, sin CI/CD.
5. Capa 3: Context Builder — RAG
Sección titulada «5. Capa 3: Context Builder — RAG»Cuando el intent requiere RAG (rag: true), se ejecuta el pipeline:
1. Embedding → BGE-M3 (Workers AI)2. Search → Vectorize (top-K similar)3. Fetch → D1 (contenido completo de docs)4. Rerank → BGE Reranker (precision)5. Return → Top-3 documentos como contextoIntegracion con el framework
Sección titulada «Integracion con el framework»| Artefacto baseline | Implementacion runtime |
|---|---|
knowledge_sources.yaml (F03) | Documentos indexados en Vectorize |
rag_pipeline skill | Pipeline: embed → search → rerank |
data_provenance_registry.yaml | Metadata de cada documento indexado |
data_classification.yaml | Filtro: no indexar docs restricted |
ai_cost_model.yaml (F04) | Costos de embeddings + inference |
6. Capa 4: Data Layer
Sección titulada «6. Capa 4: Data Layer»| Servicio | Uso | Equivalente framework |
|---|---|---|
| D1 (SQLite) | Datos transaccionales, audit log | data_dictionary.yaml schema |
| R2 (S3-compatible) | Documentos, audio, imagenes | Archivos de soporte |
| Vectorize | Embeddings para RAG | knowledge_sources.yaml |
| KV | Cache de sesiones, config, respuestas | Cache layer |
| Durable Objects | Estado de conversaciones, rate limiters | Stateful agents |
7. Mapeo a Framework (5 Capas)
Sección titulada «7. Mapeo a Framework (5 Capas)»| Capa framework | Componente runtime | Artefacto de diseño |
|---|---|---|
| Cognition | Worker (Intent Classifier) | ai_partition_map.yaml |
| Knowledge | Context Builder (RAG) + Vectorize | knowledge_sources.yaml, rag_pipeline skill |
| Execution | Workers AI + Model Providers | ai_cost_model.yaml, deployment skill |
| Control | AI Gateway (cache, limits, DLP, routing) | cost_management skill, pii_protection rule |
| Operations | AI Gateway Analytics + Logging | dora-metrics.py --dx-ai, monitoring_setup skill |
8. Mapeo a Compliance
Sección titulada «8. Mapeo a Compliance»| Control | Implementacion runtime |
|---|---|
| OWASP ASI-01 (Goal Hijack) | DLP Guard + Llama Guard pre-prompt |
| OWASP ASI-02 (Tool Misuse) | Guardrails + rate limiting |
| OWASP ASI-03 (Privilege Abuse) | Auth en Worker + budget per org |
| OWASP ASI-10 (Rogue Agents) | Budget limits + logging completo |
| ISO 42001 A.8 (Transparency) | AI Gateway logging (audit trail) |
| EU AI Act Art. 12 (Logging) | Cada request logueado con costo |
| Data Governance (PII) | DLP Guard pre/post modelo |
| Cost Control | Budget limits per tenant |
9. Costos Estimados
Sección titulada «9. Costos Estimados»Infraestructura Cloudflare (mensual)
Sección titulada «Infraestructura Cloudflare (mensual)»| Servicio | Uso estimado | Costo |
|---|---|---|
| Workers (compute) | 1M requests | ~$5 |
| D1 (storage) | 1GB | ~$2 |
| R2 (storage) | 10GB | ~$2 |
| Vectorize | 100K vectors | ~$5 |
| KV | 10M reads | ~$5 |
| AI Gateway | Included | $0 |
| Subtotal infra | ~$19/mes |
Workers AI (inference)
Sección titulada «Workers AI (inference)»| Tier | Requests/mes | Costo estimado |
|---|---|---|
| Light (8B-30B) | 50,000 | ~$5-15 |
| Medium (70B) | 10,000 | ~$10-20 |
| Heavy (120B+) | 2,000 | ~$10-30 |
| Embeddings | 100,000 | ~$2 |
| Subtotal AI | ~$27-67/mes |
Total: ~$50-90/mes para una app enterprise con AI
Sección titulada «Total: ~$50-90/mes para una app enterprise con AI»Comparado con API directa a OpenAI/Anthropic para el mismo volumen: ~$300-800/mes.
10. Cuando usar esta arquitectura
Sección titulada «10. Cuando usar esta arquitectura»Ideal para
Sección titulada «Ideal para»- Apps enterprise con multiples tipos de operacion AI
- Multi-tenant (cada org tiene su budget y config)
- Requisitos de compliance (audit trail, DLP, PII scanning)
- Necesidad de optimizar costos AI (cache + routing inteligente)
- Equipos que quieren cambiar modelos sin deploy
No ideal para
Sección titulada «No ideal para»- Aplicaciones que solo usan un modelo (no necesitan gateway)
- Prototipos sin requisitos de compliance
- Workloads que necesitan GPUs dedicadas (fine-tuning, training)
11. Checklist de Implementacion
Sección titulada «11. Checklist de Implementacion»- Crear proyecto Cloudflare Workers con Vite + Hono
- Configurar D1 (schema desde
data_dictionary.yaml) - Configurar R2 (storage de documentos)
- Configurar Vectorize (indice para RAG)
- Configurar KV (cache de sesiones)
- Implementar Intent Classifier (desde
ai_partition_map.yaml) - Implementar Context Builder (RAG pipeline)
- Crear AI Gateway en dashboard de Cloudflare
- Configurar Dynamic Routes (tier → modelo)
- Configurar Budget Limits por org/usuario
- Configurar DLP Guard (PII scanning)
- Configurar Logging (audit trail)
- Configurar Fallbacks (Workers AI → OpenAI → Anthropic)
- Implementar auth (Cloudflare Access o JWT)
- Deploy y verificar con
fab-kill-switch-drill.sh - Documentar costos en
ai_cost_model.yaml
Companion del AI Software Factory OS v7.7 See: Cloudflare_Agents_Integration_Guide.md, Deployment_Strategy_Guide.md, cost_management skill