Updated on October 29, 2026
A WhatsApp chatbot with a knowledge base uses RAG (retrieval-augmented generation): for every question that comes in through the webhook, the system searches your company’s documents for the most similar passages, hands those passages to the language model and asks for an answer based only on them, with the source. If the search finds nothing relevant, the bot says it doesn’t know and offers a human agent instead of making something up. On the official WhatsApp Business API, these replies are service messages, sent inside the 24-hour window the customer opened.
This guide covers the architecture, how to prepare your documents, how to make the bot cite its source and decline out-of-scope questions, what each reply costs, and a short Python example.
Why RAG and not just a big prompt
A “plain” AI bot answers with whatever the model learned in training. It doesn’t know your return window, your shipping rates or the refund rule that changed last month. You have three options:
| Approach | How it works | Limitation |
|---|---|---|
| Paste everything into the prompt | The whole manual goes into every call | Gets expensive and slow as the knowledge base grows; the model loses track in long text |
| Fine-tuning | Trains the model on your texts | Updating means retraining; it doesn’t tell you where an answer came from |
| RAG | Retrieves only the relevant passages and sends them with the question | Only as good as the search and the documents |
With RAG, updating the bot means updating the document and reindexing. And because you know which passages were used, you can show the source to the customer and audit the answer later.
Architecture: from webhook to reply
Customer sends a question on WhatsApp
│
▼
Webhook (returns 200 immediately and enqueues)
│
▼
Worker
1. Dedupes by wamid and checks state (bot or human)
2. Generates the question's embedding
3. Searches the vector store for the closest passages
4. No passage above the threshold? ──▶ decline and offer a human
5. Builds the prompt: rules + passages + short history + question
6. LLM answers, citing the source
│
▼
POST /messages (text) ──▶ customer
Two separate processes:
- Indexing (offline). Reads the documents, splits them into passages, generates embeddings and writes them to the vector store. Runs whenever a document changes.
- Query (on every message). Runs steps 1 to 6 above.
The webhook never waits on the LLM: it stores the event and returns 200. Why the queue is mandatory and how to dedupe is covered in AI chatbot on the WhatsApp API; validating the webhook signature is covered in webhook signature validation.
Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →
Preparing the knowledge base
The bot is only as good as its documents. Before you think about models, review the content:
- One source per topic. If your return policy appears in three PDFs with different rules, the bot will repeat the contradiction.
- Text, not images. Tables saved as images and scanned PDFs need OCR first; otherwise their content never makes it into search.
- A date and an owner. Every document should have a last-updated date and someone responsible for reviewing it.
- Real questions. Use the questions your support team already gets to check whether the knowledge base covers what customers actually ask.
Chunking: how to split documents
Documents are split into passages (chunks) because the search compares the question against each passage. Chunks that are too large mix topics; chunks that are too small lose context.
| Decision | Starting point | Why |
|---|---|---|
| Split unit | The document’s own sections and paragraphs | Respects the structure the author created |
| Size | A few hundred words per chunk | Fits one complete topic without mixing several |
| Overlap | Repeat one or two sentences between neighboring chunks | Avoids cutting a rule in half |
| Metadata | Document title, section, URL, date | This is what lets you cite the source |
Test with real questions and adjust. There’s no universal right size, only the one that works for your knowledge base.
Embeddings and the vector store
An embedding is a vector of numbers that represents the meaning of a piece of text. Texts with similar meaning produce vectors that are close together, even when the wording differs (“exchange the product” and “return”). The search computes the similarity between the question’s vector and each passage’s vector.
- Embedding model. Use the same model for indexing and querying. Pick one that handles your customers’ language well (for Brazilian customers, Portuguese).
- Vector store. For a few hundred chunks, an in-memory array does the job. For larger knowledge bases, use a database with a vector index (for example, a PostgreSQL vector extension or a dedicated vector database).
- Reindexing. When a document changes, delete its old chunks and index it again. Store the document ID on every chunk.
Citing the source and declining out-of-scope questions
Two behaviors separate a trustworthy bot from one that makes things up:
Similarity threshold
If the closest passage has low similarity, the knowledge base doesn’t have the answer. In that case the bot doesn’t even call the LLM: it says it doesn’t know and offers a human agent. The threshold value depends on the embedding model; calibrate it with a set of questions the knowledge base can answer and others it can’t.
A prompt with explicit rules
You are the customer service assistant for Example Store on WhatsApp.
Answer ONLY based on the passages below. If the answer isn't in them, reply
exactly: NO_ANSWER
Reply in English, in at most 4 lines.
At the end, give the source in this format: Source: <title> (<url>)
Don't make up deadlines, prices or policies. Don't discuss topics unrelated to Example Store.
Passages:
[1] Return policy (https://example.com/returns): ...
[2] Shipping and delivery times (https://example.com/shipping): ...
Citing the source with a link does two things: the customer can check the full rule, and your team can trace where a wrong answer came from.
Handoff
Declining shouldn’t be a dead end. When the bot doesn’t know, when the topic is sensitive or when the customer asks for a person, the conversation goes to a human agent. The WhatsApp Business Messaging Policy requires prompt, clear and direct escalation paths when you use automation. The step-by-step is in handing off from bot to human on WhatsApp.
Python code
The example shows indexing and querying. The embed and generate functions are where your embedding and LLM providers’ SDKs plug in. The code requires Python 3.10 or later, numpy and requests. For the full FastAPI webhook server, see WhatsApp bot with Python.
import os
import numpy as np
import requests
API = "https://apis.vectalk.com.br/api/messages"
TOKEN = os.environ["VECTALK_TOKEN"]
THRESHOLD = 0.75 # calibrate with real questions; depends on the embedding model
TOP_K = 3
def embed(texts: list[str]) -> np.ndarray:
"""Call your provider's embedding model here. Return normalized vectors."""
raise NotImplementedError
def generate(prompt: str) -> str:
"""Call your provider's LLM here, with a response timeout."""
raise NotImplementedError
# 1. Indexing (offline)
def split_text(text: str, max_words: int = 250, overlap: int = 30) -> list[str]:
words = text.split()
step = max_words - overlap
return [" ".join(words[i:i + max_words]) for i in range(0, len(words), step)]
def index(documents: list[dict]) -> tuple[list[dict], np.ndarray]:
chunks = []
for doc in documents: # {"title": ..., "url": ..., "text": ...}
for part in split_text(doc["text"]):
chunks.append({"title": doc["title"], "url": doc["url"], "text": part})
vectors = embed([c["text"] for c in chunks])
return chunks, vectors
# 2. Query (on every message)
def answer(question: str, chunks: list[dict], vectors: np.ndarray) -> str | None:
q = embed([question])[0]
scores = vectors @ q # cosine similarity (normalized vectors)
best = np.argsort(scores)[::-1][:TOP_K]
if scores[best[0]] < THRESHOLD:
return None # not in the knowledge base: handoff
context = "\n".join(
f"[{n}] {chunks[i]['title']} ({chunks[i]['url']}): {chunks[i]['text']}"
for n, i in enumerate(best, 1)
)
prompt = f"{RULES}\n\nPassages:\n{context}\n\nCustomer question: {question}"
reply = generate(prompt).strip()
return None if reply == "NO_ANSWER" else reply
def send_text_message(wa_id: str, text: str) -> None:
r = requests.post(
API,
headers={"Authorization": f"Bearer {TOKEN}"},
json={"messaging_product": "whatsapp", "to": wa_id, "type": "text", "text": {"body": text}},
timeout=30,
)
r.raise_for_status()
def handle_message(msg: dict, chunks, vectors) -> None:
reply = answer(msg["text"]["body"], chunks, vectors)
if reply is None:
send_text_message(msg["from"], "I couldn't find that information. I'll bring in someone from our team to help.")
hand_off_to_human(msg["from"]) # your handoff function
return
send_text_message(msg["from"], reply)
RULES = "..." # the prompt from the previous section
What’s still missing for production: handling only events whose type is text (audio, images and button replies arrive without text.body), a persistent queue, deduplication by wamid, a bot/human state check, a short conversation history in the prompt, a 24-hour window check before sending, and logging of the question, the passages used, the answer and the model.
What each reply costs
There are two costs: the WhatsApp message and the AI.
- Message. A free-form text reply inside the window is a service message. Since October 1, 2026, each phone number gets 1,000 free service messages per month, and Meta charges from the 1,001st on. For recipients in Brazil, the rate is BRL 0.0350 (R$ 0.0350) per delivered message. Meta only charges for delivered messages and doesn’t charge for the messages the customer sends.
- AI. Embedding the question and calling the LLM, billed by your provider based on context size. Sending 3 passages instead of 10 cuts that cost.
A reply sent as a single message costs less than the same reply split into three. Ask the model for short answers and send them in one go. If the conversation started from a Click-to-WhatsApp ad, replies inside the free entry point window, which can stay open for up to 7 days, aren’t charged by Meta. Pricing details are in WhatsApp API pricing in Brazil.
How to measure quality without making up numbers
There’s no “standard” RAG accuracy rate: it depends on your knowledge base, your questions and your model. Measure your own:
- Test set. Collect real support questions, with the correct answer and the source document.
- Retrieval. For each question, does the right passage show up among the top results?
- Answer. Is the answer correct, does it cite the right source, and does it avoid adding anything that isn’t in the passage?
- Refusal. Do questions outside the knowledge base get a refusal and a handoff?
- Production. Track the “no answer” handoff rate: it shows what’s missing from the knowledge base.
Rerun the test set whenever you change the model, the chunk size or the threshold.
Meta rules that affect the bot
- 24-hour window. The bot can reply with free-form text only up to 24 hours after the customer’s last message. To re-engage, you need a template. See the WhatsApp 24-hour customer service window.
- Business scope. Meta’s terms restrict offering general-purpose AI assistants as the primary product on the platform. A bot that answers questions about your own company, based on its documents, uses AI to support customer service. See Meta’s AI policy in 2026.
- Training data. The terms prohibit using platform data to build or improve AI models. The exception is fine-tuning a model for the business’s exclusive use, without that benefiting other models. Review your LLM provider’s terms on retention and use of conversations.
How to do it with Vectalk
Vectalk gives you the official API: webhooks arrive in Meta’s format and sending is POST https://apis.vectalk.com.br/api/messages, with the same payload. The dashboard has no built-in AI or knowledge base; indexing, search and the LLM run on your server or in the AI tool you connect to the API. If your human team uses the WhatsApp Business app on their phones, coexistence keeps the number working in both places.
Register your worker’s URL as a webhook (documentation), create your account at apps.vectalk.com.br/register and read the guide to the official WhatsApp Business API.
Frequently asked questions
Which embedding model and which LLM should I use?
The WhatsApp API doesn’t restrict the model. Choose based on performance in your customers’ language on your test questions, cost and the provider’s data policy. Use the same embedding model for indexing and querying.
Can the bot read PDFs the customer sends?
Yes, but that’s a different flow: the webhook delivers the media ID, which you download and process. See how to download received media. Don’t mix customer documents into the company’s knowledge base.
How do I update the knowledge base when a policy changes?
Edit the source document, delete its old chunks from the vector store and index it again. With the document ID stored on each chunk, that’s a simple operation.
Does RAG eliminate wrong answers?
No. It reduces them, because the model answers from your own texts, but the search can return the wrong passage and the model can misread it. That’s why you need the threshold, source citations, handoff and a test set.
Can I use the same bot with ChatGPT?
Yes: RAG is provider-independent. The article ChatGPT on the WhatsApp Business API shows the connection; the document search runs before the model call.
Official sources consulted on October 29, 2026: Pricing and service messages (Meta), Non-template messages (Meta), Customer service window (Meta), WhatsApp Business Messaging Policy, Meta Terms for WhatsApp Business Platform, Quickstart (Vectalk), Webhooks (Vectalk).
Put your business on the official WhatsApp
Create your account, connect your number to the official API (you can keep the app with coexistence) and start serving customers and sending messages.
