Most "WhatsApp bots" are decision trees. Press 1 for menu, press 2 for timings. The moment a customer types something real, like "can I get 2 kg paneer at 6?", they break.
In this tutorial we'll build an AI agent instead: a small Node.js service that reads a free-text WhatsApp message, decides what to do, calls your own functions (check the menu, create an order, make a payment link), and replies. It works in English, Hindi or Hinglish without extra code.
We'll use Express, the official WhatsApp Cloud API, and an LLM with tool calling. The core is about 150 lines.
How it works
Every incoming message goes through the same five steps:

  1. The customer sends a WhatsApp message to your business number.
  2. Meta's Cloud API sends it to your webhook (POST /webhook).
  3. Your server passes the text, plus a list of tools, to the LLM.
  4. The LLM either replies directly or asks to call a tool (get_menu, create_order, payment_link). Your code runs the tool and sends the result back. This repeats until the model has a final answer.
  5. Your server sends that answer back through the Cloud API. The key idea: the model decides, your code acts. The LLM never touches your database directly. It can only call the functions you expose. Setup You'll need: • Node.js 18 or newer (for built-in fetch) • A Meta developer app with the WhatsApp product added. The dashboard gives you a test number, a Phone Number ID and a temporary access token. • An API key for an LLM that supports tool calling. We use Anthropic's Claude here, but the pattern is the same for any provider. • A public HTTPS URL for local testing, e.g. with ngrok or Cloudflare Tunnel. Install the packages: mkdir wa-agent && cd wa-agent npm init -y npm install express dotenv @anthropic-ai/sdk Create a .env file: WA_TOKEN=your_whatsapp_access_token WA_PHONE_ID=your_phone_number_id WA_VERIFY_TOKEN=any_secret_string_you_choose GRAPH_VERSION=v21.0 # use the latest version shown in your Meta dashboard ANTHROPIC_API_KEY=your_api_key MODEL=claude-sonnet-5-5 PORT=3000 Add "type": "module" to package.json so we can use import. Step 1: The webhook Meta calls your webhook twice: once with a GET to verify you own it, then with a POST for every new message. Create server.js: import 'dotenv/config'; import express from 'express'; import { runAgent } from './agent.js'; import { sendText } from './whatsapp.js';

const app = express();
app.use(express.json());

// 1. Verification: Meta sends hub.challenge, we echo it back
app.get('/webhook', (req, res) => {
const mode = req.query['hub.mode'];
const token = req.query['hub.verify_token'];
const challenge = req.query['hub.challenge'];
if (mode === 'subscribe' && token === process.env.WA_VERIFY_TOKEN) {
return res.status(200).send(challenge);
}
res.sendStatus(403);
});

// 2. Incoming messages
const seen = new Set(); // Meta can retry, so skip duplicates

app.post('/webhook', (req, res) => {
res.sendStatus(200); // reply fast, then do the work

const msg = req.body?.entry?.[0]?.changes?.[0]?.value?.messages?.[0];
if (!msg || msg.type !== 'text' || seen.has(msg.id)) return;
seen.add(msg.id);

handleMessage(msg.from, msg.text.body).catch(console.error);
});

async function handleMessage(from, text) {
const reply = await runAgent(from, text);
await sendText(from, reply);
}

app.listen(process.env.PORT, () =>
console.log(Listening on :${process.env.PORT})
);
In the Meta dashboard, set the callback URL to https:///webhook, paste the same verify token, and subscribe to the messages field.
Note that we return 200 before calling the LLM. If your webhook is slow, Meta will treat it as failed and send the message again.
Step 2: The agent loop
This is the brain. We describe three tools to the model, then loop: call the model, run any tools it asks for, send the results back, and stop when it gives a final answer.
Create agent.js:
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic(); // reads ANTHROPIC_API_KEY

// --- Your business data (swap for a real database) ---
const MENU = {
paneer: { price: 420, unit: 'kg' },
milk: { price: 64, unit: 'litre' },
curd: { price: 90, unit: 'kg' },
};
const orders = [];

