<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: we take forward</title>
    <description>The latest articles on DEV Community by we take forward (@wetake_fwd).</description>
    <link>https://dev.to/wetake_fwd</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4252139%2Fdf9bede2-8449-42c6-b908-7629a58864cf.png</url>
      <title>DEV Community: we take forward</title>
      <link>https://dev.to/wetake_fwd</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/wetake_fwd"/>
    <language>en</language>
    <item>
      <title>Build a WhatsApp AI Agent That Takes Orders, with Node.js</title>
      <dc:creator>we take forward</dc:creator>
      <pubDate>Wed, 18 Nov 2026 15:02:16 +0000</pubDate>
      <link>https://dev.to/wetake_fwd/build-a-whatsapp-ai-agent-that-takes-orders-with-nodejs-4m8c</link>
      <guid>https://dev.to/wetake_fwd/build-a-whatsapp-ai-agent-that-takes-orders-with-nodejs-4m8c</guid>
      <description>&lt;p&gt;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.&lt;br&gt;
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.&lt;br&gt;
We'll use Express, the official WhatsApp Cloud API, and an LLM with tool calling. The core is about 150 lines.&lt;br&gt;
How it works&lt;br&gt;
Every incoming message goes through the same five steps:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; The customer sends a WhatsApp message to your business number.&lt;/li&gt;
&lt;li&gt; Meta's Cloud API sends it to your webhook (POST /webhook).&lt;/li&gt;
&lt;li&gt; Your server passes the text, plus a list of tools, to the LLM.&lt;/li&gt;
&lt;li&gt; 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.&lt;/li&gt;
&lt;li&gt; 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 &amp;amp;&amp;amp; 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';&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;const app = express();&lt;br&gt;
app.use(express.json());&lt;/p&gt;

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

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

&lt;p&gt;app.post('/webhook', (req, res) =&amp;gt; {&lt;br&gt;
  res.sendStatus(200); // reply fast, then do the work&lt;/p&gt;

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

&lt;p&gt;handleMessage(msg.from, msg.text.body).catch(console.error);&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;async function handleMessage(from, text) {&lt;br&gt;
  const reply = await runAgent(from, text);&lt;br&gt;
  await sendText(from, reply);&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;app.listen(process.env.PORT, () =&amp;gt;&lt;br&gt;
  console.log(&lt;code&gt;Listening on :${process.env.PORT}&lt;/code&gt;)&lt;br&gt;
);&lt;br&gt;
In the Meta dashboard, set the callback URL to https:///webhook, paste the same verify token, and subscribe to the messages field.&lt;br&gt;
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.&lt;br&gt;
Step 2: The agent loop&lt;br&gt;
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.&lt;br&gt;
Create agent.js:&lt;br&gt;
import Anthropic from '@anthropic-ai/sdk';&lt;/p&gt;

&lt;p&gt;const client = new Anthropic(); // reads ANTHROPIC_API_KEY&lt;/p&gt;

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

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

&lt;p&gt;function runTool(name, input, customer) {&lt;br&gt;
  if (name === 'get_menu') return MENU;&lt;/p&gt;

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

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

&lt;p&gt;return { error: &lt;code&gt;Unknown tool: ${name}&lt;/code&gt; };&lt;br&gt;
}&lt;/p&gt;

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

&lt;p&gt;const history = new Map(); // customer phone -&amp;gt; messages&lt;/p&gt;

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

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

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (res.stop_reason !== 'tool_use') {
  history.set(customer, trimHistory(messages));
  return res.content
    .filter((b) =&amp;gt; b.type === 'text')
    .map((b) =&amp;gt; b.text)
    .join('\n');
}

// Run every tool the model asked for and send the results back
const results = res.content
  .filter((b) =&amp;gt; b.type === 'tool_use')
  .map((b) =&amp;gt; ({
    type: 'tool_result',
    tool_use_id: b.id,
    content: JSON.stringify(runTool(b.name, b.input, customer)),
  }));
messages.push({ role: 'user', content: results });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;return 'Sorry, something went wrong. A team member will reply shortly.';&lt;br&gt;
}&lt;br&gt;
Three things to notice:&lt;br&gt;
• The model never sees your database. It only sees what runTool returns.&lt;br&gt;
• Prices come from your code, not the model. create_order calculates the total itself, so the AI can't make up a number.&lt;br&gt;
• The loop is capped at 5 steps, so a confused model can't run up your bill.&lt;br&gt;
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.&lt;br&gt;
Step 3: Send the reply&lt;br&gt;
The Cloud API sends a message with one POST to your phone number's /messages endpoint. Create whatsapp.js:&lt;br&gt;
export async function sendText(to, body) {&lt;br&gt;
  const url = &lt;code&gt;https://graph.facebook.com/${process.env.GRAPH_VERSION}/${process.env.WA_PHONE_ID}/messages&lt;/code&gt;;&lt;/p&gt;

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

&lt;p&gt;if (!res.ok) console.error('WhatsApp send failed:', await res.text());&lt;br&gt;
}&lt;br&gt;
Run it:&lt;br&gt;
node server.js&lt;br&gt;
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.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>javascript</category>
      <category>node</category>
      <category>tutorial</category>
    </item>
  </channel>
</rss>
