# mg3labs-code/whatsapp_agent architecture

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

- Interactive diagram: https://gitdiagram.com/mg3labs-code/whatsapp_agent
- Repository: https://github.com/mg3labs-code/whatsapp_agent

## Overview

1. **What this repo is**
   - `WASA` is a WhatsApp-based AI sales assistant. The runtime app is Python-based and appears to be deployed as a small service process (`Procfile`, `railway.toml`) with a single app entrypoint in `app/main.py`.

2. **Inbound channel boundary**
   - The primary ingress is a WhatsApp webhook path under `app/webhook/`.
   - `parser.py` normalizes provider payloads, and `router.py` dispatches parsed events into the application flow.
   - This is the clear edge between the external messaging platform and the internal agent/orchestration stack.

3. **Conversation orchestration**
   - `app/orchestrator/graph.py` is the central coordination layer.
   - It likely decides which agent handles a message, how state moves between steps, and when to escalate or return a final response.
   - This is the main “brain” boundary in the system: it sits above the specialized agents and below the webhook layer.

4. **Specialized agent layer**
   - `app/agents/` contains task-specific handlers:
     - `faq.py` for knowledge-base answers
     - `pricing.py` for pricing questions
     - `order.py` for order-related flows
     - `qualification.py` for lead qualification
     - `lead_scoring.py` for scoring or ranking leads
     - `escalation.py` for handoff to a human or fallback path
     - `router.py` for intent routing
     - `faq_ingest.py` for building/updating the FAQ corpus
   - Architecture-wise, these are domain workers behind the orchestrator rather than independent services.

5. **State and persistence**
   - `app/session/manager.py` suggests conversation/session state is persisted across messages.
   - `app/db/` contains the database layer: `database.py`, `models.py`, `seed.py`, and `migrate.py`.
   - Alembic migrations show the database is a first-class dependency, not a cache; it stores schema-backed business data and evolving conversation/support data.

6. **Domain/business rules**
   - `app/business/countries.py` and `app/business/hours.py` hold static operational rules.
   - These modules likely constrain qualification, availability, locale handling, and when escalation or human routing is appropriate.
   - They form a small but important policy layer separate from agent logic.

7. **Guardrails and response safety**
   - `app/guardrails/check.py` is a dedicated validation/safety boundary before output is sent.
   - This likely prevents malformed, out-of-policy, or unsupported responses from reaching WhatsApp.
   - It sits between generation/agent output and final delivery.

8. **Outbound integrations**
   - `app/integrations/whatsapp.py` is the sending side for customer-facing messages.
   - `app/integrations/slack.py` and `app/integrations/alerts.py` indicate an internal notification path, probably used for escalations, failures, or operational alerts.
   - So the system has two outward channels: customer comms via WhatsApp and staff/ops notifications via Slack.

9. **Knowledge and catalog ingestion**
   - The repo includes offline ingestion and analysis tooling under `scripts/` plus `app/agents/faq_ingest.py`.
   - Scripts for PDF/DOCX extraction, chunk normalization, FAQ probing, and product price-list import show that the assistant depends on curated source material rather than only live generation.
   - The FAQ and product catalog data appear to be maintained as an ingest pipeline feeding the runtime agents.

10. **Schema evolution and business data**
   - Alembic migrations include product catalog changes, schedule category additions, and lead-scoring client fields.
   - That implies the database schema tracks sales-oriented entities such as products, schedules, and lead metadata, not just chat logs.
   - The repository is therefore both an orchestration app and a business data system.

11. **Cross-cutting utilities**
   - `app/utils/security.py` and `app/utils/tracing.py` provide shared infrastructure concerns.
   - Security likely covers webhook/auth validation; tracing likely supports request/message observability across the webhook → orchestrator → integration path.

12. **Tests as architecture signals**
   - The test suite is broad and mirrors the package boundaries: agents, router, webhook, session, guardrails, DB, FAQ pipeline, escalation, integration scenarios.
   - That suggests the architecture is intentionally modular, with each major boundary independently testable.

13. **How a message likely flows**
   - External WhatsApp message arrives at the webhook.
   - Payload is parsed and routed.
   - Session/state is loaded, guardrails are checked, and the orchestrator selects an agent.
   - The chosen agent consults business rules and persisted data as needed.
   - A response is generated, validated, sent back through WhatsApp, and any exceptions/escalations can be pushed to Slack.

14. **Key diagram boundaries**
   - For an architecture diagram, the main boxes are: WhatsApp ingress, webhook parsing/routing, orchestration graph, agent set, persistence/session DB, business-rule helpers, guardrails, and outbound integrations/alerts.
   - The offline ingestion/scripts area should be shown separately from the live request path because it prepares knowledge and catalog data rather than serving messages directly.

