How mg3labs-code/whatsapp_agent works
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: router.py Intent router · graph.py Orchestrator · database.py Database layer · faq.py FAQ agent
Components 21
Live runtime
Online message handling and response delivery.
- App entry · Process startup and application wiring.
app/main.py - Payload parse · Normalizes inbound WhatsApp provider payloads.
app/webhook/parser.py - Webhook route · Dispatches parsed webhook events into the app flow.
app/webhook/router.py
Core logic
Orchestration, agents, guardrails, and shared business rules.
- Orchestrator · Coordinates message flow, state transitions, and agent selection.
app/orchestrator/graph.py - Intent router · Chooses specialized handlers for a given user request.
app/agents/router.py - FAQ agent · Answers product and support questions from curated knowledge.
app/agents/faq.py - Pricing agent · Handles pricing and quote-oriented questions.
app/agents/pricing.py - Order agent · Manages order-related conversation steps.
app/agents/order.py - Qualification · Collects lead details and qualifies prospects.
app/agents/qualification.py - Lead scoring · Scores or prioritizes leads for follow-up.
app/agents/lead_scoring.py - Escalation · Routes to human support or fallback handling.
app/agents/escalation.py - Response check · Validates output before it is sent to the customer.
app/guardrails/check.py - Country rules · Locale and country-specific business constraints.
app/business/countries.py - Hours rules · Operational time and escalation timing rules.
app/business/hours.py
State & data
Persistence, schema evolution, and session state.
- Session manager · Loads and persists per-chat conversation state.
app/session/manager.py - Database layer · Database access, models, seed, and migration helpers.
app/db/database.py
Outbound integrations
Customer messaging and internal notifications.
- WhatsApp send · Sends replies back to the WhatsApp platform.
app/integrations/whatsapp.py - Slack alerts · Sends internal notifications for escalations and issues.
app/integrations/slack.py - Alerting · Shared alert dispatch for operational events.
app/integrations/alerts.py
Ingestion & tooling
Offline knowledge and catalog preparation.
- FAQ ingest · Builds and updates the FAQ corpus for runtime agents.
app/agents/faq_ingest.py - Ingest scripts · Document extraction, chunk normalization, probing, and catalog import tools.
scripts
Connections 23
- 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.