Build a WhatsApp AI Agent With n8n (No Code)
Build a WhatsApp AI chatbot using n8n and the WhatsApp Business API. This step-by-step tutorial covers webhook setup, message handling, AI responses, and deployment - all without writing code.
10+ years shipping production ML across TensorFlow, PyTorch, AWS, and GCP. Ships every A8gent agent before it becomes a lesson. GitHub
- The WhatsApp Business API combined with n8n's AI Agent node lets you build intelligent WhatsApp bots that understand natural language, maintain conversation context, and perform real actions like booking appointments or checking order status.
- You need a Meta Business account, a WhatsApp Business API phone number, and a publicly accessible n8n instance (or ngrok for local development) to receive webhook events from WhatsApp.
- Session management is critical - use the sender's phone number as the memory session ID so each customer gets their own conversation history and the agent remembers context across multiple messages.
- Always implement a human handoff mechanism for complex issues the AI cannot resolve - route the conversation to a live agent via your help desk platform when the AI's confidence is low.
- WhatsApp has strict messaging rules: you can only send free-form messages within 24 hours of the customer's last message. Outside this window, you must use pre-approved message templates.
Why WhatsApp AI Agents Are a Business Game-Changer
WhatsApp has over 2 billion active users worldwide. In markets like India, Brazil, and most of Europe, it is the default communication channel - more than email, more than SMS, more than any other messaging app. If your customers are on WhatsApp (and statistically, they are), meeting them there with an AI agent is one of the highest-impact automations you can build.
The traditional approach to WhatsApp customer service is hiring human agents who respond to messages manually. This is expensive (each agent handles 3-5 conversations simultaneously at best), slow (response times of 5-30 minutes during business hours, no coverage overnight), and inconsistent (quality depends on which agent responds). An AI agent on WhatsApp responds in 1-2 seconds, handles unlimited concurrent conversations, operates 24/7, and delivers consistent quality.
The business case is compelling. A mid-size e-commerce company handling 200 WhatsApp inquiries per day with three human agents (costing roughly $4,000/month in salary) can deploy an AI agent that handles 85% of those inquiries automatically. The remaining 15% - complex issues requiring human judgment - get escalated to a single human agent. Total cost drops from $4,000 to roughly $800/month (one agent plus API costs), while response time drops from 15 minutes to 2 seconds and availability expands from 8 hours to 24/7.
n8n is the ideal platform for building WhatsApp AI agents because it handles the complex integration plumbing - webhook verification, message parsing, session management, API formatting - through visual nodes. You focus on defining what your agent should do, not on implementing the WhatsApp Business API protocol. Compared to building a custom WhatsApp bot with code, n8n reduces development time from weeks to hours and eliminates the ongoing maintenance burden of managing API updates and edge cases.
In this tutorial, we will build a complete WhatsApp AI agent using n8n. The agent will receive WhatsApp messages, understand the customer's intent using an LLM, perform actions (checking order status, booking appointments, answering FAQs), and send intelligent responses back through WhatsApp. We will also implement human handoff for complex issues and conversation logging for analytics. If you want a broader overview of building AI agents in n8n first, start with our n8n AI Agent Tutorial and come back here for the WhatsApp-specific implementation.
Before we begin, you need three things: a Meta Business account with access to the WhatsApp Business API, an n8n instance accessible from the internet (cloud-hosted n8n works out of the box; for self-hosted, you need a public URL or a tunneling service like ngrok), and an LLM API key (OpenAI or Anthropic). The WhatsApp Business API is free for the first 1,000 conversations per month - more than enough for testing and initial deployment.
Setting Up the WhatsApp Business API and Webhooks
The WhatsApp Business API is the official way to programmatically send and receive WhatsApp messages. Unlike the consumer WhatsApp app, the Business API is designed for automation - it supports webhooks for real-time message delivery, template messages for outbound notifications, and media handling for images, documents, and audio. Here is how to set it up for your n8n agent.
First, go to the Meta Developer Portal and create a new app. Select "Business" as the app type. Once created, navigate to the WhatsApp product page and add it to your app. Meta provides a free test phone number that you can use during development - you do not need to verify a real business phone number until you are ready for production. Note down the Phone Number ID, WhatsApp Business Account ID, and the temporary Access Token from the API Setup page.
Now configure the webhook in n8n. Create a new workflow and add a Webhook node. Set the HTTP method to POST and note the webhook URL (something like https://your-n8n-instance.com/webhook/whatsapp). In the Meta Developer Portal, go to the WhatsApp Configuration page and set the webhook URL to your n8n webhook URL. For the verification token, use any string you choose and configure the same string in n8n's webhook node under "Webhook Verification." Meta will send a GET request to verify the URL - n8n handles this verification automatically when configured correctly.
Subscribe to the messages webhook field. This ensures n8n receives a POST request every time someone sends a message to your WhatsApp Business number. The webhook payload contains the sender's phone number, message content, message type (text, image, audio, document), and a timestamp. In n8n, the Webhook node captures this payload as JSON that you can process in subsequent nodes.
A critical detail many tutorials skip: the WhatsApp webhook sends all events, not just incoming messages. You will receive status updates (message delivered, message read), system events, and error notifications. Your n8n workflow needs to filter these. Add an IF node immediately after the Webhook that checks whether the payload contains an actual message: {{ $json.entry[0].changes[0].value.messages }} exists and is not empty. Only continue to the AI Agent if this condition is true - otherwise, respond with a 200 status and stop processing. Failing to filter non-message events is the number one cause of unexpected behavior in WhatsApp bot workflows.
The IF node's condition expression looks like this:
Condition: exists and is not empty
Value: {{ $json.entry[0].changes[0].value.messages }}
// exists -> payload contains an actual inbound message
// is not empty -> ignores status updates, reads, and system events
For local development with self-hosted n8n, use ngrok to create a public URL for your local instance. Run ngrok http 5678 and use the generated HTTPS URL as your webhook base. Remember that ngrok URLs change every time you restart (unless you have a paid plan), so you will need to update the webhook URL in the Meta Developer Portal each time. For production, use a proper domain with SSL - the WhatsApp API requires HTTPS for webhook endpoints. The n8n webhook documentation covers advanced configuration including authentication and custom headers.
Test the webhook by sending a message from your personal WhatsApp to the test number. You should see the execution appear in n8n's execution log with the full message payload. If nothing appears, check three things: the webhook URL is correct in Meta's portal, the webhook verification succeeded (check the n8n logs), and your n8n instance is accessible from the internet. Once you see incoming messages flowing into n8n, the hardest part is done - everything from here is agent configuration.
Building the WhatsApp AI Agent Workflow
With the webhook receiving messages, let us build the AI agent that processes them. The workflow architecture has five stages: parse the incoming message, run it through the AI Agent, format the response for WhatsApp, send the reply, and log the interaction.
After the Webhook and IF filter nodes, add a Set node to extract the relevant fields from the WhatsApp payload. Map the sender's phone number to a userPhone variable: {{ $json.entry[0].changes[0].value.messages[0].from }}. Map the message text to userMessage: {{ $json.entry[0].changes[0].value.messages[0].text.body }}. Map the message ID for read receipts: {{ $json.entry[0].changes[0].value.messages[0].id }}. This clean data extraction makes the rest of your workflow much simpler to build and debug.
Next, add the AI Agent node. Configure it with a system prompt tailored for WhatsApp interactions: "You are a customer service assistant for [Your Company]. You help customers check order status, answer product questions, and book appointments. Keep responses concise - WhatsApp users expect short, clear messages. Use line breaks to improve readability. Never use markdown formatting (WhatsApp does not render it). If you cannot help with something, say so and offer to connect them with a human agent." The emphasis on concise responses is important - WhatsApp is a mobile-first platform where long paragraphs feel overwhelming.
Here is that system prompt written out in full, ready to paste into the AI Agent node:
You are a customer service assistant for [Your Company].
You help customers check order status, answer product
questions, and book appointments. Keep responses concise -
WhatsApp users expect short, clear messages. Use line breaks
to improve readability. Never use markdown formatting
(WhatsApp does not render it). If you cannot help with
something, say so and offer to connect them with a human
agent.
Connect your LLM (OpenAI, Anthropic, or your preferred provider) and add the tools your agent needs. For an e-commerce WhatsApp bot, typical tools include: an HTTP Request tool configured to call your order management API (so the agent can look up order status by order ID or customer email), a Google Sheets tool reading from your FAQ spreadsheet (faster and cheaper than vector search for small knowledge bases), and a Code tool for date calculations (scheduling appointments, calculating delivery estimates).
Memory configuration is crucial for WhatsApp agents. Add a Window Buffer Memory node and set the session ID to the customer's phone number: {{ $('Set').item.json.userPhone }}. This ensures each customer has their own conversation history. Set the context window to 8-12 messages - enough for a meaningful conversation but not so much that token costs spiral. WhatsApp conversations tend to be shorter and more transactional than web chat, so a moderate window is usually sufficient.
After the AI Agent produces a response, add an HTTP Request node to send the reply through the WhatsApp Business API. Configure it as a POST request to https://graph.facebook.com/v19.0/YOUR_PHONE_NUMBER_ID/messages with your access token in the Authorization header. The body should be: {"messaging_product": "whatsapp", "to": "{{ $('Set').item.json.userPhone }}", "text": {"body": "{{ $('AI Agent').item.json.output }}"}}. This sends the agent's response back to the customer's WhatsApp. The WhatsApp Cloud API documentation covers message formatting options including lists, buttons, and media.
The full JSON body for that HTTP Request node looks like this:
{
"messaging_product": "whatsapp",
"to": "{{ $('Set').item.json.userPhone }}",
"text": {
"body": "{{ $('AI Agent').item.json.output }}"
}
}
Finally, add a logging step. Append each interaction to a Google Sheet or database with columns for timestamp, phone number, user message, agent response, tools used, and response time. This data is invaluable for monitoring performance, identifying common questions, and improving your agent over time. You can also use it to build reports showing how many conversations the AI handled versus how many required human intervention.
Implementing Human Handoff for Complex Issues
No AI agent can handle every situation. The customer whose order was damaged in shipping and wants a replacement. The user asking about a product that is not in your catalog. The frustrated customer who has already tried three solutions and needs empathetic human interaction. Your WhatsApp agent needs a graceful path to hand these conversations to a human agent.
The simplest human handoff pattern in n8n uses keyword detection combined with AI judgment. Add instructions to your system prompt: "If the customer explicitly requests a human agent, if the issue involves a complaint or refund over $50, or if you have been unable to resolve the query after two attempts, respond with the exact phrase HANDOFF_REQUIRED at the beginning of your message, followed by a brief summary of the issue for the human agent." Then add an IF node after the AI Agent that checks whether the response starts with "HANDOFF_REQUIRED."
When the handoff condition is true, the workflow branches to a handoff sub-flow. This sub-flow does three things: (1) sends a message to the customer saying "I am connecting you with a team member who can help further. Please hold on - they will respond shortly," (2) forwards the conversation summary to your support team via Slack, email, or your help desk platform (Zendesk, Freshdesk, Intercom), and (3) updates a flag in your session store indicating that this phone number is now in "human mode" - subsequent messages should bypass the AI agent and route directly to the human agent.
The "human mode" flag is important. Without it, the AI agent will keep intercepting messages even after handoff, creating a confusing experience where the customer is simultaneously talking to the AI and a human. Add a check at the very beginning of your workflow (after the webhook, before the AI Agent) that looks up the customer's phone number in a datastore (Google Sheets, Redis, or a database) and checks whether they are in human mode. If yes, forward the message to the human agent and skip the AI entirely. The human agent can "release" the conversation back to the AI by toggling the flag when the issue is resolved.
A more sophisticated approach uses the AI's confidence scoring. Instead of relying on explicit keywords, have the AI Agent output a structured response with both the message and a confidence score. Use an Output Parser node configured to expect JSON like {"response": "...", "confidence": 0.85, "category": "order_status"}. A sample structured output from the AI Agent, ready for the Output Parser node, looks like this:
{
"response": "Your order #48213 shipped yesterday and is
expected to arrive within 2-3 business days.",
"confidence": 0.85,
"category": "order_status"
}
// Low-confidence example that should trigger handoff:
{
"response": "I'm not fully sure how to resolve this refund
request, connecting you with a team member.",
"confidence": 0.32,
"category": "refund_dispute"
}
Then route based on confidence: above 0.8 goes directly to the customer, between 0.5 and 0.8 goes to a human for review before sending, and below 0.5 triggers immediate handoff. This ensures that even borderline responses get human oversight. For a deeper dive into building support systems with escalation logic, see our customer support agent with n8n guide.
Track your handoff rate as a key metric. If more than 20% of conversations require human handoff, your agent needs improvement - either better tools, a better knowledge base, or a refined system prompt. If handoff drops below 5%, review some escalated conversations to make sure the agent is not confidently giving wrong answers when it should be escalating. The sweet spot for most businesses is 10-15% handoff rate, which means the AI handles the vast majority of routine inquiries while humans focus on genuinely complex issues that benefit from personal attention.
WhatsApp also supports interactive messages - buttons and list menus - that make handoff more user-friendly. Instead of asking users to type "speak to a human," send a message with a button labeled "Talk to a Human." The WhatsApp interactive messages documentation explains the format. In n8n, send interactive messages by adjusting the HTTP Request body to use the interactive message type instead of plain text. This creates a more polished user experience and makes intent detection trivial - a button click is unambiguous.
Handling Media Messages: Images, Audio, and Documents
WhatsApp users do not just send text. They send photos of damaged products, voice messages describing their issue, screenshots of error messages, and PDF documents. A production-grade WhatsApp AI agent needs to handle all of these media types.
When a user sends an image, the WhatsApp webhook payload includes a media ID instead of the image data itself. You need a two-step process: first, call the WhatsApp API to get the media URL (GET https://graph.facebook.com/v19.0/{media_id}), then download the image from that URL. In n8n, add two consecutive HTTP Request nodes for this. The first retrieves the download URL, and the second downloads the actual file. Once you have the image data, you can send it to an LLM with vision capabilities (GPT-4o, Claude 3.5 Sonnet) for analysis.
For image analysis, configure your AI Agent's LLM to accept image inputs. With OpenAI's GPT-4o, this means including the image as a base64-encoded data URL in the message content. In n8n, use a Code node to convert the downloaded image to base64 and format it as a proper multi-modal message. The AI can then describe what it sees - "This appears to be a photo of a cracked phone screen" - and respond accordingly. This is incredibly powerful for customer support: a customer can photograph a defective product and the AI agent can immediately identify the issue and initiate a return process.
Voice messages require speech-to-text conversion before the AI agent can process them. Download the audio file using the same media retrieval process as images. Then send the audio to a transcription service - OpenAI's Whisper API (POST https://api.openai.com/v1/audio/transcriptions) is the most popular choice, offering high accuracy across dozens of languages. In n8n, use an HTTP Request node to call the Whisper API with the audio file, extract the transcribed text, and feed it to your AI Agent as if the customer had typed it. The customer's experience is seamless - they send a voice note and receive an intelligent text response.
Document handling (PDFs, spreadsheets, Word documents) follows a similar pattern: download the file, extract text, and pass it to the AI. For PDFs, you can use n8n's Extract from File node or an external service like Apache Tika via HTTP Request. For spreadsheets, the Spreadsheet File node in n8n parses the data into JSON. The AI agent can then analyze the document content and respond to questions about it - for example, a customer might send their invoice PDF and ask "When is this due?"
A practical optimization: not every media message needs AI analysis. If a customer sends a sticker or a reaction emoji, you probably do not need to process it. Add a routing Switch node early in your workflow that checks the message type (text, image, audio, document, sticker, reaction) and routes each type to the appropriate processing path. Text goes directly to the AI Agent, images go through the vision pipeline, audio goes through transcription, and stickers/reactions get a simple acknowledgment or are ignored entirely.
Media handling adds latency to your agent's response time. Downloading media, converting formats, and calling transcription or vision APIs each add 1-5 seconds. For voice messages especially, the total processing time can reach 10-15 seconds. Manage user expectations by sending an immediate acknowledgment ("Got your voice message, let me listen...") before processing, then following up with the actual response. In n8n, use the Wait node or simply add a "typing indicator" API call before the processing chain. This small UX touch significantly improves the perceived responsiveness of your WhatsApp AI agent.
Message Templates, Rate Limits, and WhatsApp Compliance
WhatsApp has strict rules about how businesses can communicate with customers. Understanding these rules before deploying your agent prevents account suspension and ensures reliable operation.
The most important rule is the 24-hour conversation window. When a customer messages you, a 24-hour window opens during which you can send free-form messages (your AI agent's responses). Once this window closes, you can only send pre-approved message templates. Templates must be submitted to Meta for review and typically take 1-24 hours for approval. Common templates include order confirmations ("Your order #{{1}} has been shipped"), appointment reminders ("Reminder: your appointment is tomorrow at {{1}}"), and follow-up messages ("Hi {{1}}, we wanted to check if your issue was resolved").
In n8n, implement template management with a Switch node that checks whether the current conversation is within the 24-hour window. Store the timestamp of each customer's last incoming message in your session datastore. Before sending any message, calculate whether the window is still open. If yes, send a regular message. If no, send a template message or queue the message for when the customer next reaches out. This prevents failed message sends and potential account restrictions.
A Code node that checks whether the 24-hour window is still open might look like this:
const lastMessageTimestamp = $input.first().json.lastIncomingMessageAt;
const lastMessageDate = new Date(lastMessageTimestamp);
const now = new Date();
const hoursSinceLastMessage =
(now.getTime() - lastMessageDate.getTime()) / (1000 * 60 * 60);
const windowOpen = hoursSinceLastMessage < 24;
return [
{
json: {
hoursSinceLastMessage: hoursSinceLastMessage,
windowOpen: windowOpen,
},
},
];
Rate limits are another consideration. The WhatsApp Business API has tiered sending limits based on your account quality and verification status. New accounts start at 250 business-initiated conversations per 24 hours and can scale up to unlimited with good account health. Customer-initiated conversations (where the customer messages you first) do not count against this limit - your AI agent responding to incoming messages is always allowed. The limit only applies to business-initiated outreach.
Message quality is monitored by Meta. If too many customers report or block your number, your quality rating drops and your sending limits decrease. For AI agents, the biggest risk is irrelevant or repetitive responses that frustrate users. Ensure your agent has a clear opt-out mechanism ("Type STOP to stop receiving messages") and respect it immediately. In n8n, add an IF node that checks for stop/unsubscribe keywords before processing and adds the phone number to a blocklist when detected. This is not just good UX - it is required by WhatsApp's Business Policy.
For production deployment, upgrade from the test phone number to a verified business number. This requires a Meta Business Verification process where you verify your business entity with official documents. Once verified, you get a green checkmark badge on your WhatsApp profile, higher sending limits, and access to WhatsApp Commerce features. The verification process takes 3-7 business days - start it well before your planned launch date.
Data privacy compliance depends on your region. In the EU, WhatsApp conversations fall under GDPR - you need user consent before processing personal data, a clear privacy policy, and the ability to delete user data on request. In your n8n workflow, add a first-time user check that sends a consent message before the AI agent processes any queries. Store consent status alongside the session data. For comprehensive privacy compliance, consider using n8n's self-hosted option so all conversation data stays on your infrastructure. If your business processes personal data through multiple AI agents, our AI agent security and privacy guide covers compliance frameworks in detail.
Scaling and Monitoring Your WhatsApp AI Agent
A WhatsApp AI agent that works for 10 test messages needs additional consideration before handling 1,000 real customer conversations per day. Here is how to scale and monitor effectively.
Concurrency is the first scaling concern. When multiple customers message simultaneously, n8n needs to process all those webhooks concurrently. n8n cloud handles this automatically with queue-based processing. For self-hosted n8n, configure the EXECUTIONS_MODE=queue environment variable and set up a Redis instance for the queue backend. This ensures webhook events are queued and processed reliably even during traffic spikes. Without queue mode, simultaneous webhooks might be dropped or processed out of order.
Monitor response latency as your primary performance metric. Measure the time from webhook receipt to WhatsApp reply sent. Acceptable latency is under 5 seconds for text-only conversations and under 15 seconds for media processing. If latency exceeds these thresholds, investigate the bottleneck - it is usually the LLM API call. Mitigation strategies include using faster models (GPT-4o-mini instead of GPT-4o), reducing memory context size, or implementing response streaming where you send partial responses as they are generated.
Cost monitoring is essential at scale. At 1,000 conversations per day with an average of 4 messages per conversation, you are making roughly 4,000 LLM API calls daily. With GPT-4o at approximately $0.01 per call (including input and output tokens), that is $40/day or $1,200/month in API costs alone. Track costs per conversation in your logging spreadsheet and set up alerts when daily spending exceeds your budget. Consider using cheaper models for simple intent classification (determining if the query is an FAQ, order status, or requires AI reasoning) and only calling the expensive model for complex queries that need genuine reasoning.
Build a monitoring dashboard using n8n itself. Create a scheduled workflow that runs every hour, queries the n8n execution history API, and computes: total conversations, average response time, error rate, handoff rate, and top 10 most common queries. Store these metrics in a Google Sheet and build a simple dashboard with Google Data Studio, or send a daily summary to your team's Slack channel. The meta-automation pattern - using n8n to monitor n8n - is elegant and requires no additional infrastructure.
Implement conversation analytics to continuously improve your agent. Tag each conversation with the outcome: resolved autonomously, escalated to human, abandoned by user, or error. Calculate your autonomous resolution rate weekly and track the trend. Identify the top reasons for human escalation and address them - usually by adding better tools, expanding the knowledge base, or refining the system prompt. The best WhatsApp AI agents achieve 85-90% autonomous resolution within three months of iterative improvement.
Finally, plan for multi-language support if your customers span different regions. Modern LLMs handle multilingual conversations natively - a customer can message in Spanish and the agent responds in Spanish without any special configuration. However, your tools and knowledge base might be in English only. For truly multilingual support, either maintain translated knowledge bases or add a translation step in your workflow. The n8n AI Agent documentation covers multi-language configurations. For businesses deploying across multiple channels simultaneously, our complete guide to building AI agents with n8n covers multi-channel architecture patterns that work for WhatsApp, web chat, and email simultaneously.
Want the same agent on an easier channel? Telegram needs no Meta verification and takes about half the setup time. And if you would rather start from a working workflow, browse our 10 n8n AI agent templates.
FAQ
Do I need to pay for the WhatsApp Business API?
The first 1,000 service conversations per month are free. Beyond that, pricing varies by country - typically $0.005-0.08 per conversation. Business-initiated conversations (where you message first) cost more than customer-initiated ones. API access itself is free through Meta's Cloud API.
Can I use the regular WhatsApp app instead of the Business API?
No. The regular WhatsApp app and WhatsApp Web do not provide APIs for automation. The WhatsApp Business API (Cloud API) is the only official way to build automated agents. Using unofficial libraries that scrape the web interface violates WhatsApp's terms and risks account bans.
How do I handle WhatsApp messages when my n8n instance is down?
WhatsApp retries webhook delivery for up to 7 days. When your n8n instance comes back online, it receives all queued messages. However, responses will be delayed. For high-availability, deploy n8n with redundancy using Docker Compose with multiple workers and a persistent queue backend.
Can the AI agent send images and videos back to customers?
Yes. The WhatsApp API supports sending images, videos, audio, documents, and interactive messages. In n8n, configure the reply HTTP Request node with the appropriate media message format instead of text. You can send product images, PDF invoices, or instructional videos as part of the agent's response.
How do I test without messaging real customers?
Use Meta's test phone number and add up to 5 personal numbers as test recipients. You can message these numbers freely during development. The n8n Chat Trigger also works for testing agent logic before connecting to WhatsApp - test the AI behavior first, then add the WhatsApp integration layer.
