← Blog

·

Claude (Anthropic) + WhatsApp Business API: AI customer service

Updated on November 24, 2026

To answer WhatsApp customers with Claude, you receive the message through the official API webhook, send that conversation’s history to Anthropic’s Messages API (client.messages.create) and return the reply with a Cloud API send call. When Claude needs data from your system, such as an order status, it asks to use a tool: your code runs the lookup and sends the result back so Claude can finish the answer. Free-form replies can only go out inside the 24-hour window opened by the customer.

Below you’ll find the full code in Python and the same loop in Node.js, using Anthropic’s official SDK.

Claude for customer service vs. ChatGPT vs. MCP

Two related articles cover AI on WhatsApp. This one takes a third angle:

ArticleWho talks to the AIWhat the AI does
ChatGPT on the WhatsApp Business APIThe customer, on WhatsAppReplies through OpenAI’s Responses API
WhatsApp MCP serverSomeone on your team, in an AI appThe agent sends WhatsApp messages as a tool
This articleThe customer, on WhatsAppClaude replies and looks up your system through tools

With MCP, WhatsApp is one of the agent’s tools. Here, WhatsApp is the channel, and Claude’s tools query your ERP, CRM or calendar.

Which Claude model to use

Anthropic’s models page, checked on November 24, 2026, lists these current models:

ModelAPI IDAnthropic’s description
Claude Opus 5.5claude-opus-5-5Long-running agentic work and knowledge work
Claude Sonnet 5.5claude-sonnet-5-5The best combination of speed and intelligence
Claude Haiku 5.5claude-haiku-5-5High-volume, latency-sensitive tasks: classification, extraction, routing

The example uses claude-sonnet-5-5, because WhatsApp customers expect an answer within seconds. Keep the ID in an environment variable (CLAUDE_MODEL) so you can try Haiku or Opus, or switch when Anthropic ships a new model, without touching the code. Per-token prices vary by model: see Anthropic’s pricing page and our guide to AI cost per conversation.

Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →

The flow in 5 steps

StepWhat happensWhere
1The customer sends a message and the webhook reaches your serverMeta → provider → your server
2You return 200 right away and process in the backgroundWebhook
3You load that wa_id‘s history from your databaseDatabase
4You call the Messages API; on tool_use, you run the tool and call againAnthropic + your system
5With the window open, the final text goes back to the customerPOST /messages

The Messages API is stateless: according to the Messages documentation, you always send the full conversation history. Your database is what remembers the customer, keyed by wa_id (the from field of the incoming message). To store and export those conversations, see how to save WhatsApp API chat history.

Tool use in one minute

Tools are functions you describe to Claude with name, description and input_schema (a JSON Schema). Per the tool use documentation, the cycle goes like this:

  1. You send the question along with the tools list.
  2. If Claude decides to use a tool, the response comes back with stop_reason: "tool_use" and one or more tool_use blocks (with id, name and input).
  3. You run each tool and call again: the earlier messages, the response content as an assistant message (unchanged), and a user message with one tool_result per tool_use.
  4. If a tool failed, the tool_result carries is_error: true and a clear error message.
  5. Repeat while you get tool_use. When you get end_turn, the text is ready.

Per the page on handling tool calls, the tool_result blocks must come right after the message with the tool_use blocks and first in the user message content, and the same tools list goes in every call.

Full Python code

The example uses FastAPI, the anthropic SDK and sending through Vectalk, which accepts the same JSON as the Cloud API. With an instance token, the sending number is resolved automatically; with an organization token, include phone_number_id in the body. If you integrate directly with Meta, change the URL to https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages and use your Meta token.

pip install anthropic fastapi uvicorn requests
export ANTHROPIC_API_KEY="your-anthropic-key"
export CLAUDE_MODEL="claude-sonnet-5-5"
export VECTALK_TOKEN="your-instance-token"
uvicorn bot:app --port 8000
import json
import os
import time

import anthropic
import requests
from fastapi import BackgroundTasks, FastAPI, Request

MODEL = os.environ.get("CLAUDE_MODEL", "claude-sonnet-5-5")
SEND_URL = "https://apis.vectalk.com.br/api/messages"
VECTALK_TOKEN = os.environ["VECTALK_TOKEN"]  # instance token
WINDOW_SECONDS = 24 * 60 * 60
MAX_MESSAGES = 20  # history messages sent to the model
MAX_ROUNDS = 5     # cap on tool calls per reply

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment
app = FastAPI()

