← Blog

·

WhatsApp agent with LangChain and LangGraph on the official WhatsApp Business API

Updated on November 24, 2026

To build a WhatsApp agent with LangChain and LangGraph, you create the agent with create_agent, store each conversation’s memory in a checkpointer using the customer’s number (wa_id) as the thread_id, and call the agent from a webhook that returns 200 to Meta right away. The model’s answer goes out as free-form text only while the 24-hour customer service window is open; outside it, the code sends an approved template.

The webhook basics in Python are covered in the WhatsApp bot with Python and FastAPI, and the framework-free version is in ChatGPT on the official WhatsApp API. This guide focuses on what LangChain solves: per-conversation state and tools.

create_agent or create_react_agent?

Since version 1.0, the recommended way to build an agent is create_agent from the langchain package. The older create_react_agent in langgraph.prebuilt has been deprecated in its favor, according to the LangGraph v1 migration guide. In the switch, the prompt parameter was renamed to system_prompt.

LangGraph is still part of the picture. The LangChain 1.0 release notes say create_agent is built on LangGraph, and LangGraph is what provides persistence: the checkpointer saves the graph state at each step, separated by thread_id. In practice:

PieceComes fromRole in the WhatsApp bot
create_agentlangchain.agentsThe agent loop: model, tools, system prompt
@tool and ToolRuntimelangchain.toolsFunctions the model can call, with access to the conversation context
InMemorySaverlanggraph.checkpoint.memoryPer-conversation memory in RAM, for development
PostgresSaverlanggraph.checkpoint.postgresPer-conversation memory in PostgreSQL, for production
thread_idconfig["configurable"]The conversation key; here, the customer’s wa_id

Installation

The installation page requires Python 3.10 or newer. Install LangChain, the package for your model provider and the web server:

pip install -U langchain langchain-openai fastapi uvicorn httpx
# or langchain-anthropic, depending on the provider
# for production, Postgres persistence:
pip install -U langgraph-checkpoint-postgres "psycopg[binary]"

The model is passed as a provider:model string. In the code it comes from the LLM_MODEL environment variable, so you can switch models without touching the code. Use a model name listed on your provider’s models page.

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

Per-conversation state: thread_id is the wa_id

The agent doesn’t remember anything on its own. The checkpointer does, and the short-term memory docs are explicit: without a checkpointer, the thread_id doesn’t persist. Every call passes the thread_id in config["configurable"]. On WhatsApp, the natural choice is the wa_id, the customer’s number that arrives in the from field of the webhook message. As a result:

  • each customer has their own history, with no mixed-up conversations;
  • the new message is just the customer’s latest turn; the history is reloaded from the checkpointer;
  • tool calls and their results are kept in the history too.

Customers who adopt a WhatsApp username may arrive without the from field, with only the BSUID; in that case, use the BSUID as the key (the Python bot article shows both cases).

The LangGraph persistence page warns that InMemorySaver keeps everything in RAM and loses the checkpoints when the process restarts. In production, use PostgresSaver (example below).

Tools with @tool

A tool is a Python function with the @tool decorator. Its docstring becomes the description the model reads to decide when to call it.

The most important security rule in a WhatsApp bot is don’t let the model decide whose data it reads. If the tool takes the customer’s phone number as an argument, someone can type “check the order for number 5521…” and the model will comply. The tools documentation offers the right approach: a runtime: ToolRuntime[Context] parameter, hidden from the model, that delivers the context your code passed into the call. The wa_id comes from there, not from the customer’s text.

See get_order_status in the full code below: it only returns the order if it belongs to the number in the conversation.

Tools that change something (cancel, reschedule, refund) should require explicit confirmation from the customer before running; the guide to an AI agent with tools goes deeper into that design.

The full code

The example below is an app.py file with FastAPI. It receives the webhook, returns 200 immediately, processes the message in the background, calls the agent with the customer’s thread_id and sends the reply 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, as described in Vectalk authentication. If you integrate directly with Meta, replace SEND_URL with https://graph.facebook.com/v27.0/<PHONE_NUMBER_ID>/messages and use your Meta token.

import os
import threading
import time
from dataclasses import dataclass

import httpx
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request
from fastapi.responses import PlainTextResponse
from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langgraph.checkpoint.memory import InMemorySaver

