d30b22b50c34b1843ca684b7b7cd0b2f47d9fd84
- FastAPI + Python 3.12 backend - Meta WhatsApp Business API client (official) - OpenAI GPT-4o with function calling - RAG vector store with pgvector - ERPNext Frappe REST client - Celery + Redis async task queue - PostgreSQL with migrations (Alembic) - Docker Compose full stack - Enterprise logging, metrics, health checks
SKEEN CRM AI Agent
Agente de inteligencia artificial para WhatsApp Business API + ERPNext Healthcare.
Arquitectura
┌─────────────┐ ┌─────────────────────┐ ┌─────────────┐
│ Paciente │────▶│ WhatsApp Business │────▶│ Meta API │
│ (WhatsApp) │◀────│ API │◀────│ Webhooks │
└─────────────┘ └─────────────────────┘ └──────┬──────┘
│
┌────────────────────────┘
▼
┌─────────────────────┐
│ SKEEN AI Agent │ FastAPI + Python 3.12
│ (Este Repo) │
│ │
│ • OpenAI GPT-4o │
│ • RAG (pgvector) │
│ • Celery + Redis │
│ • PostgreSQL │
└──────────┬──────────┘
│
┌──────────┴──────────┐
▼ ▼
┌─────────────┐ ┌─────────────┐
│ ERPNext │ │ PostgreSQL │
│ Healthcare │ │ + pgvector │
└─────────────┘ └─────────────┘
Stack Tecnológico
| Capa | Tecnología |
|---|---|
| Web Framework | FastAPI + Uvicorn (HTTP/2) |
| Base de datos | PostgreSQL 16 + pgvector |
| Cola de tareas | Celery + Redis |
| IA / LLM | OpenAI GPT-4o + Embeddings |
| Meta Business API (oficial) | |
| CRM | ERPNext (Frappe Framework) |
| Observabilidad | Structlog + Prometheus |
| Deploy | Docker Compose |
Estructura del Proyecto
Skeen-CRM/
├── src/
│ ├── main.py # Entry point FastAPI
│ ├── config.py # Pydantic Settings
│ ├── api/
│ │ ├── v1/
│ │ │ ├── webhooks.py # Meta WhatsApp webhooks
│ │ │ ├── messages.py # API envío manual
│ │ │ └── health.py # Health checks
│ │ └── deps.py # Dependency injection
│ ├── domain/
│ │ ├── models/
│ │ │ └── conversation.py # Entidades SQLAlchemy
│ │ └── services/
│ ├── use_cases/
│ │ └── handle_incoming_message.py # Pipeline AI
│ ├── infrastructure/
│ │ ├── db.py # PostgreSQL async
│ │ ├── redis.py # Redis client
│ │ ├── whatsapp/
│ │ │ ├── client.py # Meta Graph API client
│ │ │ └── webhook.py # Webhook parser/validator
│ │ ├── ai/
│ │ │ ├── openai_client.py # OpenAI async client
│ │ │ ├── rag.py # Vector store pgvector
│ │ │ └── prompts.py # Tools & prompts
│ │ └── erpnext/
│ │ └── client.py # Frappe REST API client
│ └── workers/
│ ├── celery_app.py # Celery configuration
│ └── tasks.py # Background tasks
├── alembic/ # Database migrations
├── docker-compose.yml # Full stack local
├── Dockerfile # Production image
└── pyproject.toml # Dependencies (uv)
Requisitos
- Python 3.12+
- Docker + Docker Compose
- Cuenta de WhatsApp Business API (Meta)
- API Key de OpenAI
- Instancia de ERPNext (para integración completa)
Instalación Local
1. Clonar y entrar al directorio
cd Skeen-CRM
2. Copiar variables de entorno
cp .env.example .env
# Editar .env con tus credenciales de Meta, OpenAI y ERPNext
3. Levantar infraestructura (PostgreSQL + Redis)
docker compose up -d postgres redis
4. Instalar dependencias con uv
pip install uv
uv venv .venv
source .venv/bin/activate
uv pip install -e ".[dev]"
5. Ejecutar migraciones
alembic upgrade head
6. Iniciar servidor de desarrollo
uvicorn src.main:app --reload --host 0.0.0.0 --port 8000
7. Iniciar worker de Celery (en otra terminal)
celery -A src.workers.celery_app worker --loglevel=info -Q default,whatsapp,erpnext,ai
Deploy con Docker Compose (Producción)
docker compose up -d --build
Esto levanta:
api: FastAPI (2 workers)worker: Celery worker (4 concurrentes)scheduler: Celery beatpostgres: PostgreSQL + pgvectorredis: Redis persistente
Configuración de Webhook en Meta
- Ir a Meta Developers
- Seleccionar tu app de WhatsApp Business
- En Webhooks, configurar:
- Callback URL:
https://tu-dominio.com/api/v1/webhooks/whatsapp - Verify Token: El valor de
META_WEBHOOK_VERIFY_TOKENen.env - Suscripción:
messages
- Callback URL:
Tools / Funciones del Agente
El agente usa OpenAI Function Calling para ejecutar acciones:
| Tool | Descripción |
|---|---|
search_catalog |
Busca servicios/productos en catálogo vía RAG |
check_availability |
Consulta disponibilidad de citas en ERPNext |
create_appointment |
Crea cita médica en ERPNext Healthcare |
get_patient_info |
Consulta historial del paciente |
get_wallet_balance |
Consulta saldo de monedero |
escalate_to_human |
Escalar a agente humano |
Endpoints API
| Método | Endpoint | Descripción |
|---|---|---|
| GET | /health |
Liveness probe |
| GET | /ready |
Readiness probe (incluye DB) |
| GET | /metrics |
Métricas Prometheus |
| GET | /api/v1/webhooks/whatsapp |
Verificación Meta |
| POST | /api/v1/webhooks/whatsapp |
Recepción mensajes |
| POST | /api/v1/messages/text |
Enviar texto manual |
| POST | /api/v1/messages/template |
Enviar plantilla |
| POST | /api/v1/messages/buttons |
Enviar botones |
Testing
# Unit tests
pytest tests/ -v
# With coverage
pytest tests/ --cov=src --cov-report=html
Seguridad
- ✅ Verificación de firma HMAC en webhooks (producción)
- ✅ Tokens JWT no usados (usa API Keys de Meta)
- ✅ Rate limiting implementado por número de teléfono
- ✅ Sanitización de inputs antes de enviar a LLM
- ✅ Logging sin exponer datos PHI (solo últimos 4 dígitos de teléfono)
Licencia
Propietario - SKEEN Clínica de Belleza
Description
Languages
Python
98.4%
Dockerfile
1.1%
Mako
0.5%