SYSTEM = """You are the WhatsApp assistant for Example Store.
- Reply in English, in up to 3 short sentences, without markdown.
- Only talk about the store's orders, deliveries, returns and products.
- For order status, use get_order. Never make up dates or amounts.
- If the customer asks for a person, complains, asks to cancel or for a refund,
  or if you don't know the answer, use transfer_to_human."""

TOOLS = [
    {
        "name": "get_order",
        "description": "Looks up the status and delivery estimate of an order "
                       "from the customer in this conversation. Use it when they ask about an order.",
        "input_schema": {
            "type": "object",
            "properties": {
                "order_number": {"type": "string", "description": "Order number, e.g. 48213"}
            },
            "required": ["order_number"],
            "additionalProperties": False,
        },
        "strict": True,
    },
    {
        "name": "transfer_to_human",
        "description": "Hands the conversation over to a human agent.",
        "input_schema": {
            "type": "object",
            "properties": {
                "reason": {"type": "string", "description": "Short summary for the agent"}
            },
            "required": ["reason"],
            "additionalProperties": False,
        },
        "strict": True,
    },
]

# In production, replace with a database (Postgres, Redis) and a persistent queue.
conversations = {}  # wa_id -> {"state", "history", "last_inbound"}
processed = set()   # wamids already handled


def load(wa_id):
    return conversations.setdefault(
        wa_id, {"state": "bot", "history": [], "last_inbound": 0}
    )


def send(body):
    r = requests.post(
        SEND_URL,
        headers={"Authorization": f"Bearer {VECTALK_TOKEN}"},
        json={"messaging_product": "whatsapp", **body},
        timeout=15,
    )
    r.raise_for_status()
    return r.json()


def send_text(wa_id, text):
    return send({"to": wa_id, "type": "text", "text": {"body": text}})


def window_open(conversation):
    return time.time() - conversation["last_inbound"] < WINDOW_SECONDS


def find_order(number, wa_id):
    # Query your ERP filtering by phone (wa_id), never by order number alone.
    if number == "48213":
        return {"order": number, "status": "in transit", "estimate": "2026-11-28"}
    return None


def notify_agents(wa_id, reason):
    print(f"Handoff {wa_id}: {reason}")  # ticket queue, CRM, Slack...


def run_tool(block, wa_id, conversation):
    if block.name == "get_order":
        order = find_order(block.input["order_number"], wa_id)
        if order is None:
            return "Order not found for this customer.", True
        return json.dumps(order), False
    if block.name == "transfer_to_human":
        conversation["state"] = "human"
        notify_agents(wa_id, block.input["reason"])
        return "Transferred. Tell the customer a person will take over.", False
    return f"Unknown tool: {block.name}", True


def ask_claude(wa_id, conversation):
    messages = list(conversation["history"])  # the loop appends tool blocks
    for _ in range(MAX_ROUNDS):
        response = client.messages.create(
            model=MODEL,
            max_tokens=16000,
            system=SYSTEM,
            tools=TOOLS,
            output_config={"effort": "low"},  # lower latency for simple chat
            messages=messages,
        )
        if response.stop_reason == "tool_use":
            messages.append({"role": "assistant", "content": response.content})
            results = []
            for block in response.content:
                if block.type == "tool_use":
                    content, failed = run_tool(block, wa_id, conversation)
                    results.append({
                        "type": "tool_result",
                        "tool_use_id": block.id,
                        "content": content,
                        "is_error": failed,
                    })
            messages.append({"role": "user", "content": results})
            continue
        if response.stop_reason == "end_turn":
            text = "".join(b.text for b in response.content if b.type == "text")
            return text.strip() or None
        return None  # refusal, max_tokens, etc.: a person takes over
    return None


def trim(history):
    h = history[-MAX_MESSAGES:]
    while h and h[0]["role"] != "user":  # the first message must be from the user
        h = h[1:]
    return h


def process(msg):
    if msg["id"] in processed:
        return
    processed.add(msg["id"])
    wa_id = msg["from"]
    conversation = load(wa_id)
    conversation["last_inbound"] = int(msg["timestamp"])

    if conversation["state"] != "bot":
        return  # a human has taken over
    if msg["type"] != "text":
        send_text(wa_id, "For now I can only read text. Could you type your question?")
        return

    # Mark as read and show "typing..." while Claude replies
    send({"status": "read", "message_id": msg["id"], "typing_indicator": {"type": "text"}})
    conversation["history"].append({"role": "user", "content": msg["text"]["body"]})

    try:
        text = ask_claude(wa_id, conversation)
    except anthropic.APIError as e:
        print("Claude failed:", e)
        text = None
    if text is None:
        conversation["state"] = "human"
        notify_agents(wa_id, "model failure or refusal")
        text = "I'm bringing in someone from our team to continue here."

    if not window_open(conversation):
        return  # the window closed while processing: templates only

    send_text(wa_id, text)
    conversation["history"].append({"role": "assistant", "content": text})
    conversation["history"] = trim(conversation["history"])


