{"id":2231,"date":"2026-11-24T19:33:21","date_gmt":"2026-11-24T19:33:21","guid":{"rendered":"https:\/\/vectalk.com.br\/blog\/langchain-langgraph-whatsapp-agent\/"},"modified":"2026-11-24T19:33:26","modified_gmt":"2026-11-24T19:33:26","slug":"langchain-langgraph-whatsapp-agent","status":"publish","type":"post","link":"https:\/\/vectalk.com.br\/blog\/en\/langchain-langgraph-whatsapp-agent\/","title":{"rendered":"WhatsApp agent with LangChain and LangGraph on the official WhatsApp Business API"},"content":{"rendered":"\n<p><em>Updated on November 24, 2026<\/em><\/p>\n\n\n\n<p>To build a WhatsApp agent with LangChain and LangGraph, you create the agent with <code>create_agent<\/code>, store each conversation&#8217;s memory in a checkpointer using the customer&#8217;s number (<code>wa_id<\/code>) as the <code>thread_id<\/code>, and call the agent from a webhook that returns 200 to Meta right away. The model&#8217;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.<\/p>\n\n\n\n<p>The webhook basics in Python are covered in the <a href=\"https:\/\/vectalk.com.br\/blog\/en\/whatsapp-bot-python-fastapi\/\">WhatsApp bot with Python and FastAPI<\/a>, and the framework-free version is in <a href=\"https:\/\/vectalk.com.br\/blog\/en\/chatgpt-whatsapp-business-api\/\">ChatGPT on the official WhatsApp API<\/a>. This guide focuses on what LangChain solves: per-conversation state and tools.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">create_agent or create_react_agent?<\/h2>\n\n\n\n<p>Since version 1.0, the recommended way to build an agent is <code>create_agent<\/code> from the <code>langchain<\/code> package. The older <code>create_react_agent<\/code> in <code>langgraph.prebuilt<\/code> has been deprecated in its favor, according to the <a href=\"https:\/\/docs.langchain.com\/oss\/python\/migrate\/langgraph-v1\" target=\"_blank\" rel=\"noreferrer noopener\">LangGraph v1 migration guide<\/a>. In the switch, the <code>prompt<\/code> parameter was renamed to <code>system_prompt<\/code>.<\/p>\n\n\n\n<p>LangGraph is still part of the picture. The <a href=\"https:\/\/docs.langchain.com\/oss\/python\/releases\/langchain-v1\" target=\"_blank\" rel=\"noreferrer noopener\">LangChain 1.0 release notes<\/a> say <code>create_agent<\/code> is built on LangGraph, and LangGraph is what provides persistence: the checkpointer saves the graph state at each step, separated by <code>thread_id<\/code>. In practice:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Piece<\/th><th>Comes from<\/th><th>Role in the WhatsApp bot<\/th><\/tr><\/thead><tbody><tr><td><code>create_agent<\/code><\/td><td><code>langchain.agents<\/code><\/td><td>The agent loop: model, tools, system prompt<\/td><\/tr><tr><td><code>@tool<\/code> and <code>ToolRuntime<\/code><\/td><td><code>langchain.tools<\/code><\/td><td>Functions the model can call, with access to the conversation context<\/td><\/tr><tr><td><code>InMemorySaver<\/code><\/td><td><code>langgraph.checkpoint.memory<\/code><\/td><td>Per-conversation memory in RAM, for development<\/td><\/tr><tr><td><code>PostgresSaver<\/code><\/td><td><code>langgraph.checkpoint.postgres<\/code><\/td><td>Per-conversation memory in PostgreSQL, for production<\/td><\/tr><tr><td><code>thread_id<\/code><\/td><td><code>config[\"configurable\"]<\/code><\/td><td>The conversation key; here, the customer&#8217;s <code>wa_id<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Installation<\/h2>\n\n\n\n<p>The <a href=\"https:\/\/docs.langchain.com\/oss\/python\/langchain\/install\" target=\"_blank\" rel=\"noreferrer noopener\">installation page<\/a> requires Python 3.10 or newer. Install LangChain, the package for your model provider and the web server:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"language-bash\">pip install -U langchain langchain-openai fastapi uvicorn httpx\n# or langchain-anthropic, depending on the provider\n# for production, Postgres persistence:\npip install -U langgraph-checkpoint-postgres \"psycopg[binary]\"<\/code><\/pre>\n\n\n\n<p>The model is passed as a <code>provider:model<\/code> string. In the code it comes from the <code>LLM_MODEL<\/code> environment variable, so you can switch models without touching the code. Use a model name listed on your provider&#8217;s models page.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Per-conversation state: thread_id is the wa_id<\/h2>\n\n\n\n<p>The agent doesn&#8217;t remember anything on its own. The checkpointer does, and the <a href=\"https:\/\/docs.langchain.com\/oss\/python\/langchain\/short-term-memory\" target=\"_blank\" rel=\"noreferrer noopener\">short-term memory docs<\/a> are explicit: without a checkpointer, the <code>thread_id<\/code> doesn&#8217;t persist. Every call passes the <code>thread_id<\/code> in <code>config[\"configurable\"]<\/code>. On WhatsApp, the natural choice is the <code>wa_id<\/code>, the customer&#8217;s number that arrives in the <code>from<\/code> field of the webhook message. As a result:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>each customer has their own history, with no mixed-up conversations;<\/li>\n\n\n<li>the new message is just the customer&#8217;s latest turn; the history is reloaded from the checkpointer;<\/li>\n\n\n<li>tool calls and their results are kept in the history too.<\/li>\n\n<\/ul>\n\n\n\n<p>Customers who adopt a WhatsApp username may arrive without the <code>from<\/code> field, with only the BSUID; in that case, use the BSUID as the key (the Python bot article shows both cases).<\/p>\n\n\n\n<p>The <a href=\"https:\/\/docs.langchain.com\/oss\/python\/langgraph\/persistence\" target=\"_blank\" rel=\"noreferrer noopener\">LangGraph persistence page<\/a> warns that <code>InMemorySaver<\/code> keeps everything in RAM and loses the checkpoints when the process restarts. In production, use <code>PostgresSaver<\/code> (example below).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Tools with @tool<\/h2>\n\n\n\n<p>A tool is a Python function with the <code>@tool<\/code> decorator. Its docstring becomes the description the model reads to decide when to call it.<\/p>\n\n\n\n<p>The most important security rule in a WhatsApp bot is <strong>don&#8217;t let the model decide whose data it reads<\/strong>. If the tool takes the customer&#8217;s phone number as an argument, someone can type &#8220;check the order for number 5521&#8230;&#8221; and the model will comply. The <a href=\"https:\/\/docs.langchain.com\/oss\/python\/langchain\/tools\" target=\"_blank\" rel=\"noreferrer noopener\">tools documentation<\/a> offers the right approach: a <code>runtime: ToolRuntime[Context]<\/code> parameter, hidden from the model, that delivers the context your code passed into the call. The <code>wa_id<\/code> comes from there, not from the customer&#8217;s text.<\/p>\n\n\n\n<p>See <code>get_order_status<\/code> in the full code below: it only returns the order if it belongs to the number in the conversation.<\/p>\n\n\n\n<p>Tools that change something (cancel, reschedule, refund) should require explicit confirmation from the customer before running; the guide to an <a href=\"https:\/\/vectalk.com.br\/blog\/en\/whatsapp-ai-agent-function-calling\/\">AI agent with tools<\/a> goes deeper into that design.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The full code<\/h2>\n\n\n\n<p>The example below is an <code>app.py<\/code> file with FastAPI. It receives the webhook, returns 200 immediately, processes the message in the background, calls the agent with the customer&#8217;s <code>thread_id<\/code> 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 <code>phone_number_id<\/code> in the body, as described in <a href=\"https:\/\/docs.vectalk.com.br\/authentication\">Vectalk authentication<\/a>. If you integrate directly with Meta, replace <code>SEND_URL<\/code> with <code>https:\/\/graph.facebook.com\/v27.0\/&lt;PHONE_NUMBER_ID&gt;\/messages<\/code> and use your Meta token.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"language-python\">import os\nimport threading\nimport time\nfrom dataclasses import dataclass\n\nimport httpx\nfrom fastapi import BackgroundTasks, FastAPI, HTTPException, Request\nfrom fastapi.responses import PlainTextResponse\nfrom langchain.agents import create_agent\nfrom langchain.tools import ToolRuntime, tool\nfrom langgraph.checkpoint.memory import InMemorySaver\n\nVERIFY_TOKEN = os.environ.get(\"VERIFY_TOKEN\", \"\")\nVECTALK_TOKEN = os.environ[\"VECTALK_TOKEN\"]\nLLM_MODEL = os.environ[\"LLM_MODEL\"]  # \"provider:model\" format\nSEND_URL = \"https:\/\/apis.vectalk.com.br\/api\/messages\"\nWINDOW = 24 * 60 * 60   # 24 hours, in seconds\nMARGIN = 5 * 60         # no free-form replies in the last 5 minutes\n\nhttp = httpx.Client(timeout=15)\nlast_inbound: dict[str, float] = {}  # wa_id -&gt; timestamp of the customer's last message\nwith_human: set[str] = set()         # wa_ids taken over by an agent\nseen: set[str] = set()               # wamids already processed\nlocks: dict[str, threading.Lock] = {}\nlocks_guard = threading.Lock()\n\n\n@dataclass\nclass Context:\n    wa_id: str\n\n\nORDERS = {\n    \"48213\": {\"wa_id\": \"5511999999999\", \"status\": \"out for delivery today\"},\n    \"48190\": {\"wa_id\": \"5521988888888\", \"status\": \"waiting for PIX payment\"},\n}\n\n\n@tool\ndef get_order_status(order_number: str, runtime: ToolRuntime[Context]) -&gt; str:\n    \"\"\"Look up an order's status by its number. Use it whenever the customer asks about an order.\"\"\"\n    order = ORDERS.get(order_number.strip())\n    if order is None or order[\"wa_id\"] != runtime.context.wa_id:\n        return \"No order with that number for this customer.\"\n    return f\"Order {order_number}: {order['status']}.\"\n\n\n@tool\ndef transfer_to_human(reason: str, runtime: ToolRuntime[Context]) -&gt; str:\n    \"\"\"Hand the conversation over to a human agent. Use it when the customer asks,\n    for complaints, or when you don't have the answer.\"\"\"\n    with_human.add(runtime.context.wa_id)\n    # here: open a ticket in your support system with the reason\n    return \"Transfer done. Tell the customer an agent will continue here.\"\n\n\nSYSTEM_PROMPT = (\n    \"You are the customer service assistant for Example Store on WhatsApp. \"\n    \"Only answer about the store's orders, deliveries and returns, \"\n    \"in short sentences. Use the tools for order data \"\n    \"and never make up a status. If the customer asks for a person or the topic \"\n    \"is out of scope, use transfer_to_human.\"\n)\n\n\ndef build_agent(checkpointer):\n    return create_agent(\n        model=LLM_MODEL,\n        tools=[get_order_status, transfer_to_human],\n        system_prompt=SYSTEM_PROMPT,\n        context_schema=Context,\n        checkpointer=checkpointer,\n    )\n\n\nagent = build_agent(InMemorySaver())\n\n\nclass WindowClosed(Exception):\n    pass\n\n\ndef window_open(wa_id: str) -&gt; bool:\n    last = last_inbound.get(wa_id)\n    return last is not None and time.time() - last &lt; WINDOW - MARGIN\n\n\ndef send(payload: dict) -&gt; dict:\n    r = http.post(\n        SEND_URL,\n        headers={\"Authorization\": f\"Bearer {VECTALK_TOKEN}\"},\n        json={\"messaging_product\": \"whatsapp\", **payload},\n    )\n    r.raise_for_status()\n    return r.json()\n\n\ndef send_text(wa_id: str, text: str) -&gt; dict:\n    if not window_open(wa_id):\n        raise WindowClosed(wa_id)\n    return send({\"to\": wa_id, \"type\": \"text\", \"text\": {\"body\": text[:4096]}})\n\n\ndef send_template(wa_id: str, name: str, params: list[str], language: str = \"en_US\") -&gt; dict:\n    components = []\n    if params:\n        components.append({\n            \"type\": \"body\",\n            \"parameters\": [{\"type\": \"text\", \"text\": p} for p in params],\n        })\n    return send({\n        \"to\": wa_id,\n        \"type\": \"template\",\n        \"template\": {\"name\": name, \"language\": {\"code\": language}, \"components\": components},\n    })\n\n\ndef notify(wa_id: str, text: str, template: str, params: list[str]) -&gt; dict:\n    \"\"\"Business-initiated message: free-form text if the window is open, template if not.\"\"\"\n    if window_open(wa_id):\n        return send_text(wa_id, text)\n    return send_template(wa_id, template, params)\n\n\ndef final_text(result: dict) -&gt; str:\n    content = result[\"messages\"][-1].content\n    if isinstance(content, str):\n        return content\n    return \"\".join(b.get(\"text\", \"\") for b in content if isinstance(b, dict))\n\n\ndef lock_for(wa_id: str) -&gt; threading.Lock:\n    with locks_guard:\n        return locks.setdefault(wa_id, threading.Lock())\n\n\ndef reply(wa_id: str, msg: dict) -&gt; None:\n    if wa_id in with_human:\n        return  # a human took over; the bot stays quiet\n    if msg.get(\"type\") != \"text\":\n        send_text(wa_id, \"For now I can only read text. Could you type your question?\")\n        return\n    result = agent.invoke(\n        {\"messages\": [{\"role\": \"user\", \"content\": msg[\"text\"][\"body\"]}]},\n        config={\"configurable\": {\"thread_id\": wa_id}},\n        context=Context(wa_id=wa_id),\n    )\n    try:\n        send_text(wa_id, final_text(result))\n    except WindowClosed:\n        pass  # the model was slow and the window closed: templates only from now on\n\n\ndef process(payload: dict) -&gt; None:\n    for entry in payload.get(\"entry\", []):\n        for change in entry.get(\"changes\", []):\n            for msg in change.get(\"value\", {}).get(\"messages\", []):\n                if msg[\"id\"] in seen:\n                    continue  # the same event may be delivered again\n                seen.add(msg[\"id\"])\n                wa_id = msg.get(\"from\")\n                if not wa_id:\n                    continue\n                last_inbound[wa_id] = float(msg.get(\"timestamp\", time.time()))\n                with lock_for(wa_id):\n                    reply(wa_id, msg)\n\n\napp = FastAPI()\n\n\n@app.get(\"\/webhook\")\ndef verify(request: Request):\n    q = request.query_params\n    if q.get(\"hub.mode\") == \"subscribe\" and q.get(\"hub.verify_token\") == VERIFY_TOKEN:\n        return PlainTextResponse(q.get(\"hub.challenge\", \"\"))\n    raise HTTPException(status_code=403)\n\n\n@app.post(\"\/webhook\")\nasync def receive(request: Request, background: BackgroundTasks):\n    payload = await request.json()\n    background.add_task(process, payload)\n    return {\"ok\": True}<\/code><\/pre>\n\n\n\n<p>To run it: <code>uvicorn app:app --port 8000<\/code>, with <code>VECTALK_TOKEN<\/code> and <code>LLM_MODEL<\/code> set in the environment.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What each part does<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Fast webhook.<\/strong> <code>POST \/webhook<\/code> only reads the JSON, schedules <code>process<\/code> 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 <a href=\"https:\/\/docs.vectalk.com.br\/concepts\/webhooks\">webhooks documentation<\/a>. <code>GET \/webhook<\/code> is only for Meta&#8217;s verification, if you receive events directly from Meta.<\/li>\n\n\n<li><strong>Deduplication.<\/strong> The <code>seen<\/code> set stores the <code>id<\/code> (wamid) of each processed message, so a redelivery doesn&#8217;t double the reply and the model cost.<\/li>\n\n\n<li><strong>One turn at a time per customer.<\/strong> WhatsApp users send three messages in a row. Without the per-<code>wa_id<\/code> lock, three runs would hit the same <code>thread_id<\/code> at once and scramble the history. The lock queues messages from the same customer; different customers still run in parallel.<\/li>\n\n\n<li><strong>Context outside the prompt.<\/strong> <code>context=Context(wa_id=wa_id)<\/code> is what the tools read through <code>runtime.context<\/code>. The model never sees or changes that value.<\/li>\n\n\n<li><strong>Final text.<\/strong> Some providers return message content as a list of blocks instead of a string. <code>final_text<\/code> handles both. The 4,096-character cut follows the body limit for <a href=\"https:\/\/developers.facebook.com\/documentation\/business-messaging\/whatsapp\/messages\/text-messages\" target=\"_blank\" rel=\"noreferrer noopener\">text messages<\/a>.<\/li>\n\n<\/ul>\n\n\n\n<p>If your webhook receives events directly from Meta, validate the <code>X-Hub-Signature-256<\/code> signature before processing; see <a href=\"https:\/\/vectalk.com.br\/blog\/en\/whatsapp-webhook-signature-validation\/\">how to validate the webhook signature<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The 24-hour window in code<\/h2>\n\n\n\n<p>The <a href=\"https:\/\/developers.facebook.com\/documentation\/business-messaging\/whatsapp\/messages\/send-messages\" target=\"_blank\" rel=\"noreferrer noopener\">send messages documentation<\/a> 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:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Recording inbound messages.<\/strong> On every incoming message, <code>last_inbound[wa_id]<\/code> gets the webhook <code>timestamp<\/code>. If your system also receives calls through the API, update the same record.<\/li>\n\n\n<li><strong>Checking at send time, not at arrival.<\/strong> <code>send_text<\/code> 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.<\/li>\n\n\n<li><strong>Business-initiated messages.<\/strong> When your system wants to reach out (order shipped, reminder, ticket follow-up), use <code>notify<\/code>: free-form text if the window is open, a template if not.<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"language-python\"># example: the ERP reports that the order is out for delivery\nnotify(\n    \"5511999999999\",\n    text=\"Your order 48213 is out for delivery today.\",\n    template=\"order_out_for_delivery\",\n    params=[\"48213\"],\n)<\/code><\/pre>\n\n\n\n<p>When the customer replies to the template, the window opens again and their next message lands in the same <code>thread_id<\/code>. 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 <a href=\"https:\/\/vectalk.com.br\/blog\/en\/send-whatsapp-template-message-api\/\">how to send a template through the API<\/a>, and the window rules in <a href=\"https:\/\/vectalk.com.br\/blog\/en\/whatsapp-24-hour-customer-service-window\/\">the WhatsApp 24-hour customer service window<\/a>.<\/p>\n\n\n\n<p>Cost for recipients in Brazil: the agent&#8217;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 <a href=\"https:\/\/vectalk.com.br\/blog\/en\/whatsapp-ai-chatbot-cost-per-conversation\/\">how much an AI chatbot costs per conversation<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Production: Postgres and long conversations<\/h2>\n\n\n\n<p>With <code>PostgresSaver<\/code>, conversations survive restarts. The documented pattern is to open the checkpointer with <code>from_conn_string<\/code> and call <code>setup()<\/code> on the first run. In FastAPI this fits in the <code>lifespan<\/code> (it replaces the <code>agent = build_agent(InMemorySaver())<\/code> and <code>app = FastAPI()<\/code> lines in the example):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"language-python\">from contextlib import asynccontextmanager\n\nfrom langgraph.checkpoint.postgres import PostgresSaver\n\nDB_URI = os.environ[\"DATABASE_URL\"]\n\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    global agent\n    with PostgresSaver.from_conn_string(DB_URI) as checkpointer:\n        checkpointer.setup()  # creates the tables on the first run\n        agent = build_agent(checkpointer)\n        yield\n\n\napp = FastAPI(lifespan=lifespan)<\/code><\/pre>\n\n\n\n<p>Within the same <code>thread_id<\/code>, the history keeps growing until it exceeds the model&#8217;s context window. The short-term memory docs list three options: trim old messages, delete them from state, or summarize them. The simplest is <code>SummarizationMiddleware<\/code> (from <code>langchain.agents.middleware<\/code>), which replaces old messages with a summary. Just add <code>middleware=[SummarizationMiddleware(model=LLM_MODEL, trigger=(\"tokens\", 4000), keep=(\"messages\", 20))]<\/code> to the <code>create_agent<\/code> call in <code>build_agent<\/code>.<\/p>\n\n\n\n<p>What else production needs:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Shared state.<\/strong> <code>last_inbound<\/code>, <code>with_human<\/code> and <code>seen<\/code> live in memory. In production, move them to your database or Redis, together with the per-customer lock.<\/li>\n\n\n<li><strong>A queue with retries.<\/strong> <code>BackgroundTasks<\/code> runs in the same process; if it crashes, the message is lost. A persistent queue fixes that.<\/li>\n\n\n<li><strong>Other message types.<\/strong> Voice notes are very common in Brazil; the guide to <a href=\"https:\/\/vectalk.com.br\/blog\/en\/transcribe-whatsapp-voice-messages-api\/\">transcribing voice messages with AI<\/a> shows how to turn audio into text before calling the agent.<\/li>\n\n\n<li><strong>Handing back to the bot.<\/strong> The example never removes a customer from <code>with_human<\/code>. The full <a href=\"https:\/\/vectalk.com.br\/blog\/en\/whatsapp-chatbot-human-handoff\/\">human handoff<\/a> flow covers triggers, what to pass to the agent and how to give the conversation back.<\/li>\n\n\n<li><strong>Privacy (LGPD).<\/strong> The checkpointer history is personal data under Brazil&#8217;s data protection law (LGPD) and similar laws elsewhere. Set a retention period and delete old threads. This article is not legal advice.<\/li>\n\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What Meta allows: AI that serves your business<\/h2>\n\n\n\n<p>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&#8217;s own customers, with scope locked down in the <code>SYSTEM_PROMPT<\/code>, business tools and a clear path to a person (<code>transfer_to_human<\/code>). An &#8220;ask the AI anything&#8221; service on WhatsApp is a different case. The details, including the exception for Brazil, are in <a href=\"https:\/\/vectalk.com.br\/blog\/en\/whatsapp-api-ai-policy-2026\/\">Meta&#8217;s AI policy in 2026<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How to do it with Vectalk<\/h2>\n\n\n\n<p>Vectalk is a proxy for the <a href=\"https:\/\/vectalk.com.br\/blog\/en\/official-whatsapp-api\/\">official WhatsApp API<\/a>: the agent receives webhooks in Meta&#8217;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&#8217;s the <code>SEND_URL<\/code> constant and <code>VECTALK_TOKEN<\/code>.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Create your account at <a href=\"https:\/\/apps.vectalk.com.br\/register\">apps.vectalk.com.br\/register<\/a> and connect your number.<\/li>\n\n\n<li>Generate the instance token in the dashboard (with an organization token, include <code>phone_number_id<\/code> when sending).<\/li>\n\n\n<li>Register the agent&#8217;s URL with <code>POST https:\/\/apis.vectalk.com.br\/api\/webhooks<\/code>, passing <code>instance_id<\/code>, <code>url<\/code> and <code>name<\/code>. You can register more than one URL per instance, for example one for the agent and one for your support system.<\/li>\n\n\n<li>Create the templates <code>notify<\/code> will use outside the window; the dashboard includes a Template Library.<\/li>\n\n<\/ol>\n\n\n\n<p>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&#8217;t add a card at Meta: each delivered message is deducted from your account&#8217;s prepaid balance. The first steps are in the <a href=\"https:\/\/docs.vectalk.com.br\/quickstart\">quickstart<\/a>. To generate this code with an AI assistant from the documentation, see <a href=\"https:\/\/vectalk.com.br\/blog\/en\/integrate-whatsapp-api-with-ai\/\">how to integrate the WhatsApp API with AI<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Frequently asked questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Do I need to use LangGraph directly, or is create_agent enough?<\/h3>\n\n\n\n<p>For a support agent with tools and memory, <code>create_agent<\/code> is enough, and it already runs on LangGraph. Build your own graph with <code>StateGraph<\/code> when the flow has fixed steps the model must not skip, such as a qualification funnel with mandatory stages.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Why use the customer&#8217;s number as the thread_id?<\/h3>\n\n\n\n<p>Because it&#8217;s the stable key of the conversation on WhatsApp and it arrives with every webhook message. Each customer&#8217;s history stays isolated and can be resumed, even after the window closes and the customer replies to a template.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can the agent start the conversation?<\/h3>\n\n\n\n<p>Not with free-form text. Outside the 24-hour window, only approved templates can be sent. Use a function like <code>notify<\/code>, which picks text or template depending on the window.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I use the same agent with another model?<\/h3>\n\n\n\n<p>Yes. <code>create_agent<\/code> takes the model as a <code>provider:model<\/code> string; install the provider package and change the <code>LLM_MODEL<\/code> variable. There are dedicated guides for <a href=\"https:\/\/vectalk.com.br\/blog\/en\/claude-whatsapp-business-api\/\">Claude<\/a> and for the <a href=\"https:\/\/vectalk.com.br\/blog\/en\/whatsapp-mcp-server\/\">WhatsApp MCP server<\/a>, in case the agent needs to send messages as a tool.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>Official sources checked on November 24, 2026:<\/strong> <a href=\"https:\/\/docs.langchain.com\/oss\/python\/langchain\/agents\" target=\"_blank\" rel=\"noreferrer noopener\">LangChain: Agents<\/a>, <a href=\"https:\/\/docs.langchain.com\/oss\/python\/langchain\/tools\" target=\"_blank\" rel=\"noreferrer noopener\">LangChain: Tools<\/a>, <a href=\"https:\/\/docs.langchain.com\/oss\/python\/langchain\/short-term-memory\" target=\"_blank\" rel=\"noreferrer noopener\">LangChain: Short-term memory<\/a>, <a href=\"https:\/\/docs.langchain.com\/oss\/python\/langchain\/install\" target=\"_blank\" rel=\"noreferrer noopener\">LangChain: Install<\/a>, <a href=\"https:\/\/docs.langchain.com\/oss\/python\/langgraph\/persistence\" target=\"_blank\" rel=\"noreferrer noopener\">LangGraph: Persistence<\/a>, <a href=\"https:\/\/docs.langchain.com\/oss\/python\/migrate\/langgraph-v1\" target=\"_blank\" rel=\"noreferrer noopener\">LangGraph v1 migration guide<\/a>, <a href=\"https:\/\/docs.langchain.com\/oss\/python\/releases\/langchain-v1\" target=\"_blank\" rel=\"noreferrer noopener\">LangChain v1 release notes<\/a>, <a href=\"https:\/\/developers.facebook.com\/documentation\/business-messaging\/whatsapp\/messages\/send-messages\" target=\"_blank\" rel=\"noreferrer noopener\">Meta: Send messages<\/a>, <a href=\"https:\/\/developers.facebook.com\/documentation\/business-messaging\/whatsapp\/messages\/text-messages\" target=\"_blank\" rel=\"noreferrer noopener\">Meta: Text messages<\/a>, <a href=\"https:\/\/developers.facebook.com\/documentation\/business-messaging\/whatsapp\/pricing\" target=\"_blank\" rel=\"noreferrer noopener\">Meta: Pricing<\/a>, <a href=\"https:\/\/www.facebook.com\/legal\/Meta-Terms-for-WhatsApp-Business-Platform\" target=\"_blank\" rel=\"noreferrer noopener\">Meta Terms for WhatsApp Business Platform<\/a>, <a href=\"https:\/\/docs.vectalk.com.br\/concepts\/webhooks\">Vectalk: Webhooks<\/a>, <a href=\"https:\/\/docs.vectalk.com.br\/authentication\">Vectalk: Authentication<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python code to connect a LangChain\/LangGraph agent to the official WhatsApp Business API: per-customer memory with thread_id, tools, the 24-hour window and a FastAPI webhook.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_feature_clip_id":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[1],"tags":[],"class_list":["post-2231","post","type-post","status-publish","format-standard","hentry","category-blog"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>LangChain WhatsApp Agent with LangGraph | Vectalk<\/title>\n<meta name=\"description\" content=\"Build a LangChain WhatsApp agent with LangGraph: create_agent, thread_id per customer, @tool tools, the 24-hour window and a FastAPI webhook in Python.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/vectalk.com.br\/blog\/en\/langchain-langgraph-whatsapp-agent\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"LangChain WhatsApp Agent with LangGraph | Vectalk\" \/>\n<meta property=\"og:description\" content=\"Build a LangChain WhatsApp agent with LangGraph: create_agent, thread_id per customer, @tool tools, the 24-hour window and a FastAPI webhook in Python.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/vectalk.com.br\/blog\/en\/langchain-langgraph-whatsapp-agent\/\" \/>\n<meta property=\"og:site_name\" content=\"Blog Vectalk\" \/>\n<meta property=\"article:published_time\" content=\"2026-11-24T19:33:21+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-24T19:33:26+00:00\" \/>\n<meta name=\"author\" content=\"wanderleyfcunha\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"wanderleyfcunha\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"15 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/en\\\/langchain-langgraph-whatsapp-agent\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/en\\\/langchain-langgraph-whatsapp-agent\\\/\"},\"author\":{\"name\":\"wanderleyfcunha\",\"@id\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/#\\\/schema\\\/person\\\/ff36ecd9d8257856f227f8e5d639db2b\"},\"headline\":\"WhatsApp agent with LangChain and LangGraph on the official WhatsApp Business API\",\"datePublished\":\"2026-11-24T19:33:21+00:00\",\"dateModified\":\"2026-11-24T19:33:26+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/en\\\/langchain-langgraph-whatsapp-agent\\\/\"},\"wordCount\":1938,\"articleSection\":[\"Blog\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/en\\\/langchain-langgraph-whatsapp-agent\\\/\",\"url\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/en\\\/langchain-langgraph-whatsapp-agent\\\/\",\"name\":\"LangChain WhatsApp Agent with LangGraph | Vectalk\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/#website\"},\"datePublished\":\"2026-11-24T19:33:21+00:00\",\"dateModified\":\"2026-11-24T19:33:26+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/#\\\/schema\\\/person\\\/ff36ecd9d8257856f227f8e5d639db2b\"},\"description\":\"Build a LangChain WhatsApp agent with LangGraph: create_agent, thread_id per customer, @tool tools, the 24-hour window and a FastAPI webhook in Python.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/en\\\/langchain-langgraph-whatsapp-agent\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/en\\\/langchain-langgraph-whatsapp-agent\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/en\\\/langchain-langgraph-whatsapp-agent\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"WhatsApp agent with LangChain and LangGraph on the official WhatsApp Business API\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/\",\"name\":\"Blog Vectalk\",\"description\":\"\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/vectalk.com.br\\\/blog\\\/#\\\/schema\\\/person\\\/ff36ecd9d8257856f227f8e5d639db2b\",\"name\":\"wanderleyfcunha\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/21c37077f1731eb558973f27a7b647d55f72fde5200a843ac5f5345b247ea725?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/21c37077f1731eb558973f27a7b647d55f72fde5200a843ac5f5345b247ea725?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/21c37077f1731eb558973f27a7b647d55f72fde5200a843ac5f5345b247ea725?s=96&d=mm&r=g\",\"caption\":\"wanderleyfcunha\"},\"sameAs\":[\"https:\\\/\\\/vectalk.com.br\\\/blog\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"LangChain WhatsApp Agent with LangGraph | Vectalk","description":"Build a LangChain WhatsApp agent with LangGraph: create_agent, thread_id per customer, @tool tools, the 24-hour window and a FastAPI webhook in Python.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/vectalk.com.br\/blog\/en\/langchain-langgraph-whatsapp-agent\/","og_locale":"en_US","og_type":"article","og_title":"LangChain WhatsApp Agent with LangGraph | Vectalk","og_description":"Build a LangChain WhatsApp agent with LangGraph: create_agent, thread_id per customer, @tool tools, the 24-hour window and a FastAPI webhook in Python.","og_url":"https:\/\/vectalk.com.br\/blog\/en\/langchain-langgraph-whatsapp-agent\/","og_site_name":"Blog Vectalk","article_published_time":"2026-11-24T19:33:21+00:00","article_modified_time":"2026-11-24T19:33:26+00:00","author":"wanderleyfcunha","twitter_card":"summary_large_image","twitter_misc":{"Written by":"wanderleyfcunha","Est. reading time":"15 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/vectalk.com.br\/blog\/en\/langchain-langgraph-whatsapp-agent\/#article","isPartOf":{"@id":"https:\/\/vectalk.com.br\/blog\/en\/langchain-langgraph-whatsapp-agent\/"},"author":{"name":"wanderleyfcunha","@id":"https:\/\/vectalk.com.br\/blog\/#\/schema\/person\/ff36ecd9d8257856f227f8e5d639db2b"},"headline":"WhatsApp agent with LangChain and LangGraph on the official WhatsApp Business API","datePublished":"2026-11-24T19:33:21+00:00","dateModified":"2026-11-24T19:33:26+00:00","mainEntityOfPage":{"@id":"https:\/\/vectalk.com.br\/blog\/en\/langchain-langgraph-whatsapp-agent\/"},"wordCount":1938,"articleSection":["Blog"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/vectalk.com.br\/blog\/en\/langchain-langgraph-whatsapp-agent\/","url":"https:\/\/vectalk.com.br\/blog\/en\/langchain-langgraph-whatsapp-agent\/","name":"LangChain WhatsApp Agent with LangGraph | Vectalk","isPartOf":{"@id":"https:\/\/vectalk.com.br\/blog\/#website"},"datePublished":"2026-11-24T19:33:21+00:00","dateModified":"2026-11-24T19:33:26+00:00","author":{"@id":"https:\/\/vectalk.com.br\/blog\/#\/schema\/person\/ff36ecd9d8257856f227f8e5d639db2b"},"description":"Build a LangChain WhatsApp agent with LangGraph: create_agent, thread_id per customer, @tool tools, the 24-hour window and a FastAPI webhook in Python.","breadcrumb":{"@id":"https:\/\/vectalk.com.br\/blog\/en\/langchain-langgraph-whatsapp-agent\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/vectalk.com.br\/blog\/en\/langchain-langgraph-whatsapp-agent\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/vectalk.com.br\/blog\/en\/langchain-langgraph-whatsapp-agent\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/vectalk.com.br\/blog\/"},{"@type":"ListItem","position":2,"name":"WhatsApp agent with LangChain and LangGraph on the official WhatsApp Business API"}]},{"@type":"WebSite","@id":"https:\/\/vectalk.com.br\/blog\/#website","url":"https:\/\/vectalk.com.br\/blog\/","name":"Blog Vectalk","description":"","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/vectalk.com.br\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/vectalk.com.br\/blog\/#\/schema\/person\/ff36ecd9d8257856f227f8e5d639db2b","name":"wanderleyfcunha","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/21c37077f1731eb558973f27a7b647d55f72fde5200a843ac5f5345b247ea725?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/21c37077f1731eb558973f27a7b647d55f72fde5200a843ac5f5345b247ea725?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/21c37077f1731eb558973f27a7b647d55f72fde5200a843ac5f5345b247ea725?s=96&d=mm&r=g","caption":"wanderleyfcunha"},"sameAs":["https:\/\/vectalk.com.br\/blog"]}]}},"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/vectalk.com.br\/blog\/wp-json\/wp\/v2\/posts\/2231","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/vectalk.com.br\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/vectalk.com.br\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/vectalk.com.br\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/vectalk.com.br\/blog\/wp-json\/wp\/v2\/comments?post=2231"}],"version-history":[{"count":1,"href":"https:\/\/vectalk.com.br\/blog\/wp-json\/wp\/v2\/posts\/2231\/revisions"}],"predecessor-version":[{"id":2234,"href":"https:\/\/vectalk.com.br\/blog\/wp-json\/wp\/v2\/posts\/2231\/revisions\/2234"}],"wp:attachment":[{"href":"https:\/\/vectalk.com.br\/blog\/wp-json\/wp\/v2\/media?parent=2231"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/vectalk.com.br\/blog\/wp-json\/wp\/v2\/categories?post=2231"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/vectalk.com.br\/blog\/wp-json\/wp\/v2\/tags?post=2231"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}