// --- Tools the model is allowed to call ---
const tools = [
{
name: 'get_menu',
description: 'Get all products with price per unit in INR.',
input_schema: { type: 'object', properties: {} },
},
{
name: 'create_order',
description: 'Create an order once the customer has confirmed items and delivery time.',
input_schema: {
type: 'object',
properties: {
items: {
type: 'array',
items: {
type: 'object',
properties: {
product: { type: 'string' },
quantity: { type: 'number' },
},
required: ['product', 'quantity'],
},
},
delivery_time: { type: 'string', description: 'e.g. "6 pm today"' },
},
required: ['items', 'delivery_time'],
},
},
{
name: 'payment_link',
description: 'Create a UPI payment link for an existing order.',
input_schema: {
type: 'object',
properties: { order_id: { type: 'string' } },
required: ['order_id'],
},
},
];

function runTool(name, input, customer) {
if (name === 'get_menu') return MENU;

if (name === 'create_order') {
let total = 0;
for (const { product, quantity } of input.items) {
const item = MENU[product.toLowerCase()];
if (!item) return { error: Unknown product: ${product} };
total += item.price * quantity;
}
const order = { id: ORD${orders.length + 1001}, customer, ...input, total };
orders.push(order);
return order;
}

if (name === 'payment_link') {
const order = orders.find((o) => o.id === input.order_id);
if (!order) return { error: 'Order not found' };
// Replace with Razorpay / Cashfree / your gateway in production
const url = upi://pay?pa=yourshop@upi&pn=YourShop&am=${order.total}&cu=INR&tn=${order.id};
return { url, amount: order.total };
}

return { error: Unknown tool: ${name} };
}

const SYSTEM = You are the WhatsApp order assistant for a dairy shop.
Reply in the customer's language (English, Hindi or Hinglish).
Keep replies short and friendly, like a real shopkeeper.
Always check the menu before quoting prices. Never invent products or prices.
Confirm items and delivery time before creating an order.
;

const history = new Map(); // customer phone -> messages

// Keep the last ~30 messages, always starting at a plain user message
// so a tool call is never cut off from its result.
function trimHistory(messages, max = 30) {
let start = Math.max(0, messages.length - max);
while (start < messages.length &&
!(messages[start].role === 'user' && typeof messages[start].content === 'string')) {
start++;
}
return messages.slice(start);
}

export async function runAgent(customer, text) {
const messages = history.get(customer) ?? [];
messages.push({ role: 'user', content: text });

for (let step = 0; step < 5; step++) {
const res = await client.messages.create({
model: process.env.MODEL,
max_tokens: 1024,
system: SYSTEM,
tools,
messages,
});
messages.push({ role: 'assistant', content: res.content });

if (res.stop_reason !== 'tool_use') { history.set(customer, trimHistory(messages)); return res.content .filter((b) => b.type === 'text') .map((b) => b.text) .join('\n'); } // Run every tool the model asked for and send the results back const results = res.content .filter((b) => b.type === 'tool_use') .map((b) => ({ type: 'tool_result', tool_use_id: b.id, content: JSON.stringify(runTool(b.name, b.input, customer)), })); messages.push({ role: 'user', content: results }); 

}

return 'Sorry, something went wrong. A team member will reply shortly.';
}
Three things to notice:
• The model never sees your database. It only sees what runTool returns.
• Prices come from your code, not the model. create_order calculates the total itself, so the AI can't make up a number.
• The loop is capped at 5 steps, so a confused model can't run up your bill.
Memory lives in a Map, so it resets when the server restarts. In production, store each customer's history in a database such as Postgres, MongoDB or Redis.
Step 3: Send the reply
The Cloud API sends a message with one POST to your phone number's /messages endpoint. Create whatsapp.js:
export async function sendText(to, body) {
const url = https://graph.facebook.com/${process.env.GRAPH_VERSION}/${process.env.WA_PHONE_ID}/messages;

const res = await fetch(url, {
method: 'POST',
headers: {
Authorization: Bearer ${process.env.WA_TOKEN},
'Content-Type': 'application/json',
},
body: JSON.stringify({
messaging_product: 'whatsapp',
to,
type: 'text',
text: { body },
}),
});

if (!res.ok) console.error('WhatsApp send failed:', await res.text());
}
Run it:
node server.js
Now send "hi, can I get 2 kg paneer at 6 pm?" from your phone to the test number. The agent checks the menu, confirms the order, works out the ₹840 total in code and sends a UPI link, all in a normal chat.