@app.post("/webhook")
async def webhook(request: Request, tasks: BackgroundTasks):
    body = await request.json()
    for entry in body.get("entry", []):
        for change in entry.get("changes", []):
            for msg in change.get("value", {}).get("messages", []):
                tasks.add_task(process, msg)
    return {"ok": True}

Things worth noticing in the code:

  • Immediate webhook response. With tools, a reply takes two or more calls to Claude. On Vectalk, the endpoint must return HTTP 200 within 20 seconds or the event is resent, according to the webhooks documentation. That’s why processing runs in BackgroundTasks and the wamid deduplicates retries.
  • Round limit. MAX_ROUNDS keeps a repeating tool error from turning into an expensive loop.
  • Failure means handoff. An API error, a refusal (stop_reason: "refusal") or a cut-off reply (max_tokens) hand the conversation to a person instead of leaving the customer without an answer.
  • Generous max_tokens. Claude may reason before replying, and that counts toward max_tokens. Reply length is controlled by the system prompt.
  • Per-contact ordering. In production, use a queue with one consumer per wa_id so two back-to-back messages don’t run in parallel.

The “typing…” indicator uses the Cloud API typing_indicator: per the typing indicators documentation, it disappears when you reply or after 25 seconds, whichever comes first.

Why the history stores only text

Within a single reply, the loop sends Claude’s content back unchanged, as the documentation requires. In the database, the example saves only each exchange’s question and final answer: the record stays readable and easy to audit and trim (trim keeps the last 20 messages, always starting with a user message). If Claude needs the data again, it calls the tool again.

The same logic in Node.js

With the @anthropic-ai/sdk package, the loop is identical, and the tool definitions use exactly the same fields. The webhook, queue and sending follow the pattern from the WhatsApp bot with Node.js; the Python version without AI is in the bot with Python and FastAPI.

npm install @anthropic-ai/sdk
import Anthropic from '@anthropic-ai/sdk';
// SYSTEM and TOOLS with the same content as the Python example (same JSON);
// findOrder and notifyAgents live in your system
import { SYSTEM, TOOLS } from './config.mjs';
import { findOrder, notifyAgents } from './system.mjs';

const anthropic = new Anthropic(); // reads ANTHROPIC_API_KEY
const MODEL = process.env.CLAUDE_MODEL ?? 'claude-sonnet-5-5';
const MAX_ROUNDS = 5;

async function runTool(block, waId, conversation) {
  if (block.name === 'get_order') {
    const order = await findOrder(block.input.order_number, waId);
    if (!order) return { content: 'Order not found for this customer.', failed: true };
    return { content: JSON.stringify(order), failed: false };
  }
  if (block.name === 'transfer_to_human') {
    conversation.state = 'human';
    await notifyAgents(waId, block.input.reason);
    return { content: 'Transferred. Tell the customer a person will take over.', failed: false };
  }
  return { content: `Unknown tool: ${block.name}`, failed: true };
}

export async function askClaude(waId, conversation) {
  const messages = [...conversation.history];
  for (let round = 0; round < MAX_ROUNDS; round++) {
    const response = await anthropic.messages.create({
      model: MODEL,
      max_tokens: 16000,
      system: SYSTEM,
      tools: TOOLS,
      output_config: { effort: 'low' },
      messages,
    });
    if (response.stop_reason === 'tool_use') {
      messages.push({ role: 'assistant', content: response.content });
      const results = [];
      for (const block of response.content) {
        if (block.type !== 'tool_use') continue;
        const { content, failed } = await runTool(block, waId, conversation);
        results.push({ type: 'tool_result', tool_use_id: block.id, content, is_error: failed });
      }
      messages.push({ role: 'user', content: results });
      continue;
    }
    if (response.stop_reason === 'end_turn') {
      const text = response.content
        .filter((b) => b.type === 'text')
        .map((b) => b.text)
        .join('')
        .trim();
      return text || null;
    }
    return null; // refusal, max_tokens: handoff
  }
  return null;
}

The 24-hour window: Claude replies, it doesn’t reach out