VERIFY_TOKEN = os.environ.get("VERIFY_TOKEN", "")
VECTALK_TOKEN = os.environ["VECTALK_TOKEN"]
LLM_MODEL = os.environ["LLM_MODEL"]  # "provider:model" format
SEND_URL = "https://apis.vectalk.com.br/api/messages"
WINDOW = 24 * 60 * 60   # 24 hours, in seconds
MARGIN = 5 * 60         # no free-form replies in the last 5 minutes

http = httpx.Client(timeout=15)
last_inbound: dict[str, float] = {}  # wa_id -> timestamp of the customer's last message
with_human: set[str] = set()         # wa_ids taken over by an agent
seen: set[str] = set()               # wamids already processed
locks: dict[str, threading.Lock] = {}
locks_guard = threading.Lock()


@dataclass
class Context:
    wa_id: str


ORDERS = {
    "48213": {"wa_id": "5511999999999", "status": "out for delivery today"},
    "48190": {"wa_id": "5521988888888", "status": "waiting for PIX payment"},
}


@tool
def get_order_status(order_number: str, runtime: ToolRuntime[Context]) -> str:
    """Look up an order's status by its number. Use it whenever the customer asks about an order."""
    order = ORDERS.get(order_number.strip())
    if order is None or order["wa_id"] != runtime.context.wa_id:
        return "No order with that number for this customer."
    return f"Order {order_number}: {order['status']}."


@tool
def transfer_to_human(reason: str, runtime: ToolRuntime[Context]) -> str:
    """Hand the conversation over to a human agent. Use it when the customer asks,
    for complaints, or when you don't have the answer."""
    with_human.add(runtime.context.wa_id)
    # here: open a ticket in your support system with the reason
    return "Transfer done. Tell the customer an agent will continue here."


SYSTEM_PROMPT = (
    "You are the customer service assistant for Example Store on WhatsApp. "
    "Only answer about the store's orders, deliveries and returns, "
    "in short sentences. Use the tools for order data "
    "and never make up a status. If the customer asks for a person or the topic "
    "is out of scope, use transfer_to_human."
)


def build_agent(checkpointer):
    return create_agent(
        model=LLM_MODEL,
        tools=[get_order_status, transfer_to_human],
        system_prompt=SYSTEM_PROMPT,
        context_schema=Context,
        checkpointer=checkpointer,
    )


agent = build_agent(InMemorySaver())


class WindowClosed(Exception):
    pass


def window_open(wa_id: str) -> bool:
    last = last_inbound.get(wa_id)
    return last is not None and time.time() - last < WINDOW - MARGIN


def send(payload: dict) -> dict:
    r = http.post(
        SEND_URL,
        headers={"Authorization": f"Bearer {VECTALK_TOKEN}"},
        json={"messaging_product": "whatsapp", **payload},
    )
    r.raise_for_status()
    return r.json()


def send_text(wa_id: str, text: str) -> dict:
    if not window_open(wa_id):
        raise WindowClosed(wa_id)
    return send({"to": wa_id, "type": "text", "text": {"body": text[:4096]}})


def send_template(wa_id: str, name: str, params: list[str], language: str = "en_US") -> dict:
    components = []
    if params:
        components.append({
            "type": "body",
            "parameters": [{"type": "text", "text": p} for p in params],
        })
    return send({
        "to": wa_id,
        "type": "template",
        "template": {"name": name, "language": {"code": language}, "components": components},
    })


def notify(wa_id: str, text: str, template: str, params: list[str]) -> dict:
    """Business-initiated message: free-form text if the window is open, template if not."""
    if window_open(wa_id):
        return send_text(wa_id, text)
    return send_template(wa_id, template, params)


def final_text(result: dict) -> str:
    content = result["messages"][-1].content
    if isinstance(content, str):
        return content
    return "".join(b.get("text", "") for b in content if isinstance(b, dict))


def lock_for(wa_id: str) -> threading.Lock:
    with locks_guard:
        return locks.setdefault(wa_id, threading.Lock())


def reply(wa_id: str, msg: dict) -> None:
    if wa_id in with_human:
        return  # a human took over; the bot stays quiet
    if msg.get("type") != "text":
        send_text(wa_id, "For now I can only read text. Could you type your question?")
        return
    result = agent.invoke(
        {"messages": [{"role": "user", "content": msg["text"]["body"]}]},
        config={"configurable": {"thread_id": wa_id}},
        context=Context(wa_id=wa_id),
    )
    try:
        send_text(wa_id, final_text(result))
    except WindowClosed:
        pass  # the model was slow and the window closed: templates only from now on