Main entry points: [`app/agents/router.py`](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/router.py) (Intent router), [`app/orchestrator/graph.py`](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/orchestrator/graph.py) (Orchestrator), [`app/db/database.py`](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/db/database.py) (Database layer), [`app/agents/faq.py`](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/faq.py) (FAQ agent)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_live["Live runtime"]
  node_main["App entry<br/>service entrypoint<br/>[main.py]"]
  node_webhook_parser["Payload parse<br/>webhook adapter<br/>[parser.py]"]
  node_webhook_router["Webhook route<br/>request router<br/>[router.py]"]
end

subgraph group_core["Core logic"]
  node_orch_graph{{"Orchestrator<br/>conversation graph<br/>[graph.py]"}}
  node_agent_router["Intent router<br/>agent router<br/>[router.py]"]
  node_faq_agent["FAQ agent<br/>knowledge answerer<br/>[faq.py]"]
  node_pricing_agent["Pricing agent<br/>sales assistant<br/>[pricing.py]"]
  node_order_agent["Order agent<br/>order flow<br/>[order.py]"]
  node_qual_agent["Qualification<br/>[qualification.py]"]
  node_score_agent["Lead scoring<br/>lead ranking<br/>[lead_scoring.py]"]
  node_escalation_agent["Escalation<br/>handoff path<br/>[escalation.py]"]
  node_guardrails["Response check<br/>safety filter<br/>[check.py]"]
  node_countries["Country rules<br/>policy rules<br/>[countries.py]"]
  node_hours["Hours rules<br/>availability policy<br/>[hours.py]"]
end

subgraph group_data["State & data"]
  node_session_mgr[("Session manager<br/>conversation state<br/>[manager.py]")]
  node_db_layer[("Database layer<br/>persistence<br/>[database.py]")]
end

subgraph group_outbound["Outbound integrations"]
  node_whatsapp_out["WhatsApp send<br/>customer channel<br/>[whatsapp.py]"]
  node_slack_out["Slack alerts<br/>ops channel<br/>[slack.py]"]
  node_alerts["Alerting<br/>ops notifications<br/>[alerts.py]"]
end

subgraph group_ingest["Ingestion & tooling"]
  node_faq_ingest["FAQ ingest<br/>knowledge pipeline<br/>[faq_ingest.py]"]
  node_scripts["Ingest scripts<br/>offline tooling"]
end

node_main -->|"serve"| node_webhook_router
node_webhook_router -->|"parse"| node_webhook_parser
node_webhook_parser -->|"dispatch"| node_orch_graph
node_orch_graph -->|"select"| node_agent_router
node_agent_router -->|"faq"| node_faq_agent
node_agent_router -->|"pricing"| node_pricing_agent
node_agent_router -->|"order"| node_order_agent
node_agent_router -->|"qualify"| node_qual_agent
node_agent_router -->|"score"| node_score_agent
node_agent_router -->|"handoff"| node_escalation_agent
node_orch_graph -->|"state"| node_session_mgr
node_orch_graph -->|"validate"| node_guardrails
node_faq_agent -.->|"knowledge"| node_faq_ingest
node_faq_agent -->|"read/write"| node_db_layer
node_pricing_agent -->|"catalog"| node_db_layer
node_order_agent -->|"orders"| node_db_layer
node_qual_agent -->|"policy"| node_countries
node_qual_agent -->|"policy"| node_hours
node_escalation_agent -->|"notify"| node_slack_out
node_guardrails -->|"send"| node_whatsapp_out
node_alerts -->|"forward"| node_slack_out
node_faq_ingest -.->|"build"| node_scripts
node_scripts -.->|"seed"| node_db_layer