Meta’s send messages documentation says each customer message opens (or resets) a 24-hour customer service window. While it’s open, you can send text, media and interactive messages. Once it closes, only approved templates.

In a Claude bot, that becomes three coding rules:

  • Check the window right before sending, not only when the message arrives. A slow tool loop, a stalled queue or a retry can cross the limit. The example compares last_inbound with the clock just before sending.
  • Generated text never goes out after the window. To re-engage (“your order has arrived”), use a template whose variables come from your system, not from the model.
  • The bot is reactive. Details in the WhatsApp 24-hour customer service window.

Tool safety

With tool use, Claude picks the tool and its arguments, but your code is what runs it. Three precautions:

  • Identity comes from the webhook, not the model. The wa_id passed to find_order comes from the message’s from field. If the customer types someone else’s order number, the phone-filtered lookup returns nothing.
  • Reading is free; actions need confirmation. Cancelling an order, rescheduling or creating a charge needs an explicit “yes” from the customer or a person. See the guide to an AI agent with tools.
  • External content is data, not instructions. Anthropic recommends keeping content from external sources inside tool_result blocks, not in the system prompt.

For the handoff itself, see WhatsApp chatbot to human handoff. If the conversation involves personal data of people in Brazil, the LGPD, Brazil’s data protection law (Law 13,709/2018), applies to what you send to the AI provider; this article is not legal advice.

What Meta allows

Since January 15, 2026, section 4.7 of the Meta Terms for WhatsApp Business Platform bars AI Providers from using the platform when general-purpose AI is the primary functionality of what they offer. Using Claude to serve your own business (orders, scheduling, support) is still allowed; a “chat with an AI about anything” service is a different case. The full rule and Brazil’s exception are covered in WhatsApp API AI policy in 2026.

How much it costs

There are two bills:

  • WhatsApp. Replies inside the window are service messages. Since October 1, 2026, each number has an allowance of 1,000 service messages per month; from the 1,001st on, for recipients in Brazil, the rate is BRL 0.0350 per message, according to Meta’s pricing page. Templates are charged by category, inside or outside the window (marketing BRL 0.3217; utility and authentication BRL 0.0350).
  • Anthropic. Billed by input and output tokens, priced per model, on Anthropic’s pricing page. Tool definitions, the resent history and each tool_result round count as input.

The per-conversation math, adding both parts, is in how much an AI chatbot on WhatsApp costs per conversation. What matters most: short history, one reply per question and the right model for each kind of question.

How to do this with Vectalk

Vectalk is a proxy for the official WhatsApp API: your bot receives webhooks in Meta’s format and sends with the same Cloud API JSON to POST https://apis.vectalk.com.br/api/messages, with Authorization: Bearer <token>. With an instance token, phone_number_id is resolved automatically; with an organization token, include phone_number_id in the body (authentication). You register the bot URL with POST https://apis.vectalk.com.br/api/webhooks, passing instance_id, url and name.

Vectalk has no built-in AI, support inbox or bulk messaging in its dashboard: Claude runs on your server, as in the example. If you code with an AI assistant, the documentation offers a search MCP server at https://docs.vectalk.com.br/mcp so it can look up the routes instead of guessing. You don’t register a card with Meta: each delivered message is deducted from your account’s prepaid balance. Start at apps.vectalk.com.br/register and follow the quickstart.

Frequently asked questions

Which Claude model should I use on WhatsApp?

As of November 24, 2026, Anthropic describes Claude Sonnet 5.5 (claude-sonnet-5-5) as the best combination of speed and intelligence, and it’s the example’s default. Keep the ID in an environment variable and check the models page before going to production.

Does Claude remember the conversation on its own?

No. The Messages API keeps no state: on every message you send that wa_id‘s history, read from your database.

Do I need Meta’s permission to use Claude on WhatsApp?

For your own company’s customer service, you use the official API as usual. If your product is a general-purpose AI assistant, read section 4.7 of the terms before launching.

Can Claude send the first message to a customer?

Not with generated text. Outside the 24-hour window, only an approved template, with variables coming from your system.


Official sources checked on November 24, 2026: Anthropic: models overview, Anthropic: Messages API, Anthropic: tool use, Anthropic: handle tool calls, Anthropic: pricing, Meta: send messages, Meta: typing indicators, Meta: pricing, Meta Terms for WhatsApp Business Platform, Vectalk: quickstart, Vectalk: authentication, Vectalk: webhooks, Law 13,709/2018 (LGPD).

Put your business on the official WhatsApp

Create your account, connect your number to the official API (you can keep the app with coexistence) and start serving customers and sending messages.