Tutorial

Build an AI WhatsApp Assistant with an LLM and Webhooks (Node.js)

Any statistics or percentages in this article are general industry figures or illustrations, not QuackAPI measurements or promises. Results depend on your audience, consent and sending patterns. QuackAPI connects to WhatsApp as a linked device (an unofficial method), so read our risk and acceptable use policy before sending.

November 23, 202611 min read

AI on WhatsApp is the 2026 trend, but build the right kind

Most businesses now want an AI assistant on WhatsApp that answers common questions, takes bookings and passes tricky cases to a person. The technology part is small: a webhook that receives the message, a call to a language model, and one request to send the answer.

The rules part matters more. Meta changed the terms of its official WhatsApp Business API so that general-purpose AI chatbots (the kind that answer any question on any topic) are not allowed there from 15 January 2026, while bots that serve a specific business purpose, such as support, orders and bookings, remain fine. QuackAPI is a linked-device service rather than the Business API, so Meta's Business API terms are not the contract you are under, but the lesson carries over. Build an assistant with a clear job for your own customers, not a general chatbot, and keep it low-volume, honest and easy to stop.

Only message people who have agreed to hear from you. QuackAPI is a linked-device service, not Meta's official Cloud API, so WhatsApp can restrict a number it considers abusive. Read the acceptable use policy before you automate anything.

What you will build

A small Node.js server with three jobs. Receive a customer message from the QuackAPI webhook. Send the last few messages plus your business instructions to a language model. Send the reply back with POST /v1/messages/chat. It also remembers the last few turns per customer, answers STOP by staying silent, and hands over to a human when the customer asks for one.

Step 1: Receive the message and answer the webhook first

Set the server's URL as the webhook URL on your QuackAPI device. Incoming messages arrive as event message.received with from, content and messageId (see the webhook reference). Reply 200 straight away. Language models can take several seconds, and a webhook that waits for them may time out and be sent again.

javascript
const express = require("express");
const app = express();
app.use(express.json());

const history = new Map();   // phone -> last messages (use Redis or a database in production)
const handled = new Set();   // messageIds already processed
const humanOnly = new Set(); // numbers handed over to a person
const stopped = new Set();   // numbers that said STOP

app.post("/webhooks/whatsapp", (req, res) => {
  res.sendStatus(200);
  const evt = req.body;
  if (evt.event !== "message.received" || !evt.content) return;
  if (handled.has(evt.messageId)) return;
  handled.add(evt.messageId);
  reply(evt.from, String(evt.content)).catch((e) => console.error("assistant error", e.message));
});

app.listen(3000);

Step 2: Ask the model with a narrow job description

The system prompt is where you keep the assistant on topic. Tell it what the business is, what it may answer, what to do when it does not know and when to hand over. Keep the history short (the last six messages is plenty for support-style chats) to control cost and avoid drift.

The example uses Anthropic's Messages API. Any model API works the same way: send the instructions and the recent messages, read back the text. Set the model name in an environment variable so you can change it without touching code.

javascript
const SYSTEM = [
  "You are the WhatsApp assistant for Bright Dental, a dental clinic.",
  "Answer only questions about opening hours, prices on our price list, location and booking.",
  "Hours: Mon-Sat 9:00-18:00. Address: 12 Garden Road. Cleaning from $40.",
  "Keep replies under 60 words, friendly and plain. No medical advice.",
  "If you do not know something, or the person asks for a human, say you will pass it to the team and reply exactly: HANDOVER",
].join(" ");

async function askModel(messages) {
  const res = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "content-type": "application/json",
      "x-api-key": process.env.ANTHROPIC_API_KEY,
      "anthropic-version": "2023-06-01",
    },
    body: JSON.stringify({
      model: process.env.LLM_MODEL,
      max_tokens: 300,
      system: SYSTEM,
      messages, // [{ role: "user" | "assistant", content: "..." }]
    }),
  });
  if (!res.ok) throw new Error("model error " + res.status);
  const data = await res.json();
  return data.content?.[0]?.text?.trim() || "";
}

