# luigivalentino/voicely-code architecture

> Architecture diagram of the GitHub repository luigivalentino/voicely-code, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-15). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/luigivalentino/voicely-code
- Repository: https://github.com/luigivalentino/voicely-code

## Overview

1. **Propósito y forma general**
   Voicely es un SaaS multi-tenant para atención al cliente por WhatsApp con IA. El repositorio es principalmente un backend Flask monolítico modular: una misma aplicación sirve UI web, API REST, webhooks, lógica de negocio y orquestación de IA, mientras que el procesamiento pesado se delega a Celery workers.

2. **Punto de entrada y composición de la app**
   El núcleo está en `backend/app/__init__.py` con el patrón app factory `create_app`. Ahí se ensamblan extensiones, configuración por entorno, blueprints y seguridad. `extensions.py` centraliza dependencias como SQLAlchemy, migraciones, Flask-Security, sesión en Redis y probablemente Celery.

3. **Capas de exposición**
   Hay tres superficies principales:
   - **Frontend server-side** en `app/routes/` con Jinja2 + Tailwind para landing, auth y dashboard.
   - **REST API** en `app/api/` para conversaciones, mensajes, salud y estadísticas.
   - **Webhooks** en `app/api/webhooks_*.py` para WhatsApp, Mercado Pago, Chatwoot y n8n.  
   Estas entradas convergen hacia los servicios y modelos comunes del backend.

4. **Dominio y persistencia**
   El modelo de datos vive en `app/models/` y cubre usuarios/roles, compañías, planes (`Pack`), conversaciones, mensajes, notas, pagos, tickets, recordatorios, plantillas WhatsApp, estados de servicio y suscripciones. La persistencia es PostgreSQL con SQLAlchemy y migraciones Alembic/Flask-Migrate. El diseño refleja multi-tenancy por `Company`, con separación lógica por organización.

5. **Flujo principal de mensajes**
   El flujo crítico arranca desde WhatsApp Cloud API hacia el webhook de WhatsApp. Desde allí se crea o actualiza conversación/mensaje y se deriva trabajo asíncrono a Celery. Si el mensaje trae audio, pasa por ASR; si es texto, entra directo al pipeline IA. El resultado final se guarda y se envía de vuelta a WhatsApp.

6. **Pipeline de IA en dos niveles**
   La lógica conversacional está separada en `app/agents/`:
   - **Router**: clasifica intención y decide si responder, transferir o cerrar.
   - **Generator**: genera la respuesta final cuando corresponde.  
   Los prompts están externalizados en `app/agents/prompts/` por contexto de negocio (`general`, `restaurante`, `consultorio`, `servicios_tecnicos`). La capa de IA usa OpenRouter como proxy y modelos Claude distintos para enrutamiento y generación.

7. **ASR y mensajes de audio**
   `app/services/asr.py` integra Groq Whisper Large v3 para transcribir audios, aceptando bytes o URL. La transcripción forma parte del pipeline de entrada antes de la clasificación del Router. Esto es importante para el diagrama porque el audio no se procesa dentro del request web principal, sino mediante tareas diferidas.

8. **Servicios de negocio y orquestación**
   La lógica se distribuye en `app/services/`: booking, availability, integrations, notification, takeover, message storage, chatwoot, mercadopago, wsp, etc. `orchestrator.py` sugiere coordinación entre servicios y tareas, mientras `debounce_service.py` y `takeover_service.py` reflejan reglas de control de conversación. Esta capa es el puente entre API/webhooks y el dominio.

9. **Procesamiento asíncrono**
   `app/tasks/` contiene las tareas Celery para ASR, respuesta, mensajería WhatsApp, notificaciones y suscripciones. El README indica que el broker es Redis y que hay worker y beat separados. En la arquitectura, Celery absorbe las etapas costosas o reintentables: transcripción, generación IA y envío externo.

10. **Integraciones externas**
   Los servicios externos relevantes son:
   - **WhatsApp Cloud API** para entrada/salida de mensajes.
   - **OpenRouter** para inferencia LLM.
   - **Groq** para ASR.
   - **Mercado Pago** para suscripciones/pagos.
   - **Chatwoot** para sincronización de conversaciones.
   - **n8n** como posible automatizador de eventos.  
   Estas integraciones son boundary points claros del sistema.

