How to Build a WhatsApp AI Agent with LangChain and Python
Step-by-step Python tutorial: build a WhatsApp AI agent with LangChain and the Chatmaid API, with memory per customer, signed webhooks and human handoff.

To build a WhatsApp AI agent with LangChain, you need three pieces: a WhatsApp number your code can send and receive on, a LangChain agent that decides what to say, and a small web server that connects the two. In this tutorial the number is linked to the Chatmaid Developers API with a QR code. Incoming messages reach a Flask app as signed message.received webhooks, LangChain's create_agent writes the reply, and one POST /v1/messages/send call delivers it. The finished project is four short Python files plus a test script, with memory per customer, tools that only see the caller's own data, and an automatic pause when a person replies from the phone.
The code targets LangChain 1.x (version 1.4 was current in October 2026). Many LangChain WhatsApp tutorials still use AgentExecutor and ConversationBufferMemory. Neither imports in LangChain 1.x: LangChain 1.0 replaced them with create_agent and moved the old APIs into the separate langchain-classic package. Every snippet below uses the 1.x API.
How the WhatsApp agent works
Here is what happens when a customer writes to your number:
- The customer sends a WhatsApp message to the number you linked to Chatmaid.
- Chatmaid posts a signed
message.receivedevent to your webhook URL. - Your Flask app checks the signature, answers
204right away and hands the message to a background worker. - The worker loads that customer's recent messages, runs the LangChain agent and sends the reply with
POST /v1/messages/send. - If someone on your team types into that chat from the phone, Chatmaid sends a
message.outgoingevent and the agent stays quiet in that chat for a while.
Nothing here depends on Meta's WhatsApp Business Platform. You link your existing number by scanning a QR code, much like WhatsApp Web, so there is no Meta Business verification and no template review. The guide to the WhatsApp API without Meta Business verification explains the trade-offs.
What you need before you start
- A Chatmaid Developers account. The sandbox is free, with no credit card. Test keys (
sk_test_) and test phone numbers simulate sends, so nothing reaches WhatsApp. - A live number and key for real conversations. Inbound messages only exist on live connections, so an agent that answers real customers needs a linked live number and an
sk_live_key. Both need the $7.99 a month flat plan. See the Developers page for details. - A WhatsApp number to link when you go live, and a second WhatsApp account to play the customer while you test.
- Python 3.10 or newer. All LangChain 1.x packages require it.
- A model provider key. The examples use Anthropic. Step 9 shows how to switch providers.
- A public HTTPS URL when you connect the real webhook, such as an ngrok tunnel. Chatmaid only accepts webhook URLs that start with
https://.
Step 1: Set up the project
The finished project looks like this:
whatsapp-agent/
├── .env
├── requirements.txt
├── chatmaid.py # sends WhatsApp messages
├── memory.py # history, retries and handoffs in SQLite
├── agent.py # the LangChain agent and its tools
├── app.py # the webhook server
└── send_test_event.py # simulates an incoming message for local testsPut the dependencies in requirements.txt:
langchain>=1.0
langchain-anthropic
flask
requests
python-dotenv
gunicornThen create a virtual environment and install them:
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txtIn the Chatmaid dashboard, with the sidebar on Test Mode, open Phone Numbers, click Add Number, enter any number in international format (for example +15551234567), register it and click Connect. Test numbers connect at once, with no QR code.
Then open API Keys and create a key with the Test option (test keys start with sk_test_). The default permissions, Read Messages and Send Messages, are all this project needs. Then create .env and never commit it:
CHATMAID_API_KEY=sk_test_xxxxxxxxxxxx
CHATMAID_FROM_PHONE=+15551234567
CHATMAID_WEBHOOK_SECRET=local-test-secret
ANTHROPIC_API_KEY=your_anthropic_api_key
AGENT_MODEL=anthropic:claude-opus-5-5
STAFF_PHONE=+15550001111
ALLOWED_PHONES=+15557654321CHATMAID_API_KEYis the key you just created. You switch it to a live key in Step 7.CHATMAID_FROM_PHONEis the sending number in international format with a leading+. For now, use the test number you just registered.CHATMAID_WEBHOOK_SECRETcan be any value for local tests. Step 7 replaces it with the real secret.AGENT_MODELis a LangChain model string inprovider:modelform.STAFF_PHONEis the WhatsApp number that gets an alert when the agent hands a chat to a person.ALLOWED_PHONESis a comma-separated list of customer numbers the agent may answer while you test. Leave it empty to answer everyone.
Step 2: Send a WhatsApp message from Python
Start with the outbound side. chatmaid.py wraps the send endpoint in one function:
import os
import requests
SEND_URL = "https://developers-api.chatmaid.net/v1/messages/send"
class ChatmaidError(Exception):
pass
def send_whatsapp(to: str, text: str, idempotency_key: str | None = None) -> str:
"""Send a WhatsApp text from your linked number and return the Chatmaid message ID."""
body = {
"fromPhoneId": os.environ["CHATMAID_FROM_PHONE"],
"to": to,
"content": text[:4096],
}
if idempotency_key:
body["idempotencyKey"] = idempotency_key[:64]
response = requests.post(
SEND_URL,
headers={"Authorization": f"Bearer {os.environ['CHATMAID_API_KEY']}"},
json=body,
timeout=30,
)
try:
payload = response.json()
except ValueError:
payload = {}
if not response.ok:
raise ChatmaidError(
f"HTTP {response.status_code} {payload.get('error')}: {payload.get('message')}"
)
return payload["data"]["id"]What the request contains:
Authorization: Bearer <key>. The key prefix picks the environment:sk_test_for the sandbox,sk_live_for real WhatsApp delivery. The host is the same for both.fromPhoneId. The sending number, written like+15551234567, or its ID from the dashboard.to. The recipient's number in the same international format. A WhatsApp group ID ending in@g.usalso works.content. The message text, up to 4,096 characters.idempotencyKey. Optional, up to 64 characters. If your account already has a message with the same key, the API returns that message instead of sending a second one. If that first send failed, the same key returns the same error, so a retry needs a new key. The webhook handler in Step 5 relies on this.
A successful send returns HTTP 201 with the message under data, including an ID that starts with msg_. Errors return a non-2xx status with an error field and a list of messages, for example HTTP 401 Unauthorized: ['Invalid API key'] for a wrong key, or a 400 when a live number is not connected. The messages reference lists every field.
Try it from the project folder. Replace the number with your second WhatsApp account:
python -c "from dotenv import load_dotenv; load_dotenv(); from chatmaid import send_whatsapp; print(send_whatsapp('+15557654321', 'Hello from my LangChain agent'))"You should see a msg_ ID. With a sandbox key the send is simulated; with a live key the message arrives on the other phone. If all you need is one-way alerts, the Python Flask notifications guide covers that case in more depth.
Step 3: Give each customer their own memory
A LangChain agent does not remember earlier runs by itself. Before you build the agent in Step 4, create memory.py. It stores every chat in SQLite, keyed by phone number, and also keeps track of retried webhooks and paused chats:
import os
import sqlite3
import threading
import time
_db = sqlite3.connect(os.environ.get("AGENT_DB", "agent.db"), check_same_thread=False)
_db_lock = threading.Lock()
_chat_locks: dict[str, threading.Lock] = {}
_db.executescript(
"""
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
phone TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS messages_by_phone ON messages (phone, id);
CREATE TABLE IF NOT EXISTS seen_events (event_id TEXT PRIMARY KEY);
CREATE TABLE IF NOT EXISTS paused_chats (
phone TEXT PRIMARY KEY,
paused_until REAL NOT NULL
);
"""
)
def chat_lock(phone: str) -> threading.Lock:
"""One lock per customer, so their messages are answered one at a time, in order."""
with _db_lock:
return _chat_locks.setdefault(phone, threading.Lock())
def load_history(phone: str, limit: int = 20) -> list[dict]:
"""Return the last `limit` messages for this number, oldest first."""
with _db_lock:
rows = _db.execute(
"SELECT role, content FROM messages WHERE phone = ? ORDER BY id DESC LIMIT ?",
(phone, limit),
).fetchall()
history = [{"role": role, "content": content} for role, content in reversed(rows)]
while history and history[0]["role"] != "user":
history.pop(0) # the conversation sent to the model should start with the customer
return history
def save_message(phone: str, role: str, content: str) -> None:
with _db_lock, _db:
_db.execute(
"INSERT INTO messages (phone, role, content) VALUES (?, ?, ?)",
(phone, role, content),
)
def first_time_seen(event_id: str) -> bool:
"""False if this webhook event was already handled (Chatmaid retries failed deliveries)."""
with _db_lock, _db:
cursor = _db.execute(
"INSERT OR IGNORE INTO seen_events (event_id) VALUES (?)", (event_id,)
)
return cursor.rowcount == 1
def pause_agent(phone: str, minutes: int) -> None:
with _db_lock, _db:
_db.execute(
"INSERT OR REPLACE INTO paused_chats (phone, paused_until) VALUES (?, ?)",
(phone, time.time() + minutes * 60),
)
def agent_paused(phone: str) -> bool:
with _db_lock:
row = _db.execute(
"SELECT paused_until FROM paused_chats WHERE phone = ?", (phone,)
).fetchone()
return row is not None and row[0] > time.time()What each part does:
load_historyreturns the last 20 messages for one number, oldest first. If the window cuts into the middle of a conversation, it drops leading replies so the history starts with a customer message.first_time_seenrecords each webhook event ID once. Chatmaid retries failed deliveries, so the same event can arrive more than once.pause_agentandagent_pausedhandle handoffs to a person (Step 8).chat_lockmakes sure two quick messages from the same customer are answered one after the other, so the second reply is written with the first exchange in its history.
The 20-message window keeps prompts short; raise or lower limit to trade context against cost. For summaries of older messages and a profile saved per customer, see how to add conversation memory to your WhatsApp AI agent. If you prefer LangChain's built-in persistence, create_agent also accepts a checkpointer, and the phone number can serve as the thread_id.
Step 4: Build the LangChain agent
agent.py defines the tools and the agent. It knows nothing about webhooks, so you can test it on its own.
import os
from dataclasses import dataclass
from datetime import datetime, timezone
from functools import cache
from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
import memory
from chatmaid import send_whatsapp
@dataclass
class Caller:
phone: str # the customer's WhatsApp number, set by your code, never by the model
# Replace this with a query against your own order system.
ORDERS = {
"+15557654321": [
{"number": "1042", "status": "shipped", "eta": "Thursday"},
{"number": "1057", "status": "being packed", "eta": "next week"},
],
}
@tool
def current_time() -> str:
"""Get the current date and time in UTC."""
return datetime.now(timezone.utc).strftime("%A %d %B %Y, %H:%M UTC")
@tool
def my_orders(runtime: ToolRuntime[Caller]) -> str:
"""List the orders that belong to the customer in this chat, with status and delivery estimate."""
orders = ORDERS.get(runtime.context.phone, [])
if not orders:
return "No orders found for this WhatsApp number."
return "\n".join(
f"Order #{o['number']}: {o['status']}, expected {o['eta']}" for o in orders
)
@tool
def request_human(reason: str, runtime: ToolRuntime[Caller]) -> str:
"""Hand the chat to a team member when you cannot help or the customer asks for a person."""
phone = runtime.context.phone
memory.pause_agent(phone, minutes=60)
send_whatsapp(os.environ["STAFF_PHONE"], f"Customer {phone} needs a person: {reason}")
return "A team member was notified and will reply in this chat."
SYSTEM_PROMPT = """You are the WhatsApp assistant for an online store.
- Reply in plain text, in one to four short sentences. No headings, tables or Markdown links.
- Reply in the language the customer writes in.
- For anything about orders, call my_orders. Never guess an order status.
- If you cannot help, or the customer asks for a person, call request_human.
- If a customer asks, say you are an automated assistant."""
@cache
def get_agent():
return create_agent(
model=os.environ.get("AGENT_MODEL", "anthropic:claude-opus-5-5"),
tools=[current_time, my_orders, request_human],
system_prompt=SYSTEM_PROMPT,
context_schema=Caller,
)
def run_agent(phone: str, history: list[dict], text: str) -> str:
result = get_agent().invoke(
{"messages": history + [{"role": "user", "content": text}]},
context=Caller(phone=phone),
config={"recursion_limit": 12}, # caps the model and tool steps in one reply
)
return result["messages"][-1].textHow the pieces fit together:
create_agenttakes a model, a list of tools and a system prompt. It calls the model, runs any tools the model asks for and calls the model again until it has an answer. The stringanthropic:claude-opus-5-5loads the model through thelangchain-anthropicpackage you installed.- Tools are plain functions with the
@tooldecorator. The docstring is what the model reads to decide when to call a tool, so write it for the model. CallerandToolRuntimekeep data private. Anyone who has your number can talk to this agent, so the customer's number comes from the webhook, never from the model. LangChain fills in theruntimeargument itself and leaves it out of the tool description the model sees, somy_orderstakes no arguments at all. A message like "show me the orders for +1 555 000 0000" still only returns the sender's own orders.request_humanpauses the agent for that chat and alerts your team on WhatsApp.recursion_limitcaps the steps in one run. With 12, the agent gets up to five rounds of tool calls; after that LangGraph stops the run with aGraphRecursionError, and the webhook handler sends a fallback reply. Without a cap, a confused run could keep calling tools at your expense..textreturns only the text of the final message. Some models also put reasoning blocks in the message content, and those should never reach a customer.- The prompt asks for plain text. WhatsApp uses its own formatting marks, not Markdown, and short replies read better in a chat.
Test the agent before connecting WhatsApp. This calls your model provider but sends nothing:
python -c "from dotenv import load_dotenv; load_dotenv(); from agent import run_agent; print(run_agent('+15557654321', [], 'Where is my order?'))"The agent should call my_orders and answer with the status of orders 1042 and 1057.
Adding tools for your own business
The example tools show the patterns most WhatsApp agents need:
- Start with read-only lookups: order status, opening hours, stock, appointment times. They are useful on day one and cannot do damage. To replace the
ORDERSdictionary with real Shopify or WooCommerce lookups, see the WhatsApp order tracking bot guide, which covers the store queries and the check that an order belongs to the sender. - Scope every lookup to
runtime.context. Do not give the model a tool that takes a phone number or customer ID as an argument. - Return short strings. The tool result goes back into the model's context, and the customer only needs the relevant lines.
- Keep actions behind a person or a confirmation. For refunds, cancellations or bookings, have the tool create a pending request and confirm it with the customer, or hand the chat over with
request_human.
Step 5: Receive WhatsApp messages with a webhook
app.py is the only part that talks to the outside world:
import hashlib
import hmac
import json
import os
from concurrent.futures import ThreadPoolExecutor
from dotenv import load_dotenv
from flask import Flask, abort, request
load_dotenv() # read .env before the modules below look up their settings
import memory
from agent import run_agent
from chatmaid import send_whatsapp
WEBHOOK_SECRET = os.environ["CHATMAID_WEBHOOK_SECRET"]
STAFF_PHONE = os.environ["STAFF_PHONE"]
ALLOWED = {p.strip() for p in os.environ.get("ALLOWED_PHONES", "").split(",") if p.strip()}
HANDOFF_MINUTES = 30
FALLBACK_REPLY = "Sorry, I could not answer that just now. Please try again in a few minutes."
app = Flask(__name__)
workers = ThreadPoolExecutor(max_workers=4)
def valid_signature(raw_body: bytes, header: str) -> bool:
"""Check X-Chatmaid-Signature: t=<unix time>,v1=<hex HMAC-SHA256 of "t.body">."""
try:
parts = dict(item.split("=", 1) for item in header.split(","))
signed = parts["t"].encode() + b"." + raw_body
except (KeyError, ValueError):
return False
expected = hmac.new(WEBHOOK_SECRET.encode(), signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(parts.get("v1", ""), expected)
@app.post("/webhooks/chatmaid")
def chatmaid_webhook():
raw_body = request.get_data()
if not valid_signature(raw_body, request.headers.get("X-Chatmaid-Signature", "")):
abort(401)
event = json.loads(raw_body)
data = event.get("data", {})
if event.get("event") == "message.received":
workers.submit(handle_incoming, data)
elif event.get("event") == "message.outgoing" and not data.get("isGroup"):
# Someone typed in this chat from the phone: let them take over.
memory.pause_agent(data["to"], HANDOFF_MINUTES)
if data.get("content"):
memory.save_message(data["to"], "assistant", data["content"])
return "", 204 # answer fast; the agent runs in the background
def handle_incoming(data: dict) -> None:
try:
reply_to_customer(data)
except Exception:
app.logger.exception("Could not handle inbound message %s", data.get("messageId"))
def reply_to_customer(data: dict) -> None:
if data.get("isGroup") or data.get("type") != "text" or not data.get("content"):
return # this agent answers one-to-one text messages only
if not memory.first_time_seen(data["messageId"]):
return # a retried delivery we already handled
phone, text = data["from"], data["content"]
if phone == STAFF_PHONE:
return # replies to handoff alerts are for people, not the agent
if ALLOWED and phone not in ALLOWED:
return # while testing, answer only the numbers in ALLOWED_PHONES
with memory.chat_lock(phone):
if memory.agent_paused(phone):
memory.save_message(phone, "user", text) # keep the context for later
return
history = memory.load_history(phone)
try:
reply = run_agent(phone, history, text) or FALLBACK_REPLY
except Exception:
app.logger.exception("Agent failed for %s", phone)
reply = FALLBACK_REPLY
memory.save_message(phone, "user", text)
# The inbound message ID doubles as the idempotency key, so one event never gets two replies.
message_id = send_whatsapp(phone, reply, idempotency_key=data["messageId"])
memory.save_message(phone, "assistant", reply)
print(f"Replied to {phone} ({message_id}): {reply}", flush=True)Three details matter in production.
Check the signature on the raw body. Every delivery carries an X-Chatmaid-Signature header in the form t=<unix time>,v1=<signature>. The signature is an HMAC-SHA256 of the timestamp, a dot and the raw request body, keyed with your webhook secret. Compute it over the exact bytes you received, before parsing the JSON. A retried delivery reuses the signature from its first attempt, so a tight freshness check on t would reject legitimate retries; the duplicate check handles replays instead.
Answer first, think later. Chatmaid waits up to 30 seconds for a response, and a slow or non-2xx response counts as a failed delivery that gets retried. A model call with a tool or two can take several seconds, so the handler returns 204 at once and the agent runs in a thread pool.
Make duplicates harmless. Two layers protect against double replies. first_time_seen drops an event the app has already handled, and the inbound message ID (it starts with inmsg_) is passed as the idempotencyKey of the reply. Even if the same event were processed twice, Chatmaid would send only one reply.
The handler skips group messages and anything that is not text. It also ignores your team's replies to handoff alerts, and while ALLOWED_PHONES is set it answers only those numbers. The agent answers every other one-to-one text sent to the linked number, so link a number you use only for customers, not your personal one. For media, the event's type says what arrived (image, audio, document and so on) and content carries the caption, if any. The webhook guide covers every event and field, and the webhooks reference has the full payloads.
Step 6: Test the whole loop in the sandbox
The sandbox never delivers inbound messages, but you can check everything except WhatsApp itself by posting a signed message.received event to your own app. send_test_event.py builds the event with the same fields and signature scheme Chatmaid uses:
"""Post a signed, simulated message.received event to the agent running on port 8000."""
import hashlib
import hmac
import json
import os
import secrets
import sys
import time
from datetime import datetime, timezone
import requests
from dotenv import load_dotenv
load_dotenv()
customer = sys.argv[1]
text = sys.argv[2]
now = datetime.now(timezone.utc).isoformat()
event = {
"event": "message.received",
"timestamp": now,
"data": {
"messageId": "inmsg_" + secrets.token_hex(12),
"from": customer,
"to": os.environ["CHATMAID_FROM_PHONE"],
"content": text,
"type": "text",
"isGroup": False,
"groupId": None,
"receivedAt": now,
},
}
body = json.dumps(event).encode()
timestamp = str(int(time.time()))
signature = hmac.new(
os.environ["CHATMAID_WEBHOOK_SECRET"].encode(),
timestamp.encode() + b"." + body,
hashlib.sha256,
).hexdigest()
response = requests.post(
"http://localhost:8000/webhooks/chatmaid",
data=body,
headers={
"Content-Type": "application/json",
"X-Chatmaid-Event": "message.received",
"X-Chatmaid-Signature": f"t={timestamp},v1={signature}",
},
timeout=10,
)
print(response.status_code)Start the app in one terminal:
flask --app app run --port 8000Send a test message from a second terminal:
python send_test_event.py +15557654321 "Where is my order?"The script prints 204. A few seconds later the app terminal shows a line starting with Replied to +15557654321, followed by the agent's answer about orders 1042 and 1057. The model call is real; the reply is a simulated sandbox send. Run the script again with a follow-up such as "When will the second one arrive?" and the agent answers from the conversation history. Try "Can I talk to a person?" to see request_human pause the chat and send a (simulated) alert to STAFF_PHONE. That chat then stays paused for an hour, so later test messages from the same number are stored without a reply. To keep testing, delete agent.db or send from another number in ALLOWED_PHONES.
Step 7: Go live with your WhatsApp number
Once the loop works, connect real WhatsApp traffic:
- Start the $7.99 a month subscription. Then switch the sidebar toggle from Test Mode to Live, and on API Keys create a key with the Live option (it starts with
sk_live_) and the same two permissions. - On Phone Numbers, click Add Number, register the number the agent will use, click Connect and scan the QR code with WhatsApp on that phone. If the dashboard says WhatsApp is requiring a passkey to link this number, turn off passkey linking for that WhatsApp account and connect again.
- Start a tunnel to port 8000, for example with
ngrok http 8000, and copy the HTTPS address it prints. On a free ngrok plan the address changes each time you restart it; update the Webhook URL when it does. - On Webhooks, set the Webhook URL to that address followed by
/webhooks/chatmaid. Under Events to receive, select Message Received and Message Sent From Phone, then click Configure Webhook. - Copy the secret that appears. The dashboard shows it only once.
- In
.env, setCHATMAID_API_KEYto the live key,CHATMAID_FROM_PHONEto your linked number andCHATMAID_WEBHOOK_SECRETto the secret. Restart the app. - Click Test Webhook. Chatmaid sends a signed test event, and the dashboard reports whether your app answered successfully. A
401from your app means the secret in.envdoes not match. - Add your second WhatsApp number to
ORDERSinagent.pyand toALLOWED_PHONESin.env, restart the app and send "Where is my order?" from that account to your linked number. When you're ready to answer real customers, emptyALLOWED_PHONES.
The reply should arrive within a few seconds. On the linked phone it appears in that chat as a message you sent, because it was sent from your number.
Step 8: Let a person take over the chat
Customers sometimes need a person, and your team will sometimes jump into a chat on their own. The message.outgoing event covers the second case. It fires when someone types a message into the linked phone's WhatsApp app instead of sending it through the API. Chatmaid reports messages your code sends through the API as message.sent, so the agent's own replies don't normally pause it.
When the event arrives for a one-to-one chat, the handler:
- pauses the agent in that chat for 30 minutes, and each new message from your team restarts the timer;
- saves your team member's message in the history, so the agent knows what was said when it resumes.
While a chat is paused, customer messages are stored but not answered. The request_human tool uses the same pause from the other direction: the agent decides it cannot help, pauses itself for an hour and alerts STAFF_PHONE. Change HANDOFF_MINUTES in app.py and minutes=60 in agent.py to fit your team's response times. Use a different number for STAFF_PHONE than the one the agent sends from. Replies your team sends to the alert are ignored by the agent.
Step 9: Switch to another model provider
The model is one environment variable. To use OpenAI instead of Anthropic, install the integration, add langchain-openai to requirements.txt so your deployed image includes it, and change two lines in .env:
pip install langchain-openaiOPENAI_API_KEY=your_openai_api_key
AGENT_MODEL=openai:your-model-nameReplace your-model-name with a model ID from OpenAI's model list that supports tool calling. Tools, memory and the webhook code stay the same, because LangChain passes tools and messages to each provider in the format it expects. This works for any LangChain chat model that supports tool calling. A smaller model costs less per reply; test it on real customer questions before you switch, especially the ones that need a tool.
Step 10: Deploy the agent
Any host that runs a Docker container and gives you an HTTPS URL will do. A minimal Dockerfile:
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN mkdir -p /data
ENV AGENT_DB=/data/agent.db
CMD ["gunicorn", "--workers", "1", "--threads", "8", "--bind", "0.0.0.0:8000", "app:app"]Add a .dockerignore so your keys and local data stay out of the image:
.env
.venv
agent.dbA few notes:
- Set the variables on your host. Enter the values from
.envas environment variables in your hosting dashboard instead of copying the file into the image. - One worker process, several threads. The per-chat locks and the thread pool live inside one process. Several gunicorn workers would answer the same customer in parallel.
- Keep the database on a volume. Mount a persistent volume at
/data, or each deploy starts every customer with an empty history. - Update the webhook URL on the dashboard's Webhooks page to your production address. The secret stays the same.
- Mind your logs. The
printinreply_to_customerwrites reply text to your logs. Remove it if you do not want message content there. - Restarts drop replies in progress. A deploy that stops the process loses any reply the agent is still writing. When one process is no longer enough, move the history to Postgres and the agent runs to a job queue, so the webhook handler only verifies, deduplicates and enqueues.
Keep your WhatsApp number in good standing
The agent sends from your own WhatsApp number, so ordinary WhatsApp rules apply. Restrictions are very unlikely with normal use. They happen when an account behaves like spam, such as sending unsolicited bulk messages to people who do not have you saved.
An agent that only answers people who wrote to you first fits normal use. If you later have it start conversations, such as reminders or follow-ups, only message people who expect to hear from you. For other ways to connect agents, including Claude Code through MCP, see how to connect an AI agent to WhatsApp.
Frequently asked questions
Do I need the WhatsApp Business API or Meta verification?
No. You link your existing number by scanning a QR code in the Chatmaid dashboard, and your code sends through the Chatmaid Developers API. There is no Meta Business verification and no template review.
Can I build and test this for free?
Mostly. The sandbox is free with no credit card: you can build the send side, run the agent in the terminal and test the whole webhook loop with send_test_event.py. Your model provider bills per token from the first call. Receiving real customer messages needs a linked live number and a live key, which come with the $7.99 a month plan.
Does this work with OpenAI or other models?
Yes. Set AGENT_MODEL to the LangChain model string of any chat model that supports tool calling, and install that provider's package, as shown in Step 9. The rest of the code does not change.
Can the agent reply in WhatsApp groups?
The API supports it. Inbound group messages carry a groupId, and passing it as to sends to the group, as long as your number is a member and allowed to post there. This tutorial skips groups on purpose, because a bot that answers every group message quickly becomes noise. If you add group support, reply only when the agent is addressed directly.
Can the agent read photos or voice notes?
The webhook tells you the message type and gives you the caption, which the agent can use. The API does not pass along the media file itself, so this tutorial answers text messages only.
Can I build a WhatsApp AI agent without writing Python?
Yes. The n8n customer service agent guide builds a similar agent as an n8n workflow on the same API, and the Chatmaid MCP server lets Claude Code and other MCP clients send WhatsApp messages without any HTTP code.