def process(payload: dict) -> None:
    for entry in payload.get("entry", []):
        for change in entry.get("changes", []):
            for msg in change.get("value", {}).get("messages", []):
                if msg["id"] in seen:
                    continue  # the same event may be delivered again
                seen.add(msg["id"])
                wa_id = msg.get("from")
                if not wa_id:
                    continue
                last_inbound[wa_id] = float(msg.get("timestamp", time.time()))
                with lock_for(wa_id):
                    reply(wa_id, msg)


app = FastAPI()


@app.get("/webhook")
def verify(request: Request):
    q = request.query_params
    if q.get("hub.mode") == "subscribe" and q.get("hub.verify_token") == VERIFY_TOKEN:
        return PlainTextResponse(q.get("hub.challenge", ""))
    raise HTTPException(status_code=403)


@app.post("/webhook")
async def receive(request: Request, background: BackgroundTasks):
    payload = await request.json()
    background.add_task(process, payload)
    return {"ok": True}

To run it: uvicorn app:app --port 8000, with VECTALK_TOKEN and LLM_MODEL set in the environment.

What each part does

  • Fast webhook. POST /webhook only reads the JSON, schedules process and returns 200. The agent can take several seconds; on Vectalk, the endpoint must return HTTP 200 in under 20 seconds or the event is resent, according to the webhooks documentation. GET /webhook is only for Meta’s verification, if you receive events directly from Meta.
  • Deduplication. The seen set stores the id (wamid) of each processed message, so a redelivery doesn’t double the reply and the model cost.
  • One turn at a time per customer. WhatsApp users send three messages in a row. Without the per-wa_id lock, three runs would hit the same thread_id at once and scramble the history. The lock queues messages from the same customer; different customers still run in parallel.
  • Context outside the prompt. context=Context(wa_id=wa_id) is what the tools read through runtime.context. The model never sees or changes that value.
  • Final text. Some providers return message content as a list of blocks instead of a string. final_text handles both. The 4,096-character cut follows the body limit for text messages.

If your webhook receives events directly from Meta, validate the X-Hub-Signature-256 signature before processing; see how to validate the webhook signature.

The 24-hour window in code

The send messages documentation sets the rule: when a customer messages or calls the business, a 24-hour customer service window opens; each new message or call resets the timer; once the window closes, only approved templates can be sent. LangChain knows nothing about this. The rule has to live in your code, and the example applies it in three places:

  1. Recording inbound messages. On every incoming message, last_inbound[wa_id] gets the webhook timestamp. If your system also receives calls through the API, update the same record.
  2. Checking at send time, not at arrival. send_text checks the window right before sending. If the model stalled, the queue lagged or a human took a while to hand the conversation back, the window may have closed in between. The 5-minute margin avoids sending right at the edge.
  3. Business-initiated messages. When your system wants to reach out (order shipped, reminder, ticket follow-up), use notify: free-form text if the window is open, a template if not.
# example: the ERP reports that the order is out for delivery
notify(
    "5511999999999",
    text="Your order 48213 is out for delivery today.",
    template="order_out_for_delivery",
    params=["48213"],
)

When the customer replies to the template, the window opens again and their next message lands in the same thread_id. The agent picks up the conversation with the earlier history, because the checkpointer kept it. Templates are created and approved beforehand; the full send format is in how to send a template through the API, and the window rules in the WhatsApp 24-hour customer service window.

Cost for recipients in Brazil: the agent’s replies inside the window are service messages, with an allowance of 1,000 per number per month and R$ 0.0350 (Brazilian reais) from the 1,001st on. Templates are charged by category, inside or outside the window: R$ 0.3217 for marketing and R$ 0.0350 for utility, and since October 1, 2026 that includes utility templates sent inside the window. Adding model tokens on top of these rates is covered in how much an AI chatbot costs per conversation.

Production: Postgres and long conversations

With PostgresSaver, conversations survive restarts. The documented pattern is to open the checkpointer with from_conn_string and call setup() on the first run. In FastAPI this fits in the lifespan (it replaces the agent = build_agent(InMemorySaver()) and app = FastAPI() lines in the example):

from contextlib import asynccontextmanager

from langgraph.checkpoint.postgres import PostgresSaver

DB_URI = os.environ["DATABASE_URL"]


