Launching Third‑Party AI Agents on WhatsApp Business API (2024)
Introduction
WhatsApp is no longer just a chat app—it's becoming the fastest growing platform for AI‑driven commerce. Since the official release of third‑party AI agents on the WhatsApp Business API (early 2024), interest has surged — searches for “WhatsApp chatbot tutorial” and “WhatsApp LLM integration” are up more than 350 % worldwide.
If you want to plug a large‑language‑model (LLM) directly into the world’s most popular messenger, this guide shows you exactly how, from registration to production‑grade monitoring, with ready‑to‑copy snippets in Node.js, Python, and Google Cloud Functions.
Table of Contents
- Prerequisites & Account Setup
- API Architecture Overview
- Registering Your AI Agent Endpoint
- Webhook Wiring to an LLM (OpenAI, Anthropic, Falcon)
- Prompt Engineering for Common Use‑Cases
- Security, Compliance & Data Retention
- Cost‑Comparison Table
- Launch Checklist
- Metrics & Alerting Script (Python)
- Real‑World Success Stories
- FAQ
1. Prerequisites & Account Setup
| Requirement | How to Obtain |
|---|---|
| Verified WhatsApp Business Account (WABA) | Apply via Meta Business Manager → Business Settings → WhatsApp Accounts. Must pass phone‑number verification and display name review. |
| Facebook Developer App with WhatsApp Business API product added | Create a new app at developers.facebook.com, enable the WhatsApp product, and generate a System User token with whatsapp_business_management and whatsapp_business_messaging scopes. |
| Cloud hosting (Node.js, Python, or Cloud Functions) with a public HTTPS endpoint (TLS 1.3) | Example: Google Cloud Run, AWS Lambda (via API Gateway), or Azure Functions. |
| LLM access (OpenAI, Anthropic, or self‑hosted Falcon) | Obtain an API key from the provider; the WhatsApp endpoint only requires an HTTP‑compatible JSON schema. |
| Optional: Docker for local testing | docker run -p 8080:8080 your‑image |
2. API Architecture Overview
User ⇄ WhatsApp Server (E2E encrypted) ⇄ Business API (decrypts) ⇄ Your Webhook (TLS 1.3) ⇄ LLM Provider (JSON over HTTPS) ⇄ Your Webhook (response) ⇄ Business API ⇄ User
- The AI‑agent layer is just another webhook endpoint (
/v1/ai-agent) that receives the decrypted message payload, forwards it to the LLM, and returns the generated reply. - All traffic between WhatsApp and your server must use TLS 1.3; between your server and the LLM you can use the provider’s default TLS.
3. Registering Your AI Agent Endpoint
-
Create the endpoint – e.g.,
https://mybot.example.com/v1/ai-agent. - Add the endpoint in the Business Manager:
Navigate → Business Settings → WhatsApp Accounts → **AI Agents* → Add New Agent*
Enter the URL, select the associated phone number, and enable “Message Templates” if you need proactive messages.
-
Save the verification token (Meta will send a GET request with
hub.challenge). Respond with the exact challenge string to complete verification.
curl -X GET "https://mybot.example.com/v1/ai-agent?hub.mode=subscribe&hub.challenge=12345&hub.verify_token=MY_TOKEN"
# Respond with body: 12345
- Generate a permanent access token for your System User and store it securely (e.g., AWS Secrets Manager).
4. Webhook Wiring to an LLM
Below are minimal, production‑ready snippets (no fenced blocks) that you can drop into a Node.js Express app or a Python Flask route.
Node.js (Express)
const express = require('express')
const fetch = require('node-fetch')
const app = express()
app.use(express.json())
app.post('/v1/ai-agent', async (req, res) => {
const { messages } = req.body
const userMsg = messages[0].text.body
// Forward to OpenAI GPT‑4o
const llmResp = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-4o',
messages: [{ role: 'user', content: userMsg }],
temperature: 0.7
})
})
const { choices } = await llmResp.json()
const reply = choices[0].message.content
// Send reply back to WhatsApp
await fetch(`https://graph.facebook.com/v17.0/${process.env.WABA_PHONE_ID}/messages`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.WABA_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
messaging_product: 'whatsapp',
to: messages[0].from,
text: { body: reply }
})
})
res.sendStatus(200)
})
app.listen(8080, () => console.log('AI Agent listening on :8080'))
Python (Flask)
from flask import Flask, request, jsonify
import requests, os
app = Flask(__name__)
@app.route('/v1/ai-agent', methods=['POST'])
def ai_agent():
data = request.get_json()
user_msg = data['messages'][0]['text']['body']
# Call Anthropic Claude‑3.5
llm_resp = requests.post(
'https://api.anthropic.com/v1/messages',
headers={'x-api-key': os.getenv('ANTHROPIC_API_KEY'), 'Content-Type': 'application/json'},
json={'model': 'claude-3.5-sonnet', 'max_tokens': 1024,
'messages': [{'role': 'user', 'content': user_msg}]}
)
reply = llm_resp.json()['content'][0]['text']
# Send back to WhatsApp
requests.post(
f"https://graph.facebook.com/v17.0/{os.getenv('WABA_PHONE_ID')}/messages",
headers={'Authorization': f"Bearer {os.getenv('WABA_TOKEN')}",
'Content-Type': 'application/json'},
json={'messaging_product': 'whatsapp',
'to': data['messages'][0]['from'],
'text': {'body': reply}}
)
return ('', 200)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)
Swap the LLM endpoint and payload format to use Falcon‑180B or any OpenAI‑compatible service.
5. Prompt Engineering for Common Use‑Cases
| Use‑Case | Prompt Template | Tips |
|---|---|---|
| Customer Support | “You are a helpful support agent for {brand}. Answer the user’s question concisely, include a link to the relevant FAQ, and ask if anything else is needed.” | Keep temperature ≤ 0.3 for factual replies. |
| Restaurant Reservations | “Act as a reservation bot for {restaurant}. Collect date, time, party size, and confirm availability. End with a confirmation number.” | Use slot‑filling logic; store the extracted slots in a temporary DB (TTL = 15 min). |
| Order Tracking | “You are an order‑status assistant. The user provides an order ID. Retrieve the status from the internal API (POST /status) and reply with a friendly sentence.” | Cache recent order IDs for 5 min to avoid repeated API calls. |
6. Security, Compliance & Data Retention
- Transport security – Enforce TLS 1.3 on all inbound/outbound endpoints.
- At‑rest encryption – If you store any message content (e.g., for analytics), encrypt with AES‑256 and rotate keys every 90 days.
- Retention policy – Delete raw user messages after 30 days; keep only anonymized analytics (e.g., intent counts).
- **GDPR &
Herramienta mencionada: Groq Cloud
Top comments (0)