Step 3: Reply, remember and hand over

The reply function ties it together. It stops for numbers that opted out, stays silent for numbers already with a human, adds the message to a short history, asks the model, and sends the answer. When the model answers HANDOVER, the code tells the customer a person will follow up and alerts your team on a number you own.

javascript
async function sendWhatsApp(to, body) {
  const res = await fetch("https://quackapi.com/v1/messages/chat", {
    method: "POST",
    headers: { "Content-Type": "application/json", "x-api-key": process.env.QUACKAPI_KEY },
    body: JSON.stringify({ deviceId: Number(process.env.QUACKAPI_DEVICE), to, body }),
  });
  if (!res.ok) throw new Error("send failed " + res.status);
}

async function reply(phone, text) {
  if (stopped.has(phone) || humanOnly.has(phone)) return;
  if (text.trim().toUpperCase() === "STOP") { stopped.add(phone); return; }

  const turns = history.get(phone) || [];
  turns.push({ role: "user", content: text });
  const recent = turns.slice(-6);
  while (recent.length && recent[0].role !== "user") recent.shift(); // must start with a user message

  const answer = await askModel(recent);
  if (!answer) return;

  if (answer.includes("HANDOVER")) {
    humanOnly.add(phone);
    await sendWhatsApp(phone, "Thanks, I have passed this to our team and someone will reply soon.");
    await sendWhatsApp(process.env.TEAM_NUMBER, "Customer " + phone + " needs a person: " + text);
    return;
  }

  turns.push({ role: "assistant", content: answer });
  history.set(phone, turns.slice(-12));
  await new Promise((r) => setTimeout(r, 1500 + Math.random() * 1500)); // a human-like pause
  await sendWhatsApp(phone, answer);
}

Guardrails that keep it useful and safe

Keep it on one job. The narrower the system prompt, the fewer odd answers and the lower the chance of the assistant saying something you would not. Give it facts to quote (hours, prices, policies) instead of letting it guess.

Never let it invent. Tell it to hand over when it does not know. Do not let it handle payments, medical or legal advice, or anything where a wrong answer costs money or health.

Limit volume per number. Cap replies per customer per hour, and ignore your own number's messages so the assistant never answers itself. Only reply to people who wrote to you first. Do not use the assistant to start cold conversations. The messaging best practices and number ban guide cover pacing and opt-outs.

Tell people it is automated and give them a way out. A short first message such as "I'm the clinic's automated assistant, type HUMAN to reach the team" avoids confusion and complaints. Add HUMAN as a second handover keyword if you like.

Log conversations in your own database for quality checks, and tell customers in your privacy policy that messages are processed by an AI service.

Can I use ChatGPT, Claude or Gemini with QuackAPI?
Yes. QuackAPI only delivers messages. Your server decides which model API to call, so any provider with an HTTP API works. The example uses Anthropic's Messages API.
Is a WhatsApp AI chatbot allowed?
On Meta's official Business API, bots that serve a specific business purpose are allowed and general-purpose AI assistants are not (from 15 January 2026). QuackAPI is a linked-device service with different terms, but WhatsApp can still restrict a number that behaves like spam. Keep the bot narrow, low-volume and opt-in.
How do I keep costs down?
Keep the history short, cap max_tokens, answer common questions from a fixed FAQ before calling the model, and use a small, fast model for routine support.
Will it answer in other languages?
Most current language models reply in the customer's language. Say in the system prompt which languages you support and what to do otherwise.
Where do I host this?
Anywhere that can receive an HTTPS webhook: a small VPS, a Node host, or a serverless function with a queue. See the Python version in the chatbot guide if you prefer Python.

Ready to get started?

Send WhatsApp Messages via API — Free

No Meta Business verification. No credit card. Connect your WhatsApp in under 2 minutes and start sending messages through the REST API.

Related Articles