11. **Seguridad y aislamiento**
   La app usa Flask-Security para autenticación, CSRF con SeaSurf, HSTS con Talisman y sesiones en Redis. El repositorio menciona RLS en PostgreSQL vía `app.current_user_id`, lo que refuerza el aislamiento por tenant. También hay rate limiting en Nginx para login y webhooks.

12. **Infraestructura de ejecución**
   `docker-compose.yml` levanta seis servicios: `app` (Flask/Gunicorn), `worker`, `beat`, `postgres`, `redis` y `nginx`. Nginx actúa como reverse proxy y límite de tasa; Gunicorn con gevent atiende la app; Redis sirve de broker, cache y sesiones. Esto define un despliegue claramente desacoplado entre web, background jobs y datos.

13. **Observabilidad y verificación**
   El stack menciona Langfuse y Sentry como observabilidad, y el health check verifica base de datos y Redis. Hay tests de modelos, rutas y API en `backend/tests/`, además de evaluaciones Promptfoo para prompts del Router y Generator. Esto indica que la calidad de IA y la integridad de endpoints forman parte del diseño operativo, no solo del código.

14. **Qué dibujar en un diagrama**
   Un diagrama correcto debería mostrar: usuarios/web/WhatsApp entrando a Nginx; Nginx enruta a Flask; Flask persiste en PostgreSQL y usa Redis; Flask dispara tareas a Celery; Celery llama a Groq, OpenRouter, WhatsApp y Mercado Pago; y la UI web/REST comparten el mismo backend y base de datos. El límite principal del sistema está entre la capa síncrona de Flask y la capa asíncrona de Celery/integraciones externas.

