Files
Skeen-CRM/README.md
root d30b22b50c feat: initial Skeen-CRM AI Agent architecture
- 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
2026-04-29 05:30:59 +00:00

211 lines
7.0 KiB
Markdown

# 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 |
| WhatsApp | 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
```bash
cd Skeen-CRM
```
### 2. Copiar variables de entorno
```bash
cp .env.example .env
# Editar .env con tus credenciales de Meta, OpenAI y ERPNext
```
### 3. Levantar infraestructura (PostgreSQL + Redis)
```bash
docker compose up -d postgres redis
```
### 4. Instalar dependencias con uv
```bash
pip install uv
uv venv .venv
source .venv/bin/activate
uv pip install -e ".[dev]"
```
### 5. Ejecutar migraciones
```bash
alembic upgrade head
```
### 6. Iniciar servidor de desarrollo
```bash
uvicorn src.main:app --reload --host 0.0.0.0 --port 8000
```
### 7. Iniciar worker de Celery (en otra terminal)
```bash
celery -A src.workers.celery_app worker --loglevel=info -Q default,whatsapp,erpnext,ai
```
## Deploy con Docker Compose (Producción)
```bash
docker compose up -d --build
```
Esto levanta:
- `api`: FastAPI (2 workers)
- `worker`: Celery worker (4 concurrentes)
- `scheduler`: Celery beat
- `postgres`: PostgreSQL + pgvector
- `redis`: Redis persistente
## Configuración de Webhook en Meta
1. Ir a [Meta Developers](https://developers.facebook.com/)
2. Seleccionar tu app de WhatsApp Business
3. En **Webhooks**, configurar:
- **Callback URL**: `https://tu-dominio.com/api/v1/webhooks/whatsapp`
- **Verify Token**: El valor de `META_WEBHOOK_VERIFY_TOKEN` en `.env`
- **Suscripción**: `messages`
## 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
```bash
# 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