@asynccontextmanager
async def lifespan(app: FastAPI):
    global agent
    with PostgresSaver.from_conn_string(DB_URI) as checkpointer:
        checkpointer.setup()  # creates the tables on the first run
        agent = build_agent(checkpointer)
        yield


app = FastAPI(lifespan=lifespan)

Within the same thread_id, the history keeps growing until it exceeds the model’s context window. The short-term memory docs list three options: trim old messages, delete them from state, or summarize them. The simplest is SummarizationMiddleware (from langchain.agents.middleware), which replaces old messages with a summary. Just add middleware=[SummarizationMiddleware(model=LLM_MODEL, trigger=("tokens", 4000), keep=("messages", 20))] to the create_agent call in build_agent.

What else production needs:

  • Shared state. last_inbound, with_human and seen live in memory. In production, move them to your database or Redis, together with the per-customer lock.
  • A queue with retries. BackgroundTasks runs in the same process; if it crashes, the message is lost. A persistent queue fixes that.
  • Other message types. Voice notes are very common in Brazil; the guide to transcribing voice messages with AI shows how to turn audio into text before calling the agent.
  • Handing back to the bot. The example never removes a customer from with_human. The full human handoff flow covers triggers, what to pass to the agent and how to give the conversation back.
  • Privacy (LGPD). The checkpointer history is personal data under Brazil’s data protection law (LGPD) and similar laws elsewhere. Set a retention period and delete old threads. This article is not legal advice.

What Meta allows: AI that serves your business

Since January 15, 2026, section 4.7 of the Meta Terms for WhatsApp Business Platform prohibits AI Providers from using the platform when general-purpose AI (generic assistants, LLMs, generative AI) is the primary functionality of the service. The agent in this article is on the allowed side: it serves the business’s own customers, with scope locked down in the SYSTEM_PROMPT, business tools and a clear path to a person (transfer_to_human). An “ask the AI anything” service on WhatsApp is a different case. The details, including the exception for Brazil, are in Meta’s AI policy in 2026.

How to do it with Vectalk

Vectalk is a proxy for the official WhatsApp API: the agent receives webhooks in Meta’s format and sends with the same JSON as the Cloud API, changing only the base URL and the token. In the code above, that’s the SEND_URL constant and VECTALK_TOKEN.

  1. Create your account at apps.vectalk.com.br/register and connect your number.
  2. Generate the instance token in the dashboard (with an organization token, include phone_number_id when sending).
  3. Register the agent’s URL with POST https://apis.vectalk.com.br/api/webhooks, passing instance_id, url and name. You can register more than one URL per instance, for example one for the agent and one for your support system.
  4. Create the templates notify will use outside the window; the dashboard includes a Template Library.

Vectalk has no built-in AI, support inbox or bulk messaging: the LangChain agent runs on your server, and human support happens in your own system or in the WhatsApp Business app via coexistence. You don’t add a card at Meta: each delivered message is deducted from your account’s prepaid balance. The first steps are in the quickstart. To generate this code with an AI assistant from the documentation, see how to integrate the WhatsApp API with AI.

Frequently asked questions

Do I need to use LangGraph directly, or is create_agent enough?

For a support agent with tools and memory, create_agent is enough, and it already runs on LangGraph. Build your own graph with StateGraph when the flow has fixed steps the model must not skip, such as a qualification funnel with mandatory stages.

Why use the customer’s number as the thread_id?

Because it’s the stable key of the conversation on WhatsApp and it arrives with every webhook message. Each customer’s history stays isolated and can be resumed, even after the window closes and the customer replies to a template.

Can the agent start the conversation?

Not with free-form text. Outside the 24-hour window, only approved templates can be sent. Use a function like notify, which picks text or template depending on the window.

Can I use the same agent with another model?

Yes. create_agent takes the model as a provider:model string; install the provider package and change the LLM_MODEL variable. There are dedicated guides for Claude and for the WhatsApp MCP server, in case the agent needs to send messages as a tool.


Official sources checked on November 24, 2026: LangChain: Agents, LangChain: Tools, LangChain: Short-term memory, LangChain: Install, LangGraph: Persistence, LangGraph v1 migration guide, LangChain v1 release notes, Meta: Send messages, Meta: Text messages, Meta: Pricing, Meta Terms for WhatsApp Business Platform, Vectalk: Webhooks, Vectalk: Authentication.

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.