Main entry points: [`backend/app/__init__.py`](https://github.com/luigivalentino/voicely-code/blob/master/backend/app/__init__.py) (App factory), [`backend/app/api`](https://github.com/luigivalentino/voicely-code/tree/master/backend/app/api) (API layer), [`backend/app/services`](https://github.com/luigivalentino/voicely-code/tree/master/backend/app/services) (Business services), [`backend/app/tasks`](https://github.com/luigivalentino/voicely-code/tree/master/backend/app/tasks) (Task queue)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_grp_runtime["Runtime"]
  node_n_run(("run.py<br/>entrypoint<br/>[run.py]"))
  node_n_celery(("Celery app<br/>worker entrypoint<br/>[celery_app.py]"))
end

subgraph group_grp_backend["Backend"]
  node_n_init["App factory<br/>flask core<br/>[__init__.py]"]
  node_n_ext["Extensions<br/>shared infra<br/>[extensions.py]"]
  node_n_routes["Web UI<br/>server-side routes"]
  node_n_api["API layer<br/>REST/webhooks"]
  node_n_models[("Domain models<br/>ORM models")]
  node_n_services["Business services<br/>orchestration"]
  node_n_tasks["Task queue<br/>celery tasks"]
end

subgraph group_grp_ai["AI Pipeline"]
  node_n_agents{{"Agents<br/>LLM logic"}}
  node_n_prompts["Prompts<br/>prompt assets"]
  node_n_openrouter(("OpenRouter<br/>llm gateway<br/>[openrouter.py]"))
  node_n_asr(("ASR<br/>speech-to-text<br/>[asr.py]"))
end

subgraph group_grp_infra["Infrastructure"]
  node_n_wsp(("WhatsApp<br/>messaging gateway<br/>[wsp_service.py]"))
  node_n_mp(("Mercado Pago<br/>payments gateway"))
  node_n_chatwoot(("Chatwoot<br/>support sync"))
  node_n_db[("PostgreSQL<br/>primary database")]
  node_n_redis[("Redis<br/>cache/broker<br/>[redis_pool.py]")]
  node_n_nginx["Nginx<br/>reverse proxy<br/>[default.conf]"]
end

node_n_run -->|"starts"| node_n_init
node_n_celery -->|"runs"| node_n_tasks
node_n_init -->|"configures"| node_n_ext
node_n_init -->|"mounts"| node_n_routes
node_n_init -->|"mounts"| node_n_api
node_n_init -->|"binds"| node_n_models
node_n_init -->|"uses"| node_n_services
node_n_api -->|"delegates"| node_n_services
node_n_routes -->|"reads/writes"| node_n_services
node_n_services -->|"persists"| node_n_models
node_n_services -->|"queries"| node_n_db
node_n_ext -->|"shares"| node_n_redis
node_n_tasks -->|"calls"| node_n_asr
node_n_tasks -->|"calls"| node_n_agents
node_n_tasks -->|"sends"| node_n_wsp
node_n_tasks -->|"processes"| node_n_mp
node_n_services -->|"syncs"| node_n_chatwoot
node_n_agents -->|"loads"| node_n_prompts
node_n_agents -->|"invokes"| node_n_openrouter
node_n_api -->|"webhooks"| node_n_wsp
node_n_api -->|"webhooks"| node_n_mp
node_n_api -->|"webhooks"| node_n_chatwoot
node_n_nginx -->|"proxies"| node_n_run
node_n_nginx -->|"routes"| node_n_api
node_n_run -->|"uses"| node_n_redis
node_n_run -->|"uses"| node_n_db

click node_n_run "https://github.com/luigivalentino/voicely-code/blob/master/backend/run.py"
click node_n_celery "https://github.com/luigivalentino/voicely-code/blob/master/backend/celery_app.py"
click node_n_init "https://github.com/luigivalentino/voicely-code/blob/master/backend/app/__init__.py"
click node_n_ext "https://github.com/luigivalentino/voicely-code/blob/master/backend/app/extensions.py"
click node_n_routes "https://github.com/luigivalentino/voicely-code/tree/master/backend/app/routes"
click node_n_api "https://github.com/luigivalentino/voicely-code/tree/master/backend/app/api"
click node_n_models "https://github.com/luigivalentino/voicely-code/tree/master/backend/app/models"
click node_n_services "https://github.com/luigivalentino/voicely-code/tree/master/backend/app/services"
click node_n_tasks "https://github.com/luigivalentino/voicely-code/tree/master/backend/app/tasks"
click node_n_agents "https://github.com/luigivalentino/voicely-code/tree/master/backend/app/agents"
click node_n_prompts "https://github.com/luigivalentino/voicely-code/tree/master/backend/app/agents/prompts"
click node_n_openrouter "https://github.com/luigivalentino/voicely-code/blob/master/backend/app/services/openrouter.py"
click node_n_asr "https://github.com/luigivalentino/voicely-code/blob/master/backend/app/services/asr.py"
click node_n_wsp "https://github.com/luigivalentino/voicely-code/blob/master/backend/app/services/wsp_service.py"
click node_n_mp "https://github.com/luigivalentino/voicely-code/blob/master/backend/app/services/mercadopago_service.py"
click node_n_chatwoot "https://github.com/luigivalentino/voicely-code/blob/master/backend/app/services/chatwoot_service.py"
click node_n_db "https://github.com/luigivalentino/voicely-code/tree/master/backend/migrations"
click node_n_redis "https://github.com/luigivalentino/voicely-code/blob/master/backend/app/services/redis_pool.py"
click node_n_nginx "https://github.com/luigivalentino/voicely-code/blob/master/backend/nginx/default.conf"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_n_run,node_n_celery toneBlue
class node_n_init,node_n_ext,node_n_routes,node_n_api,node_n_models,node_n_services,node_n_tasks toneAmber
class node_n_agents,node_n_prompts,node_n_openrouter,node_n_asr toneMint
class node_n_wsp,node_n_mp,node_n_chatwoot,node_n_db,node_n_redis,node_n_nginx toneRose
```

## Components

### Runtime

Execution entrypoints and deployment surface

- [run.py](https://github.com/luigivalentino/voicely-code/blob/master/backend/run.py): entrypoint · App bootstrap · `backend/run.py`
- [Celery app](https://github.com/luigivalentino/voicely-code/blob/master/backend/celery_app.py): worker entrypoint · Background task bootstrap · `backend/celery_app.py`

### Backend

Flask app, routes, domain, and services

- [App factory](https://github.com/luigivalentino/voicely-code/blob/master/backend/app/__init__.py): flask core · create_app composition root · `backend/app/__init__.py`
- [Extensions](https://github.com/luigivalentino/voicely-code/blob/master/backend/app/extensions.py): shared infra · SQLAlchemy, Redis, security, migration wiring · `backend/app/extensions.py`
- [Web UI](https://github.com/luigivalentino/voicely-code/tree/master/backend/app/routes): server-side routes · Landing, auth, dashboard, docs · `backend/app/routes`
- [API layer](https://github.com/luigivalentino/voicely-code/tree/master/backend/app/api): REST/webhooks · Conversations, messages, subscriptions, inbound webhooks · `backend/app/api`
- [Domain models](https://github.com/luigivalentino/voicely-code/tree/master/backend/app/models): ORM models · Users, companies, conversations, payments, subscriptions · `backend/app/models`
- [Business services](https://github.com/luigivalentino/voicely-code/tree/master/backend/app/services): orchestration · Booking, notification, WhatsApp, payment, takeover, storage · `backend/app/services`
- [Task queue](https://github.com/luigivalentino/voicely-code/tree/master/backend/app/tasks): celery tasks · Async ASR, response, messaging, notifications, subscriptions · `backend/app/tasks`

### AI Pipeline

Routing, generation, and prompt management

- [Agents](https://github.com/luigivalentino/voicely-code/tree/master/backend/app/agents): LLM logic · Router and generator for conversation decisions · `backend/app/agents`
- [Prompts](https://github.com/luigivalentino/voicely-code/tree/master/backend/app/agents/prompts): prompt assets · Context-specific system prompts · `backend/app/agents/prompts`
- [OpenRouter](https://github.com/luigivalentino/voicely-code/blob/master/backend/app/services/openrouter.py): llm gateway · LLM inference proxy · `backend/app/services/openrouter.py`
- [ASR](https://github.com/luigivalentino/voicely-code/blob/master/backend/app/services/asr.py): speech-to-text · Audio transcription via Groq Whisper · `backend/app/services/asr.py`

### Infrastructure

Database, cache, workers, and proxy

- [WhatsApp](https://github.com/luigivalentino/voicely-code/blob/master/backend/app/services/wsp_service.py): messaging gateway · Cloud API send/receive integration · `backend/app/services/wsp_service.py`
- [Mercado Pago](https://github.com/luigivalentino/voicely-code/blob/master/backend/app/services/mercadopago_service.py): payments gateway · Subscriptions and payment webhooks · `backend/app/services/mercadopago_service.py`
- [Chatwoot](https://github.com/luigivalentino/voicely-code/blob/master/backend/app/services/chatwoot_service.py): support sync · Conversation synchronization · `backend/app/services/chatwoot_service.py`
- [PostgreSQL](https://github.com/luigivalentino/voicely-code/tree/master/backend/migrations): primary database · Multi-tenant persistence with RLS · `backend/migrations`
- [Redis](https://github.com/luigivalentino/voicely-code/blob/master/backend/app/services/redis_pool.py): cache/broker · Sessions, cache, and Celery broker · `backend/app/services/redis_pool.py`
- [Nginx](https://github.com/luigivalentino/voicely-code/blob/master/backend/nginx/default.conf): reverse proxy · TLS termination and rate limiting · `backend/nginx/default.conf`

## Connections

- run.py → App factory: starts · Gunicorn/Flask bootstraps the application
- Celery app → Task queue: runs · Celery worker executes async jobs
- App factory → Extensions: configures · Registers shared extensions and security
- App factory → Web UI: mounts · Serves server-side pages
- App factory → API layer: mounts · Serves REST and webhook endpoints
- App factory → Domain models: binds · Application context uses ORM models
- App factory → Business services: uses · Requests delegate into business services
- API layer → Business services: delegates · API/webhooks hand off to service layer
- Web UI → Business services: reads/writes · Dashboard and auth use shared business logic
- Business services → Domain models: persists · Service layer stores business state
- Business services → PostgreSQL: queries · SQLAlchemy/Postgres persistence
- Extensions → Redis: shares · Sessions, cache, and broker access
- Task queue → ASR: calls · Audio jobs transcribe voice notes
- Task queue → Agents: calls · Response jobs invoke router and generator
- Task queue → WhatsApp: sends · Background delivery to WhatsApp
- Task queue → Mercado Pago: processes · Subscription and payment jobs
- Business services → Chatwoot: syncs · Conversation synchronization boundary
- Agents → Prompts: loads · Context-specific system prompts
- Agents → OpenRouter: invokes · LLM routing and generation requests
- API layer → WhatsApp: webhooks · Inbound and outbound WhatsApp flow
- API layer → Mercado Pago: webhooks · Payment gateway callbacks
- API layer → Chatwoot: webhooks · Support platform callbacks
- Nginx → run.py: proxies · Reverse proxy to Flask app
- Nginx → API layer: routes · External HTTP entry surface
- run.py → Redis: uses · Runtime sessions/cache integration
- run.py → PostgreSQL: uses · Primary persistence connection
