# Omnichannel & WhatsApp AI Customer Support Bot — Complete AI & LLM Reference Corpus (`llms-full.txt`) - Repository: https://github.com/mohan-n-swamy/freshchat-bot-public - Web Discovery URL: https://mohan-n-swamy.github.io/repos/freshchat-bot-public/ - License: MIT - Keywords: whatsapp-bot, customer-support, ai-chatbot, webhook, redis, llm-agents, typescript, conversational-ai, eval-harness, helpdesk --- ## File: `AI-README.md` — AI-README.md --- repo: "mohan-n-swamy/freshchat-bot-public" title: "Omnichannel & WhatsApp AI Customer Support Bot" license: "MIT" keywords: [whatsapp-bot, customer-support, ai-chatbot, webhook, redis, llm-agents, typescript, conversational-ai, eval-harness, helpdesk] capabilities: - "Multi-channel webhook adapters (`src/channels/adapters.py`) normalizing **Freshchat**, **Chatwoot**, and **WhatsApp Cloud API** events." - "HMAC SHA-256 webhook signature verification (`src/webhook/hmac_verify.py`) and Redis `SETNX` `conv_lock` burst deduplication." - "Zero-LLM-cost noise & echo filter (`src/domain/noise_filter.py`) dropping stray acknowledgments, CSAT ratings, and bot echoes." - "Five deterministic policy guards (`src/domain/guards/`): `NEVER_INTERRUPT_HUMAN`, `AUTH_GATE`, `PARTNER_ORDER`, `REPORT_SUPPRESSION`, and `READ_ONLY`." - "Pluggable async `CRMClient`, `OMSClient`, and `CatalogClient` (`src/domain/enrichment/`) plus voice-note STT support (`src/domain/media/`)." - "Zero-credential CLI simulation (`bin/bot-demo.py`), golden-set eval harness (`bin/eval-harness.py`), and 161 passing pytest cases." when_to_use: - "A production-hardened FastAPI omnichannel customer support bot for Freshchat, self-hosted Chatwoot, and WhatsApp Cloud API featuring HMAC-verified webhooks, atomic Redis `SETNX` conversation locks, zero-cost noise filtering, caller-phone PII authentication gates, pluggable CRM/Order/Catalog adapters, and 161 automated tests." - "Tutorial chatbots wire an LLM directly to a webhook and fail on day one of production traffic: webhook retries trigger triple replies, stray 'Thank you!' messages burn tokens and reopen resolved tickets, bots talk over live human agents, and unverified order lookups leak customer PII. `freshchat-bot-public` packages the complete 7-layer deterministic-first pipeline used in high-volume omnichannel support." inputs_required: - "CHANNEL_PROVIDER: Active helpdesk channel (`chatwoot`, `freshchat`, or `whatsapp_cloud`)" - "WEBHOOK_HMAC_SECRET: Shared HMAC secret for inbound webhook verification" - "CHATWOOT_BASE_URL: Base URL of your Chatwoot instance (`chatwoot-public` compatible)" - "REDIS_URL: Redis connection URL for `conv_lock` deduplication and catalog cache" - "CRM_API_BASE: Your customer CRM lookup endpoint" - "OMS_API_BASE: Your Order Management System status endpoint" - "ANTHROPIC_API_KEY: API key for structured LLM comprehension & reply synthesis" quickstart: - "python3 bin/bot-demo.py # run 3-channel offline routing & dedup simulation" - "python3 bin/eval-harness.py # run golden-set policy evaluation" - "pytest -q tests/ # run all 161 unit & integration tests" - "uvicorn src.webhook.app:app --port 8000 # start FastAPI webhook server" --- # Omnichannel & WhatsApp AI Customer Support Bot — Machine-Readable Agent Guide A production-hardened FastAPI omnichannel customer support bot for Freshchat, self-hosted Chatwoot, and WhatsApp Cloud API featuring HMAC-verified webhooks, atomic Redis `SETNX` conversation locks, zero-cost noise filtering, caller-phone PII authentication gates, pluggable CRM/Order/Catalog adapters, and 161 automated tests. Tutorial chatbots wire an LLM directly to a webhook and fail on day one of production traffic: webhook retries trigger triple replies, stray 'Thank you!' messages burn tokens and reopen resolved tickets, bots talk over live human agents, and unverified order lookups leak customer PII. `freshchat-bot-public` packages the complete 7-layer deterministic-first pipeline used in high-volume omnichannel support. Key modules and entry points in this repository: - `src/webhook/app.py & handler.py`: FastAPI application, health probe, HMAC verification, and background task dispatch - `src/channels/adapters.py`: Webhook normalizers for Freshchat, Chatwoot, WhatsApp Cloud API, and `InMemoryDemoAdapter` - `src/domain/pipeline.py`: 7-layer orchestrator with emergency fallback handoff guarantee - `src/domain/guards/`: Deterministic `auth_gate`, `partner_order`, `report_suppress`, and human-assignment guards - `src/domain/enrichment/`: `CRMClient`, `OMSClient`, `CatalogClient`, and local `KnowledgeBase` - `src/domain/llm/`: Prompt builder, provider chain, and post-LLM output validator - `bin/bot-demo.py & bin/eval-harness.py`: Zero-credential local simulation and golden-set regression runner - `tests/`: 161-test suite covering guards, HMAC, phone normalization, escalation routing, and pipeline recovery Every organization-specific value enters through `.env` (copied from `.env.example`) or external adapter files. No source edit is needed to change organization names, endpoints, database URLs, webhook secrets, or thresholds. When a human asks an AI coding agent to deploy or adapt `freshchat-bot-public` into their stack: 1. Run `python3 bin/bot-demo.py` and `pytest -q tests/` locally to verify the pipeline without external keys. 2. Edit `src/domain/enrichment/oms_client.py` and `catalog_client.py` (or point `OMS_API_BASE` / `CATALOG_API_BASE` in `.env`) to map your order status codes and SKU catalog. 3. Adjust your intent taxonomy in `src/domain/intents/taxonomy.py` and team escalation map in `src/domain/escalation/routing.py`. 4. Add 20-50 representative transcripts from your domain to `data/golden_eval_cases.json` and gate CI with `python3 bin/eval-harness.py`. - Product Requirements: `docs/PRD.md` - Working-Backwards PR-FAQ: `docs/PR-FAQ.md` - High-Level Architecture: `docs/HLD.md` - Low-Level Interfaces & Runbook: `docs/LLD.md` - Coding Agent Rules: `AGENTS.md` --- ## File: `.env.example` — Environment Contract (.env.example) ```ini # freshchat-bot-public — Production Omnichannel & WhatsApp AI Support Bot CHANNEL_PROVIDER=chatwoot WEBHOOK_HMAC_SECRET=replace_with_webhook_hmac_secret CHATWOOT_BASE_URL=http://localhost:3000 CHATWOOT_API_TOKEN=replace_with_bot_access_token FRESHCHAT_API_URL=https://api.freshchat.com/v2 FRESHCHAT_API_TOKEN=replace_with_freshchat_token REDIS_URL=redis://localhost:6379/0 CONV_LOCK_TTL=45 CRM_API_BASE=https://crm.ops.example.org/api OMS_API_BASE=https://oms.ops.example.org/api CATALOG_API_BASE=https://catalog.ops.example.org/api ANTHROPIC_API_KEY=replace_with_llm_api_key OPERATING_HOURS_START=08:00 OPERATING_HOURS_END=22:00 OPERATING_TIMEZONE=UTC ``` --- ## File: `AGENTS.md` — AGENTS.md # AGENTS.md — Omnichannel & WhatsApp AI Customer Support Bot Read this file first before modifying `freshchat-bot-public`. ## Purpose A production-hardened FastAPI omnichannel customer support bot for Freshchat, self-hosted Chatwoot, and WhatsApp Cloud API featuring HMAC-verified webhooks, atomic Redis `SETNX` conversation locks, zero-cost noise filtering, caller-phone PII authentication gates, pluggable CRM/Order/Catalog adapters, and 161 automated tests. ## Commands ```bash python3 bin/bot-demo.py # run 3-channel offline routing & dedup simulation python3 bin/eval-harness.py # run golden-set policy evaluation pytest -q tests/ # run all 161 unit & integration tests uvicorn src.webhook.app:app --port 8000 # start FastAPI webhook server ``` ## Module Map - `src/webhook/app.py & handler.py`: FastAPI application, health probe, HMAC verification, and background task dispatch - `src/channels/adapters.py`: Webhook normalizers for Freshchat, Chatwoot, WhatsApp Cloud API, and `InMemoryDemoAdapter` - `src/domain/pipeline.py`: 7-layer orchestrator with emergency fallback handoff guarantee - `src/domain/guards/`: Deterministic `auth_gate`, `partner_order`, `report_suppress`, and human-assignment guards - `src/domain/enrichment/`: `CRMClient`, `OMSClient`, `CatalogClient`, and local `KnowledgeBase` - `src/domain/llm/`: Prompt builder, provider chain, and post-LLM output validator - `bin/bot-demo.py & bin/eval-harness.py`: Zero-credential local simulation and golden-set regression runner - `tests/`: 161-test suite covering guards, HMAC, phone normalization, escalation routing, and pipeline recovery ## Invariants 1. Keep all organization names, credentials, domains, and thresholds in `.env` or external config files. Never hardcode company names, host IPs, or secrets in source files. 2. Deterministic business logic belongs in code and lookup tables, not inside LLM prompts. 3. Update `docs/HLD.md`, `docs/LLD.md`, and `.env.example` in the same commit whenever an interface or environment variable changes. 4. Run the repository smoke check and secret scan before opening a pull request. --- ## File: `docs/PRD.md` — Product Requirements Document (docs/PRD.md) # Product Requirements Document — Omnichannel & WhatsApp AI Customer Support Bot A production-hardened FastAPI omnichannel customer support bot for Freshchat, self-hosted Chatwoot, and WhatsApp Cloud API featuring HMAC-verified webhooks, atomic Redis `SETNX` conversation locks, zero-cost noise filtering, caller-phone PII authentication gates, pluggable CRM/Order/Catalog adapters, and 161 automated tests. ## 1. Problem Tutorial chatbots wire an LLM directly to a webhook and fail on day one of production traffic: webhook retries trigger triple replies, stray 'Thank you!' messages burn tokens and reopen resolved tickets, bots talk over live human agents, and unverified order lookups leak customer PII. `freshchat-bot-public` packages the complete 7-layer deterministic-first pipeline used in high-volume omnichannel support. ## 2. Users and Jobs-to-be-Done | Persona | Job-to-be-Done | |---|---| | Support Engineering Team | Deploy an AI front-line bot on Chatwoot, Freshchat, or WhatsApp Cloud that resolves routine order/catalog questions and hands edge cases to the right specialist queue. | | Security & Privacy Lead | Enforce caller-phone ownership checks (`AUTH_GATE`) and PII-masked structured logging outside the LLM prompt. | | AI Quality Owner | Gate prompt and routing changes against deterministic golden test cases (`bin/eval-harness.py`) and 161 unit/integration tests. | ## 3. Core Capabilities - Multi-channel webhook adapters (`src/channels/adapters.py`) normalizing **Freshchat**, **Chatwoot**, and **WhatsApp Cloud API** events. - HMAC SHA-256 webhook signature verification (`src/webhook/hmac_verify.py`) and Redis `SETNX` `conv_lock` burst deduplication. - Zero-LLM-cost noise & echo filter (`src/domain/noise_filter.py`) dropping stray acknowledgments, CSAT ratings, and bot echoes. - Five deterministic policy guards (`src/domain/guards/`): `NEVER_INTERRUPT_HUMAN`, `AUTH_GATE`, `PARTNER_ORDER`, `REPORT_SUPPRESSION`, and `READ_ONLY`. - Pluggable async `CRMClient`, `OMSClient`, and `CatalogClient` (`src/domain/enrichment/`) plus voice-note STT support (`src/domain/media/`). - Zero-credential CLI simulation (`bin/bot-demo.py`), golden-set eval harness (`bin/eval-harness.py`), and 161 passing pytest cases. ## 4. Configurable Inputs Adopters configure the system for their own organization without editing core application logic: | Variable | Default / Example | Purpose | |---|---|---| | `CHANNEL_PROVIDER` | `chatwoot` | Active helpdesk channel (`chatwoot`, `freshchat`, or `whatsapp_cloud`) | | `WEBHOOK_HMAC_SECRET` | `replace_me` | Shared HMAC secret for inbound webhook verification | | `CHATWOOT_BASE_URL` | `http://localhost:3000` | Base URL of your Chatwoot instance (`chatwoot-public` compatible) | | `REDIS_URL` | `redis://localhost:6379/0` | Redis connection URL for `conv_lock` deduplication and catalog cache | | `CRM_API_BASE` | `https://crm.ops.example.org/api` | Your customer CRM lookup endpoint | | `OMS_API_BASE` | `https://oms.ops.example.org/api` | Your Order Management System status endpoint | | `ANTHROPIC_API_KEY` | `sk-ant-...` | API key for structured LLM comprehension & reply synthesis | ## 5. Phasing and Stability Exit Criteria 1. **Phase 1 (Local Synthetic Run):** Clone the repository, copy `.env.example` to `.env`, and run the quickstart commands against synthetic seed data. Exit criterion: smoke checks pass with zero external credentials. 2. **Phase 2 (Read-Only Shadow Wiring):** Connect read-only credentials or webhook listeners in shadow/dry-run mode. Exit criterion: 100 consecutive events or queries reconcile cleanly against source records. 3. **Phase 3 (Production Cutover):** Enable live writes, alerts, or routing behind bounded retry and idempotency guards. ## 6. Non-Goals - Shipping organization-specific business rules hardcoded in application source. - Storing credentials, personal customer records, or tenant URLs inside version control. - Replacing deterministic validation or arithmetic with unconstrained model prompts. --- ## File: `docs/PR-FAQ.md` — Working-Backwards PR-FAQ (docs/PR-FAQ.md) # Working-Backwards PR-FAQ — Omnichannel & WhatsApp AI Customer Support Bot **Release Summary:** `freshchat-bot-public` gives engineering and operations teams a self-hosted, open-source implementation of Omnichannel & WhatsApp AI Customer Support Bot that configures via `.env` and runs on standard infrastructure in minutes. ## Press Release Operations and engineering teams often rebuild the same internal workflows behind closed doors or pay per-seat SaaS markups for rigid tools that cannot match their field reality. `freshchat-bot-public` open-sources a battle-tested implementation of Omnichannel & WhatsApp AI Customer Support Bot, stripped of all single-company assumptions and packaged with clear adapter boundaries, synthetic demo data, and machine-readable agent documentation. Any team can fork `freshchat-bot-public`, supply their own `.env` inputs and taxonomy config, and deploy locally or in production with Docker, Python, or Node. AI coding assistants such as Claude Code, Codex, and Cursor can read `AI-README.md` and `llms.txt` to wire custom ERP, CRM, or warehouse adapters in a single session. ## External Adopter FAQ **Q1: How long does it take to run locally after cloning?** Under five minutes. Copy `.env.example` to `.env` and run the quickstart commands in `README.md`. Synthetic fixtures let you inspect the workflow before connecting live credentials. **Q2: Do I need to rewrite source files to use my own company name, channels, or rules?** No. Organization names, endpoints, thresholds, and credentials sit in `.env` and declarative config files. External system specifics live behind narrow adapter modules documented in `docs/LLD.md`. **Q3: What license governs this repository?** MIT License. You can fork, modify, self-host, and use it commercially without restriction. ## Internal Engineering & Security FAQ **Q4: How do we prevent tenant or employer data from ever entering a public fork?** The repository starts from a clean git history, excludes raw exports and binary dumps, validates every commit through `gitleaks`, and ships only synthetic fixtures. **Q5: What happens when an upstream API or model provider is slow or unavailable?** Inbound webhooks persist raw payloads before processing, outbound writes carry idempotency keys with bounded exponential backoff, and model-backed paths fail open to deterministic rules or explicit human queues. --- ## File: `docs/HLD.md` — High-Level Design (docs/HLD.md) # High-Level Design (HLD) — Omnichannel & WhatsApp AI Customer Support Bot A production-hardened FastAPI omnichannel customer support bot for Freshchat, self-hosted Chatwoot, and WhatsApp Cloud API featuring HMAC-verified webhooks, atomic Redis `SETNX` conversation locks, zero-cost noise filtering, caller-phone PII authentication gates, pluggable CRM/Order/Catalog adapters, and 161 automated tests. ## 1. System Topology ```mermaid flowchart LR Ingress["Freshchat / Chatwoot / WhatsApp"] --> HMAC["HMAC Verify + 200 OK"] HMAC --> Lock["Redis SETNX conv_lock"] Lock --> Noise["Noise & CSAT Filter"] Noise --> Enrich["CRM / OMS / Catalog Enricher"] Enrich --> Guards["5 Deterministic Policy Guards"] Guards -->|"safe free-form"| LLM["Validated LLM Router"] Guards -->|"human / complex"| Escalate["Team Queue + Private Note"] LLM --> Outbound["Channel Reply Dispatcher"] ``` ## 2. Architectural Decisions and Rejected Alternatives | Decision | Why It Holds | Rejected Alternative | |---|---|---| | Deterministic guards before and after the LLM | Guarantees `NEVER_INTERRUPT_HUMAN`, `AUTH_GATE`, and operating-hours behavior regardless of model temperature or prompt phrasing. | Single end-to-end tool-calling agent prompt | | Per-conversation Redis `SETNX` TTL lock (`conv_lock:{id}`) | Prevents concurrent LLM calls when a user sends 4 short WhatsApp messages in 3 seconds or when a BSP retries delivery. | Stateless per-request webhook handlers | | Pluggable `CRMClient` / `OMSClient` / `CatalogClient` enrichment | Separates external HTTP schemas from core guard and escalation logic so any e-commerce, logistics, or service team can wire their own APIs in one afternoon. | Inline SQL or vendor SDK calls scattered across prompt builders | ## 3. Data Flow and Failure Boundaries 1. **Configuration Boundary:** Startup validates `.env` variables and declarative config schemas before accepting traffic or running scheduled jobs. 2. **Adapter Boundary:** External services (databases, chat channels, HRMS, warehouses, or LLM providers) sit behind explicit adapter modules so failures stay isolated and testable with local mocks. 3. **Observability and Audit:** State transitions and job executions emit structured logs and deterministic status records rather than mutating state silently. ## 4. Scaling Notes - **1x to 10x load:** Single-node Docker Compose or process supervisor handles standard team workloads with indexed database queries and bounded worker concurrency. - **First bottleneck at 10x+:** High-frequency webhook or batch ingestion queues; mitigate by separating the stateless HTTP receiver from background worker processes sharing Redis or PostgreSQL locks. --- ## File: `docs/LLD.md` — Low-Level Design & Runbook (docs/LLD.md) # Low-Level Design (LLD) & Operations Runbook — Omnichannel & WhatsApp AI Customer Support Bot This document defines the module responsibilities, environment contract, and operational procedures for `freshchat-bot-public`. ## 1. Module and File Inventory | Path | Responsibility | |---|---| | `src/webhook/app.py & handler.py` | FastAPI application, health probe, HMAC verification, and background task dispatch | | `src/channels/adapters.py` | Webhook normalizers for Freshchat, Chatwoot, WhatsApp Cloud API, and `InMemoryDemoAdapter` | | `src/domain/pipeline.py` | 7-layer orchestrator with emergency fallback handoff guarantee | | `src/domain/guards/` | Deterministic `auth_gate`, `partner_order`, `report_suppress`, and human-assignment guards | | `src/domain/enrichment/` | `CRMClient`, `OMSClient`, `CatalogClient`, and local `KnowledgeBase` | | `src/domain/llm/` | Prompt builder, provider chain, and post-LLM output validator | | `bin/bot-demo.py & bin/eval-harness.py` | Zero-credential local simulation and golden-set regression runner | | `tests/` | 161-test suite covering guards, HMAC, phone normalization, escalation routing, and pipeline recovery | ## 2. Environment Variable Contract | Variable | Default / Example | Required | Description | |---|---|---|---| | `CHANNEL_PROVIDER` | `chatwoot` | Yes | Active helpdesk channel (`chatwoot`, `freshchat`, or `whatsapp_cloud`) | | `WEBHOOK_HMAC_SECRET` | `replace_me` | Yes | Shared HMAC secret for inbound webhook verification | | `CHATWOOT_BASE_URL` | `http://localhost:3000` | Yes | Base URL of your Chatwoot instance (`chatwoot-public` compatible) | | `REDIS_URL` | `redis://localhost:6379/0` | Yes | Redis connection URL for `conv_lock` deduplication and catalog cache | | `CRM_API_BASE` | `https://crm.ops.example.org/api` | Yes | Your customer CRM lookup endpoint | | `OMS_API_BASE` | `https://oms.ops.example.org/api` | Yes | Your Order Management System status endpoint | | `ANTHROPIC_API_KEY` | `sk-ant-...` | Yes | API key for structured LLM comprehension & reply synthesis | ## 3. Extension Recipe 1. Run `python3 bin/bot-demo.py` and `pytest -q tests/` locally to verify the pipeline without external keys. 2. Edit `src/domain/enrichment/oms_client.py` and `catalog_client.py` (or point `OMS_API_BASE` / `CATALOG_API_BASE` in `.env`) to map your order status codes and SKU catalog. 3. Adjust your intent taxonomy in `src/domain/intents/taxonomy.py` and team escalation map in `src/domain/escalation/routing.py`. 4. Add 20-50 representative transcripts from your domain to `data/golden_eval_cases.json` and gate CI with `python3 bin/eval-harness.py`. ## 4. Operations Runbook ### 1. Run offline multi-channel simulation ```bash python3 bin/bot-demo.py ``` ### 2. Run full pytest & golden eval gates ```bash python3 bin/eval-harness.py && pytest -q tests/ ``` ### 3. Deploy with Docker Compose alongside Redis ```bash docker compose -f deploy/docker-compose.yml up -d --build ``` --- ## File: `docs/RESEARCH-2026.md` — 2026 Research & Landscape Notes (docs/RESEARCH-2026.md) # 2026 Omnichannel & WhatsApp Support AI Architecture Research ## 1. Why Pure-Prompt Support Bots Fail in Production Across 2026 production WhatsApp Cloud API, Freshchat, and Chatwoot deployments, the top failure modes are infrastructure and state bugs rather than model intelligence: 1. **Webhook Retry Storms:** Meta Cloud API and Freshchat retry webhooks if synchronous LLM calls exceed timeout thresholds, sending duplicate replies unless deduplicated via atomic Redis `SETNX` locks. 2. **PII Cross-Talk (`AUTH_GATE`):** Customers frequently forward order IDs from family members or third-party partners; without deterministic phone-to-order ownership verification before prompt assembly, LLMs leak private status details. 3. **Human/Bot Collision:** Once a human agent claims a conversation, the bot must deterministically mute (`NEVER_INTERRUPT_HUMAN`) rather than racing the human agent. 4. **Off-Hours False Promises:** Promising "connecting you to an agent now" at 02:00 when no agents are staffed destroys trust; operating-hours awareness must queue morning follow-ups honestly. ## 2. Architecture Applied in `freshchat-bot-public` - **Multi-Channel Ingress Normalization (`src/channels/adapters.py`):** Decouples Freshchat, Chatwoot, and Meta WhatsApp Cloud payload shapes from core domain guards. - **7-Stage Deterministic-First Pipeline (`src/domain/pipeline.py`):** Executes HMAC verification, `conv_lock` deduplication, noise/CSAT filtering (`$0` model spend), CRM/OMS enrichment, and 5 hard guards *before* invoking Claude/OpenAI/local LLMs. - **Offline Simulation & Golden Eval (`bin/bot-demo.py`, `bin/eval-harness.py`):** Enables local verification in seconds with zero external credentials.