Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 

Repository files navigation

🇺🇸 English · 🇨🇱 Español


🇺🇸 whatsapp-chatbot-engine

Production WhatsApp chatbot built on the Meta Cloud API. Receives queries via webhook, validates signatures, applies rate limiting, and uses a rule engine with an LLM fallback (Claude via Vertex AI) to answer operational queries from a Google Sheets data source.

Architecture

Meta (WhatsApp Cloud API)
        │ POST /webhook
        ▼
┌────────────────────────────────────────────────────┐
│  Webhook Handler                                   │
│  1. HMAC signature validation (x-hub-signature-256)│
│  2. Whitelist check (authorized numbers only)      │
│  3. Rate limiting per number + time window         │
│  4. Text-only filter (rejects images, audio, etc.) │
└──────────────────────┬─────────────────────────────┘
                       │
              ┌────────▼────────┐
              │   Rule Engine   │ → deterministic match
              └────────┬────────┘
                       │ no match
              ┌────────▼────────┐
              │  LLM Fallback   │ → Claude (structured JSON output)
              └────────┬────────┘
                       │
              ┌────────▼────────┐
              │  Google Sheets  │ → read-only data lookup
              └────────┬────────┘
                       │
              ┌────────▼────────┐
              │  WhatsApp API   │ → send response + audit log
              └─────────────────┘

Key Features

  • HMAC signature validation on every incoming webhook — invalid signatures are silently dropped
  • Whitelist-based access control — only pre-authorized numbers can interact with the bot
  • Rate limiting — prevents abuse and uncontrolled API costs per number
  • Hybrid rule engine + LLM: deterministic rules handle common queries instantly; LLM only activates for ambiguous input
  • Structured LLM output: Claude returns a validated JSON schema — no free-text parsing, no hallucinations about the data
  • Read-only data access: the bot never writes to any system. It queries → responds → logs.
  • Full audit trail: every query, response, and matched data record is logged with traceability

Security Design

The system enforces multiple layers before any query reaches the data:

  1. Signature verification (cryptographic)
  2. Number whitelist (operational access control)
  3. Rate limiting (abuse prevention)
  4. Read-only data source (zero write risk)
  5. Structured LLM output (no prompt injection leakage)

Mock Mode

The project auto-detects which credentials are configured and adapts per service:

Service Without credentials With real credentials
Data 5 simulated records Google Sheets (read-only)
LLM Deterministic rule engine only Claude via Anthropic API
WhatsApp Log to console Meta Cloud API

Stack

Node.js · TypeScript · Meta WhatsApp Cloud API · Claude (Anthropic) · Google Sheets API · Cloud Run

Deploy

npm install
cp .env.example .env
# Configure: META_APP_SECRET, WHATSAPP_TOKEN, SPREADSHEET_ID, ANTHROPIC_API_KEY

npm run dev         # local development
npm run build && npm start   # production

# Cloud Run deployment
./scripts/deploy.sh

🇨🇱 whatsapp-chatbot-engine

Chatbot de WhatsApp en producción, construido sobre la Meta Cloud API. Recibe consultas vía webhook, valida firmas HMAC, aplica rate limiting y usa un motor de reglas con fallback LLM (Claude) para responder consultas operacionales desde Google Sheets.

Arquitectura

Meta (WhatsApp Cloud API)
        │ POST /webhook
        ▼
┌────────────────────────────────────────────────────┐
│  Webhook Handler                                   │
│  1. Validación firma HMAC (x-hub-signature-256)    │
│  2. Verificación whitelist (solo números autorizados)│
│  3. Rate limiting por número + ventana de tiempo   │
│  4. Filtro solo-texto (rechaza imágenes, audio)    │
└──────────────────────┬─────────────────────────────┘
                       │
              ┌────────▼────────┐
              │ Motor de Reglas │ → match determinístico
              └────────┬────────┘
                       │ sin match
              ┌────────▼────────┐
              │  Fallback LLM   │ → Claude (output JSON estructurado)
              └────────┬────────┘
                       │
              ┌────────▼────────┐
              │  Google Sheets  │ → consulta solo-lectura
              └────────┬────────┘
                       │
              ┌────────▼────────┐
              │  WhatsApp API   │ → envía respuesta + audit log
              └─────────────────┘

Características Clave

  • Validación firma HMAC en cada webhook entrante — firmas inválidas se descartan silenciosamente
  • Control de acceso por whitelist — solo números preautorizados pueden interactuar
  • Rate limiting — previene abuso y costos de API descontrolados
  • Motor de reglas híbrido + LLM: las reglas determinísticas manejan consultas comunes al instante; el LLM solo se activa para input ambiguo
  • Output LLM estructurado: Claude devuelve un JSON Schema validado — sin parseo de texto libre, sin alucinaciones sobre los datos
  • Acceso de solo lectura: el bot nunca escribe en ningún sistema. Consulta → responde → registra.
  • Auditoría completa: cada consulta, respuesta y registro coincidente queda logueado con trazabilidad

Modo Maqueta (sin credenciales)

El proyecto detecta automáticamente qué credenciales están configuradas y se adapta:

Servicio Sin credenciales Con credenciales reales
Datos 5 registros simulados Google Sheets (solo lectura)
LLM Solo motor de reglas Claude vía API de Anthropic
WhatsApp Log a consola Meta Cloud API

Stack

Node.js · TypeScript · Meta WhatsApp Cloud API · Claude (Anthropic) · Google Sheets API · Cloud Run

Despliegue

npm install
cp .env.example .env
# Configurar: META_APP_SECRET, WHATSAPP_TOKEN, SPREADSHEET_ID, ANTHROPIC_API_KEY

npm run dev         # desarrollo local
npm run build && npm start   # producción

# Despliegue Cloud Run
./scripts/deploy.sh

About

Enterprise WhatsApp Meta Cloud API webhook engine with HMAC validation, rate limiting, and LLM fallback.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors