The problem
Agents ran their client conversations on WhatsApp from their own numbers. Those conversations, and the brochures and documents shared in them, stayed on individual phones, where the business could not see, search or learn from them.
The brief had two parts: capture every conversation reliably, then give agents an assistant that could step in when a conversation broke down, without ever inventing a price or an availability.
Follow one message
Scroll the diagram sideways to see all of it.
A client messages an agent
Agents keep using WhatsApp on their own numbers. Coexistence mode with the Cloud API sends every message to the system as a webhook.
The webhook verifies and queues it
A FastAPI service checks the request's signature, puts the message on an SQS queue and acknowledges at once, so a slow step downstream never loses a message.
Ingest stores it exactly once
Workers upsert each message keyed on WhatsApp's message ID and the agent's number, and remove it from the queue only after it is stored. Duplicate and out-of-order deliveries are harmless.
Media is saved with the conversation
Photos, PDFs and voice notes are downloaded by media ID with retries and refreshed links, checksummed and stored encrypted in S3.
The assistant notices a stall
It steps in when the agent types /assist, the client waits more than 20 minutes, a question repeats or the tone turns negative.
Retrieval finds real listings
Filter by the client's requirements, broaden if too few match, re-rank the top 15 with pgvector and pass the best three with reason codes. No match means one clarifying question, never a guess.
A small model drafts the reply
A low-cost model writes in the agent's style and escalates once only when retrieval is thin. The agent sends the draft; only scheduling is answered automatically, within each agent's budget.
How I built it
I delivered it in three phases, each with its own definition of done, so the business got value from the first week and the riskier AI work rested on proven foundations.
Phase 1: capture everything
- Agents kept their app. WhatsApp's coexistence mode with the Cloud API let agents carry on using the normal app on their own numbers while every message reached the system.
- A webhook that never drops work. A FastAPI service verifies each request's signature, puts the message on a queue and returns immediately, so a slow step downstream never loses a message.
- Duplicates are harmless. WhatsApp delivers webhooks at least once and not always in order. Ingest workers write each message as an upsert keyed on WhatsApp's message ID and the agent's number, and remove it from the queue only after it is stored, so a failure is retried and a repeat is ignored.
- Media kept with the conversation. Media workers download photos, PDFs and voice notes by media ID, refresh expired links, retry with backoff, record a SHA-256 checksum and store the file encrypted in S3.
- Pilot first. One agent went live first; more agents joined once capture was stable.
Phase 2: data readiness and assist mode
- Clean, labelled data. Conversations were split into turn pairs and labelled with intent and outcome in a small in-house tagging tool. Phone numbers, emails and addresses were masked before any text was used for training or analysis.
- Knowing when to step in. A conversation counts as broken down when the agent types
/assist, when a client waits more than 20 minutes, when the same question is asked twice, or when negative-sentiment keywords appear. - Assist before takeover. The assistant drafts replies for the agent to send. It answers on its own only for scheduling, and an agent can switch it off for any chat with
/bot off. - The agent's own voice. Style comes from retrieval over the agent's past replies, with the last 20 to 30 turns and the client's stated requirements as context. Outside WhatsApp's 24-hour window, only an approved utility template is sent.
Phase 3: grounded replies
- The brokerage's own data. Listings and transactions were synced into PostgreSQL with pgvector embeddings and an HNSW index.
- Retrieval that explains itself. The assistant filters listings by the client's requirements, broadens the search if too few match, re-ranks the top 15 by meaning and passes the best three to the model with reason codes. Every answer records the listing IDs it used.
- No guessing. If nothing matches, the assistant asks exactly one clarifying question instead of making something up.
Key decisions
- Make capture complete before making it clever. Everything downstream, from labels to retrieval, depends on complete data, so capture shipped first and runs independently of the assistant.
- Small models by default, with hard cost caps. Routine turns use small, low-cost models such as GPT-5 Nano and Gemini 2.5 Flash-Lite. The router escalates once to Gemini 2.5 Flash only when retrieval returns fewer than two valid listings. Prompts are capped at 3,000 to 5,000 tokens in and 300 out, and each agent has a monthly budget with an alert at 70% and a hard cap.
- Retrieval before fine-tuning. Retrieval with example replies came first. Fine-tuning, such as per-agent LoRA adapters on a self-hosted model, stayed an option only if the data showed a need.
- In real estate, an invented fact is the worst failure. Grounding rules, listing IDs in every trace and a weekly audit for invented facts made that failure visible and rare.
Quality and evaluation
- A golden set of more than 150 real prompts, scored every week for whether the top three results held a valid listing, factual accuracy, correct use of the clarifying question and style similarity.
- Blind reviews of 20 random drafts a week by two agents, checking whether the draft could pass as the agent's own reply.
- Ten per cent of conversations labelled twice to check consistency, with a Cohen's kappa target of 0.75.
- An incident playbook: if an invented fact is reported, takeover is switched off, the cause is fixed in the prompt or retrieval, and a post-mortem follows within 48 hours.
Security and privacy
- Agents see only their own conversations, enforced by row-level security; analysts get read-only, masked access.
- Access logs go to a separate, immutable bucket and are kept for 180 days.
- A per-contact deletion job removes that person's messages, media and embeddings on request.
- Data is encrypted in transit with TLS 1.2+ and at rest in PostgreSQL and S3. Secrets live in AWS Systems Manager, rotate every 90 days, and workers use short-lived credentials.
- Agents' WhatsApp profiles carry a consent line explaining that conversations may be used for quality and training.
Infrastructure and operations
- AWS, defined in Terraform: services on Amazon ECS behind a load balancer, SQS queues, PostgreSQL, S3 with KMS encryption, and Kinesis Firehose streaming messages into the data lake.
- Separate development, staging and production environments. CI runs linting, unit and integration tests and database migrations, and releases go out behind feature flags with a 10% canary.
- Dashboards for ingest volume and errors, assistant triggers, retrieval matches, token spend by model and cost per agent, with alarms routed through CloudWatch and SNS.
- Runbooks for replaying failed webhooks, re-downloading media, deleting a person's data and running migrations. Daily PostgreSQL snapshots, with S3 lifecycle rules moving old media to cheaper storage.
- Tests beyond unit tests: contract tests on sample webhook payloads for every message type, a load test of 50 messages a minute for 30 minutes with zero loss, and a chaos test that kills a media worker mid-download to prove retries work.
Targets I set: at least 99% of messages captured, media saved within 60 seconds at p95, assistant drafts within 5 seconds and takeover replies within 8 seconds at p95, a top-three retrieval hit rate of at least 95% on the golden set, and no more than USD 25 per agent per month.
Results
- WhatsApp chatbots running in production at La Capitale, with the capture pipeline, retrieval over the brokerage's data, service-level targets, cost caps and incident runbooks.
- Replacing paid SaaS tools with this system saved the company about AED 25,000.
- La Capitale featured its AI rollout, including this work, in a public interview on a property show.
What I would do differently
- Start the golden set on day one. Model routing, takeover and every retrieval change were judged against it; having it from the first week would have made the early phases faster to evaluate.
- Agree the source of truth for listings before building retrieval. Grounded answers are only as fresh as the listings sync, so that decision deserves to come first.
- Keep capture and the assistant separate from the start. It let either one fail or change without touching the other, and I would design it that way again.
Stack
- WhatsApp Cloud API
- Python
- FastAPI
- PostgreSQL
- pgvector
- Redis
- Amazon SQS
- Amazon S3
- Amazon ECS
- Terraform
- GPT-5 Nano
- Gemini 2.5 Flash