Customer support teams are constantly flooded with repetitive queries: "Where is my order?", "What's your return policy?", or "Do you ship internationally?". While these questions have existing answers in company knowledge bases, customers often prefer messaging apps like WhatsApp over digging through an FAQ page.
In this tutorial, I'll walk through how I build a production-ready WhatsApp support bot using Retrieval-Augmented Generation (RAG). This setup connects the WhatsApp Business API to an LLM, backed by a vector search over your company's support documentation so the bot only answers based on verified facts.
Architecture Overview
Here is how data flows from a customer's incoming WhatsApp message to an accurate, retrieved response:
[Customer WhatsApp]
│
▼ (Webhook POST)
[FastAPI Backend] ──► [Embeddings API] ──► [Vector DB (Chroma/FAISS)]
│ │
└─────────────────► [LLM (OpenAI/Anthropic)] ◄┘
│
▼
[WhatsApp Business API] ◄── [Formatted Response]
- Webhook Reception: WhatsApp sends an incoming message via HTTP POST to our FastAPI endpoint.
- Retrieval (RAG): We generate an embedding of the customer's query and query our vector store for the top 3 most relevant FAQ chunks.
- Generation: We pass the user query and the retrieved context into an LLM with a strict system prompt preventing hallucinations.
- Reply: The generated response is sent back to the customer via the WhatsApp Graph API.
Step 1: Setting up the FastAPI Webhook Receiver
First, let's create a minimal FastAPI server to receive incoming messages from the WhatsApp Cloud API.
from fastapi import FastAPI, Request, HTTPException
import os
import requests
app = FastAPI()
VERIFY_TOKEN = os.getenv("WHATSAPP_VERIFY_TOKEN", "my_secure_token")
WHATSAPP_TOKEN = os.getenv("WHATSAPP_ACCESS_TOKEN", "your_meta_token")
PHONE_NUMBER_ID = os.getenv("WHATSAPP_PHONE_ID", "your_phone_id")
@app.get("/webhook")
async def verify_webhook(request: Request):
mode = request.query_params.get("hub.mode")
token = request.query_params.get("hub.verify_token")
challenge = request.query_params.get("hub.challenge")
if mode == "subscribe" and token == VERIFY_TOKEN:
return int(challenge)
raise HTTPException(status_code=403, detail="Verification failed")
@app.post("/webhook")
async def receive_message(request: Request):
body = await request.json()
try:
entry = body["entry"][0]
changes = entry["changes"][0]
value = changes["value"]
message = value["messages"][0]
sender_phone = message["from"]
message_body = message["text"]["body"]
# Process query through our RAG pipeline
response_text = generate_rag_response(message_body)
# Send reply back to WhatsApp
send_whatsapp_message(sender_phone, response_text)
except (KeyError, IndexError):
# Not a text message or format mismatch
pass
return {"status": "success"}
def send_whatsapp_message(to: str, text: str):
url = f"https://graph.facebook.com/v17.0/{PHONE_NUMBER_ID}/messages"
headers = {
"Authorization": f"Bearer {WHATSAPP_TOKEN}",
"Content-Type": "application/json"
}
payload = {
"messaging_product": "whatsapp",
"to": to,
"type": "text",
"text": {"body": text}
}
requests.post(url, json=payload, headers=headers)
Step 2: Ingesting FAQs into a Vector Store
Before our bot can answer questions, we need to chunk our FAQ markdown or text files and store them in a local or hosted vector database. Here is how I set up chunking and indexing using Python and ChromaDB.
import chromadb
from sentence_transformers import SentenceTransformer
# Initialize Chroma and embedding model
client = chromadb.PersistentClient(path="./chroma_db")
collection = client.get_or_create_collection(name="support_faqs")
embed_model = SentenceTransformer("all-MiniLM-L6-v2")
def ingest_faqs(faqs: list[dict]):
"""
faqs format: [{"id": "faq_1", "text": "Our shipping takes 3-5 days...", "category": "shipping"}]
"""
ids = [item["id"] for item in faqs]
texts = [item["text"] for item in faqs]
embeddings = embed_model.encode(texts).tolist()
metadatas = [{"category": item["category"]} for item in faqs]
collection.upsert(
ids=ids,
documents=texts,
embeddings=embeddings,
metadatas=metadatas
)
# Example sample data
sample_faqs = [
{"id": "1", "text": "Standard shipping takes 3 to 5 business days across the country.", "category": "shipping"},
{"id": "2", "text": "You can return any item within 30 days of purchase for a full refund.", "category": "returns"}
]
ingest_faqs(sample_faqs)
Step 3: Implementing the RAG Pipeline
When a user asks a question, we retrieve the top matching document chunks and feed them into OpenAI or Anthropic with strict instructions: do not invent information.
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
def generate_rag_response(query: str) -> str:
# 1. Retrieve top 2 relevant FAQ chunks
query_embedding = embed_model.encode([query]).tolist()
results = collection.query(
query_embeddings=query_embedding,
n_results=2
)
retrieved_docs = results["documents"][0]
context = "\n\n".join(retrieved_docs)
# 2. Construct strict prompt
system_prompt = (
"You are a helpful customer support assistant for Example Retail. "
"Answer the user's question using ONLY the provided context below. "
"If the answer cannot be found in the context, politely inform the user "
"that you are connecting them to a human support agent. Do not make up facts."
)
user_prompt = f"Context:\n{context}\n\nCustomer Question: {query}"
# 3. Call LLM
response = openai.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
temperature=0.1
)
return response.choices[0].message.content
Common Pitfalls & Best Practices
- Chunking Size: Keep FAQ chunks granular (100–300 words). If chunks are too large, the embeddings become noisy and the LLM misses precise details.
-
Temperature Control: Set temperature to
0.0or0.1. Support bots need consistency and strict adherence to facts, not creative writing. - Human Handoff Trigger: Always include a fallback rule. If the similarity score of retrieved documents falls below a threshold, immediately escalate to human staff in your CRM or support desk.
- Rate Limiting: Meta enforces messaging tier limits on the WhatsApp Cloud API. Implement background workers (like Celery or Redis Queue) for high-volume deployments.
Implementation Checklist
- [ ] WhatsApp Cloud API webhook verified and connected to HTTPS endpoint.
- [ ] FAQ documentation chunked and indexed into Chroma/FAISS vector store.
- [ ] LLM system prompt configured with strict anti-hallucination guardrails.
- [ ] Fallback mechanism tested for queries outside the knowledge base.
- [ ] Logging enabled for incoming messages and generated responses.
I'm Nandan Singh — I build AI and automation systems (Odoo, Zoho, chatbots, voice agents) at NMT Solutions. Questions? Drop a comment or WhatsApp +91 92260 02903.
Top comments (0)