click node_main "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/main.py"
click node_webhook_parser "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/webhook/parser.py"
click node_webhook_router "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/webhook/router.py"
click node_orch_graph "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/orchestrator/graph.py"
click node_agent_router "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/router.py"
click node_faq_agent "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/faq.py"
click node_pricing_agent "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/pricing.py"
click node_order_agent "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/order.py"
click node_qual_agent "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/qualification.py"
click node_score_agent "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/lead_scoring.py"
click node_escalation_agent "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/escalation.py"
click node_guardrails "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/guardrails/check.py"
click node_countries "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/business/countries.py"
click node_hours "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/business/hours.py"
click node_session_mgr "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/session/manager.py"
click node_db_layer "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/db/database.py"
click node_whatsapp_out "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/integrations/whatsapp.py"
click node_slack_out "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/integrations/slack.py"
click node_alerts "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/integrations/alerts.py"
click node_faq_ingest "https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/faq_ingest.py"
click node_scripts "https://github.com/mg3labs-code/whatsapp_agent/tree/main/scripts"

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_main,node_webhook_parser,node_webhook_router toneBlue
class node_orch_graph,node_agent_router,node_faq_agent,node_pricing_agent,node_order_agent,node_qual_agent,node_score_agent,node_escalation_agent,node_guardrails,node_countries,node_hours toneAmber
class node_session_mgr,node_db_layer toneMint
class node_whatsapp_out,node_slack_out,node_alerts toneRose
class node_faq_ingest,node_scripts toneIndigo
```

## Components

### Live runtime

Online message handling and response delivery.

- [App entry](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/main.py): service entrypoint · Process startup and application wiring. · `app/main.py`
- [Payload parse](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/webhook/parser.py): webhook adapter · Normalizes inbound WhatsApp provider payloads. · `app/webhook/parser.py`
- [Webhook route](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/webhook/router.py): request router · Dispatches parsed webhook events into the app flow. · `app/webhook/router.py`

### Core logic

Orchestration, agents, guardrails, and shared business rules.

- [Orchestrator](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/orchestrator/graph.py): conversation graph · Coordinates message flow, state transitions, and agent selection. · `app/orchestrator/graph.py`
- [Intent router](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/router.py): agent router · Chooses specialized handlers for a given user request. · `app/agents/router.py`
- [FAQ agent](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/faq.py): knowledge answerer · Answers product and support questions from curated knowledge. · `app/agents/faq.py`
- [Pricing agent](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/pricing.py): sales assistant · Handles pricing and quote-oriented questions. · `app/agents/pricing.py`
- [Order agent](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/order.py): order flow · Manages order-related conversation steps. · `app/agents/order.py`
- [Qualification](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/qualification.py): lead qualification · Collects lead details and qualifies prospects. · `app/agents/qualification.py`
- [Lead scoring](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/lead_scoring.py): lead ranking · Scores or prioritizes leads for follow-up. · `app/agents/lead_scoring.py`
- [Escalation](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/escalation.py): handoff path · Routes to human support or fallback handling. · `app/agents/escalation.py`
- [Response check](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/guardrails/check.py): safety filter · Validates output before it is sent to the customer. · `app/guardrails/check.py`
- [Country rules](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/business/countries.py): policy rules · Locale and country-specific business constraints. · `app/business/countries.py`
- [Hours rules](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/business/hours.py): availability policy · Operational time and escalation timing rules. · `app/business/hours.py`

### State & data

Persistence, schema evolution, and session state.

- [Session manager](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/session/manager.py): conversation state · Loads and persists per-chat conversation state. · `app/session/manager.py`
- [Database layer](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/db/database.py): persistence · Database access, models, seed, and migration helpers. · `app/db/database.py`

### Outbound integrations

Customer messaging and internal notifications.

- [WhatsApp send](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/integrations/whatsapp.py): customer channel · Sends replies back to the WhatsApp platform. · `app/integrations/whatsapp.py`
- [Slack alerts](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/integrations/slack.py): ops channel · Sends internal notifications for escalations and issues. · `app/integrations/slack.py`
- [Alerting](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/integrations/alerts.py): ops notifications · Shared alert dispatch for operational events. · `app/integrations/alerts.py`

### Ingestion & tooling

Offline knowledge and catalog preparation.

- [FAQ ingest](https://github.com/mg3labs-code/whatsapp_agent/blob/main/app/agents/faq_ingest.py): knowledge pipeline · Builds and updates the FAQ corpus for runtime agents. · `app/agents/faq_ingest.py`
- [Ingest scripts](https://github.com/mg3labs-code/whatsapp_agent/tree/main/scripts): offline tooling · Document extraction, chunk normalization, probing, and catalog import tools. · `scripts`

## Connections

- App entry → Webhook route: serve · Application exposes the webhook handler.
- Webhook route → Payload parse: parse · Incoming payloads are normalized before routing.
- Payload parse → Orchestrator: dispatch · Parsed events enter the orchestration layer.
- Orchestrator → Intent router: select · Orchestrator chooses which specialized agent should handle the message.
- Intent router → FAQ agent: faq · Routes knowledge questions to FAQ handling.
- Intent router → Pricing agent: pricing · Routes pricing questions to pricing handling.
- Intent router → Order agent: order · Routes order flows to order handling.
- Intent router → Qualification: qualify · Routes lead-qualification conversations.
- Intent router → Lead scoring: score · Routes lead-scoring work.
- Intent router → Escalation: handoff · Routes fallback or human handoff cases.
- Orchestrator → Session manager: state · Conversation state is loaded and updated during flow execution.
- Orchestrator → Response check: validate · Generated or selected responses are checked before delivery.
- FAQ agent → FAQ ingest: knowledge · FAQ runtime depends on the curated FAQ corpus.
- FAQ agent → Database layer: read/write · FAQ and related business data are persisted in the database.
- Pricing agent → Database layer: catalog · Pricing logic consults persisted product and sales data.
- Order agent → Database layer: orders · Order flow interacts with stored business records.
- Qualification → Country rules: policy · Qualification uses country constraints.
- Qualification → Hours rules: policy · Qualification and handoff timing uses operational hours.
- Escalation → Slack alerts: notify · Escalations can alert staff through Slack.
- Response check → WhatsApp send: send · Validated responses are delivered to WhatsApp.
- Alerting → Slack alerts: forward · Alerting routes internal notifications to Slack.
- FAQ ingest → Ingest scripts: build · Offline scripts prepare source material for ingestion.
- Ingest scripts → Database layer: seed · Import and migration tooling updates database-backed business data.
