Building this with a coding agent? Copy this prompt into it
Help me build the WhatsApp AI agent from this tutorial.
First read all of it:
https://www.neuronautasrd.com/en/blog/whatsapp-ai-agent-python-kapso-langgraph-step-by-step
Then work through it with me, one step at a time, in the current folder:
- Use the tutorial's code as written. If a step fails, check its Troubleshooting
section before changing code.
- After each step, run the check the tutorial gives and show me its output next to
the expected output.
- Some steps need me: the Kapso dashboard (sandbox number, API key, webhook secret)
and sending WhatsApp messages from my phone. Tell me exactly what to do, then
wait.
- Never print, log or commit what's in .env. Ask me to paste the keys into .env
myself.
If you need more than the tutorial:
- kapso-python: https://raw.githubusercontent.com/Joselier3/kapso-python/main/README.md
- Kapso docs: https://docs.kapso.ai/llms.txt
- LangGraph docs: https://docs.langchain.com/llms.txt
In this tutorial we'll build a WhatsApp sales assistant for a small electronics shop. A customer writes "Hi, I'm looking for a wireless mouse under $50 that works with a Mac", and the bot looks through the real inventory, checks stock, recommends something that exists at a price that's true, and takes the order once the customer confirms. Fixed questions like opening hours or the address get instant answers from buttons, without calling the model.
We'll build it in the order you'd debug it: first a bot that only accepts what Kapso signed, then one that replies, then the agent, and only at the end the two together. Each part runs and is checked before the next one starts.
- Time: About 45 minutes
-
Level: You write Python and know what
async/awaitdo. You haven't used Kapso or LangGraph before. - Finished code: github.com/Joselier3/kapso-langgraph-starter, with offline tests
By the end of this tutorial, you'll be able to:
- Receive a WhatsApp message from Kapso, verify its signature, and reject one Kapso didn't sign
- Answer inside Kapso's 10-second window and ignore retried deliveries
- Give each WhatsApp conversation its own LangGraph agent, with tools the model can call
The stack:
- Kapso, a platform on top of WhatsApp's official Cloud API, for the WhatsApp number and webhooks.
- kapso-python, a Python SDK I built for Kapso.
- LangGraph for the agent, with an OpenAI model.
- FastAPI to receive the webhooks.
What you need
| You need | Check it with |
|---|---|
| Python 3.11 or newer | python3 --version |
| uv | uv --version |
| ngrok, signed in to a free account | ngrok version |
| A free Kapso account | |
| An OpenAI API key | |
| WhatsApp on your phone |
It helps to know:
-
async/awaitin Python (the asyncio docs) - What a FastAPI route looks like (FastAPI's first steps)
1. Set up a test number and the project
- In your Kapso project, go to WhatsApp β Sandbox and click Add Test Number. Enter your own WhatsApp number, click Create, then click Open WhatsApp and send the 6-character activation code to the sandbox number.
- Create a project API key in the Kapso dashboard. One key works for every Kapso API.
- Create the project and install the packages:
mkdir shop-bot && cd shop-bot
uv init --bare
uv add kapso-python "fastapi[standard]" python-dotenv langchain langgraph langchain-openai
- Put your variables in a
.envfile in the same folder:
KAPSO_API_KEY=your-project-api-key
KAPSO_WEBHOOK_SECRET=placeholder-until-step-3
OPENAI_API_KEY=your-openai-key
Kapso generates the webhook secret when you create the webhook in step 3. Leave the placeholder for now.
2. Check Kapso's signature
Kapso signs every webhook it sends with an HMAC of the request body and your webhook's secret. The first version of the bot does only one thing: refuse any request Kapso didn't sign.
Create bot.py:
import os
from dotenv import load_dotenv
load_dotenv() # copies .env into os.environ
from fastapi import FastAPI, HTTPException, Request
import kapso
WEBHOOK_SECRET = os.environ["KAPSO_WEBHOOK_SECRET"]
app = FastAPI()
@app.post("/webhooks/kapso")
async def webhook(request: Request):
raw = await request.body() # the exact bytes Kapso signed
if not kapso.verify(raw, request.headers.get("x-webhook-signature"), WEBHOOK_SECRET):
raise HTTPException(status_code=401, detail="invalid signature")
return {"ok": True}
Notice that the route reads await request.body(), not request.json(). The signature covers the exact bytes Kapso sent. If you parse the JSON and dump it again, the bytes change and the signature no longer matches. kapso.verify() recomputes the HMAC and compares it in constant time, so the comparison doesn't leak how much of a forged signature was right. A missing or malformed header returns False instead of raising.
Start the bot:
uv run fastapi dev bot.py
The last line it prints should be:
INFO: Application startup complete.
In a second terminal, send it a request nobody signed:
curl -s -X POST localhost:8000/webhooks/kapso -d '{}'
Expected output:
{"detail":"invalid signature"}
The bot's terminal logs the refusal (your port number will differ):
INFO: 127.0.0.1:35082 - "POST /webhooks/kapso HTTP/1.1" 401 Unauthorized
Leave the bot running. If it stopped with a KeyError instead, see Troubleshooting.
3. Point Kapso at your bot
Kapso needs a public URL to send messages to. In the second terminal:
ngrok http 8000
Copy the https://β¦ngrokβ¦ URL it prints. Then register a webhook on the sandbox number (Kapso's webhook docs cover the details):
- In the Kapso sidebar, under Integrate, open Webhooks and stay on the WhatsApp tab. Expand Sandbox WhatsApp and click Add webhook.
- Keep Kapso events selected. That's the format kapso-python reads. (Raw Meta webhook forwards Meta's payload as-is.)
- In Endpoint URL, paste
https://<your-ngrok-url>/webhooks/kapso. Under Events, check Message received (whatsapp.message.received). Leave Debounce rapid messages into batches off for now. - Click Create webhook.
The new webhook shows up under Sandbox WhatsApp with a Secret field. Copy that value into .env as KAPSO_WEBHOOK_SECRET. fastapi dev restarts by itself when a .py file changes, but not when .env does, so stop the bot with Ctrl+C and start it again:
uv run fastapi dev bot.py
Checkpoint: Kapso reaches your bot
From your phone, send "hi" to the sandbox number. The bot's terminal should show:
INFO: 127.0.0.1:35090 - "POST /webhooks/kapso HTTP/1.1" 200 OK
Nothing arrives on your phone yet. The bot accepts the message and doesn't answer, which is the next step.
You now have a public endpoint that only accepts what Kapso signed. If you see 401 Unauthorized instead, or no line at all, see Troubleshooting.
4. Reply with a menu
Now the bot reads the message and answers it, always with the same menu for now. Replace bot.py with:
import os
from contextlib import asynccontextmanager
from dotenv import load_dotenv
load_dotenv() # copies .env into os.environ
from fastapi import FastAPI, HTTPException, Request
import kapso
from kapso import Button, InboundMessage, KapsoClient
API_KEY = os.environ["KAPSO_API_KEY"]
WEBHOOK_SECRET = os.environ["KAPSO_WEBHOOK_SECRET"]
MENU = [
Button(id="hours", title="Opening hours"),
Button(id="location", title="Where are you?"),
Button(id="human", title="Talk to a person"),
]
@asynccontextmanager
async def lifespan(app: FastAPI):
async with KapsoClient(API_KEY) as client: # one connection pool for the whole app
app.state.kapso = client
yield
app = FastAPI(lifespan=lifespan)
@app.post("/webhooks/kapso")
async def webhook(request: Request):
raw = await request.body() # the exact bytes Kapso signed
if not kapso.verify(raw, request.headers.get("x-webhook-signature"), WEBHOOK_SECRET):
raise HTTPException(status_code=401, detail="invalid signature")
for msg in kapso.parse(raw, request.headers.get("x-webhook-event")):
await answer(request.app.state.kapso, msg)
return {"ok": True}
async def answer(client: KapsoClient, msg: InboundMessage) -> None:
await client.messages.send_buttons(msg.phone_number_id, msg.sender, "Hi! π How can I help?", MENU)
Three new pieces, all from kapso-python:
-
kapso.parse()turns a delivery into a list ofInboundMessage. It takes thex-webhook-eventheader because a single delivery doesn't say in its body which event it is. For any event other than a received message (delivery and read statuses, for example), it returns an empty list, and the route still answers 200, which is what Kapso expects. It's a list because Kapso can buffer several messages into one delivery.parse()flattens that, and it also leaves out your own outgoing messages echoed back and imported history. -
Each
InboundMessagecarries what you need to answer.msg.phone_number_idis the business number that received the message, and you reply from the same one.msg.senderis who wrote. Some WhatsApp users now hide their phone number behind a username, so a message can come with only a business-scoped user ID (BSUID).msg.senderholds whichever one the user has, and the SDK puts it in the right field when you send. -
KapsoClientsends. Opening it withasync within FastAPI'slifespangives the whole app one connection pool, opened at startup and closed at shutdown.send_buttonssends WhatsApp's reply buttons.Buttonchecks WhatsApp's limits in your code: a title over 20 characters raises aValueErrorbefore any request is made.
fastapi dev reloads when you save. Send "hi" again from your phone: the menu arrives with three buttons. Tap one, and you get the same menu again, because the bot doesn't read which button you tapped. That comes next.
5. Answer the buttons
A tapped button comes back as its own kind of message. In bot.py, import two more names from kapso and set up a logger:
import logging
from kapso import Button, InboundMessage, InteractiveReply, KapsoClient, KapsoError
log = logging.getLogger("bot")
Put import logging at the top with the other imports, replace the from kapso import β¦ line, and add log below WEBHOOK_SECRET. Then replace answer():
async def answer(client: KapsoClient, msg: InboundMessage) -> None:
m = client.messages
try:
match msg.content:
case InteractiveReply(id="hours"):
await m.reply_text(msg, "We're open Monday to Saturday, 9am to 7pm.")
case InteractiveReply(id="location"):
await m.send_location(
msg.phone_number_id,
msg.sender,
18.4735,
-69.8840,
name="TechShop",
address="Calle El Conde 101, Santo Domingo",
)
case InteractiveReply(id="human"):
await m.reply_text(msg, "Got it! Someone from the team will write you here shortly.")
case _:
await m.send_buttons(msg.phone_number_id, msg.sender, "Hi! π How can I help?", MENU)
except KapsoError as e:
# status, code and request_id are enough to debug, and never contain the user's text
log.error("reply failed: status=%s code=%s request_id=%s", e.status_code, e.code, e.request_id)
msg.content is typed by what the user sent: Text, MediaMessage, Location, InteractiveReply and a few more. A tapped button is an InteractiveReply carrying the id you gave the Button in step 4, so Python's match can pick the answer. reply_text(msg, ...) is a shortcut that answers from msg.phone_number_id to msg.sender.
When Kapso or Meta refuses a request, the SDK raises KapsoError. Log its status_code, code and request_id. The error's message is the provider's own text, and it can quote what you tried to send, which in a real bot is your customer's data.
Checkpoint: the menu works
From your phone:
- Tap Opening hours. You get the hours.
- Tap Where are you? You get a location pin for TechShop.
- Tap Talk to a person. You get the "Got it!" message.
- Type anything. You get the menu.
Each of these answers comes from your code, with no model involved, so it's instant, free and always right. If a button still brings back the menu, check that answer() was replaced and that the terminal shows the reload.
6. Build the agent
The agent lives in its own file, agent.py, and knows nothing about WhatsApp. It's the loop from the LangGraph quickstart: the model reads the conversation, either asks for a tool or answers, and your code runs the tools it asks for until it answers.
import operator
from typing import Annotated, Literal
from langchain.chat_models import init_chat_model
from langchain.messages import AnyMessage, SystemMessage, ToolMessage
from langchain.tools import tool
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from typing_extensions import TypedDict
model = init_chat_model("openai:gpt-6-luna")
# A toy inventory. In production this is your database.
INVENTORY = {
"log-m240": {"name": "Logitech M240 Silent", "price": 32, "mac": True, "stock": 12},
"log-m185": {"name": "Logitech M185", "price": 20, "mac": False, "stock": 30},
"log-mxa3": {"name": "Logitech MX Anywhere 3", "price": 85, "mac": True, "stock": 5},
"key-k380": {"name": "Logitech K380 (keyboard)", "price": 40, "mac": True, "stock": 0},
}
@tool
def search_products(query: str, max_price: int = 0) -> str:
"""Search the shop's catalog.
Args:
query: what the customer is looking for, in free text (e.g. 'wireless mouse for mac')
max_price: price limit in US dollars (0 = no limit)
"""
results = []
for pid, p in INVENTORY.items():
if max_price and p["price"] > max_price:
continue
if "mac" in query.lower() and not p["mac"]:
continue
results.append(f"{pid}: {p['name']}, ${p['price']}, {'works with Mac' if p['mac'] else 'not for Mac'}")
return "\n".join(results) or "No results for that search."
@tool
def check_stock(product_id: str) -> str:
"""Check how many units of a product are in stock.
Args:
product_id: the product's id (e.g. 'log-m240')
"""
p = INVENTORY.get(product_id)
if not p:
return f"There is no product {product_id}."
return f"{p['name']}: {p['stock']} in stock." if p["stock"] else f"{p['name']}: OUT OF STOCK."
@tool
def create_order(product_id: str, quantity: int, address: str) -> str:
"""Create an order. Only call this once the customer confirmed the product, quantity and address.
Args:
product_id: the chosen product's id
quantity: number of units
address: shipping address
"""
p = INVENTORY.get(product_id)
if not p:
return f"Error: there is no product {product_id}."
if p["stock"] < quantity:
return f"Error: only {p['stock']} units of {p['name']} left."
p["stock"] -= quantity
return f"Order ORD-4471 created: {quantity}x {p['name']} to {address}. Total: ${p['price'] * quantity}."
tools = [search_products, check_stock, create_order]
tools_by_name = {t.name: t for t in tools}
model_with_tools = model.bind_tools(tools)
SYSTEM = SystemMessage(content=(
"You are the sales assistant of TechShop, a small electronics shop, and you answer customers on WhatsApp. "
"Keep replies short. Format for WhatsApp: *bold* and _italics_ only, no Markdown headers, tables or links. "
"Use the tools to search products, check stock and create orders. "
"NEVER make up prices, stock or products that didn't come from a tool. "
"Before creating an order, confirm the product, quantity and shipping address with the customer."
))
class State(TypedDict):
messages: Annotated[list[AnyMessage], operator.add] # new messages are appended, not replaced
async def llm_call(state: State):
"""The model reads the whole conversation and decides: call a tool, or answer."""
return {"messages": [await model_with_tools.ainvoke([SYSTEM] + state["messages"])]}
async def tool_node(state: State):
"""Your code runs the tools the model asked for."""
results = []
for call in state["messages"][-1].tool_calls:
observation = await tools_by_name[call["name"]].ainvoke(call["args"])
results.append(ToolMessage(content=observation, tool_call_id=call["id"]))
return {"messages": results}
def should_continue(state: State) -> Literal["tool_node", END]:
return "tool_node" if state["messages"][-1].tool_calls else END
builder = StateGraph(State)
builder.add_node("llm_call", llm_call)
builder.add_node("tool_node", tool_node)
builder.add_edge(START, "llm_call")
builder.add_conditional_edges("llm_call", should_continue, ["tool_node", END])
builder.add_edge("tool_node", "llm_call")
# The checkpointer saves each conversation's messages under a thread_id, so the agent remembers.
agent = builder.compile(checkpointer=InMemorySaver())
The pieces, in order:
-
Tools are plain Python functions.
@toolturns each one into a JSON description the model can read, and the docstring is that description. That's how the model knowscreate_ordershould only be called after the customer confirms. The inventory is a dict here; in your shop it's a database query. -
The state is a list of messages.
Annotated[..., operator.add]tells LangGraph that new messages are appended to the list instead of replacing it. -
llm_callis where the model decides. It gets the system prompt plus the whole conversation, and returns either an answer or a request to call one or more tools. The system prompt does most of the work: it forbids making up prices or stock, asks for confirmation before ordering, and asks for WhatsApp formatting. WhatsApp uses*bold*, not Markdown's**bold**, and models write Markdown unless you tell them otherwise. -
tool_noderuns the tools. The model never runs anything; it asks. Your code runs the function and puts the result back in the list as aToolMessage. -
should_continuecloses the loop. If the model's last message asks for tools, go totool_nodeand back to the model. If not, that message is the answer. -
The checkpointer is the memory. With
InMemorySaver, each call with the samethread_idcontinues where the last one left off. In the bot, the thread will be the WhatsApp conversation.
Checkpoint: the agent answers in your terminal
Before it touches WhatsApp, try the agent on its own. Create try_agent.py:
import asyncio
from dotenv import load_dotenv
load_dotenv()
from langchain.messages import HumanMessage
from agent import agent
async def main():
result = await agent.ainvoke(
{"messages": [HumanMessage("Do you have a wireless mouse under $50 that works with a Mac?")]},
config={"configurable": {"thread_id": "terminal-test"}},
)
for message in result["messages"]:
message.pretty_print()
asyncio.run(main())
Run it:
uv run python try_agent.py
The output should look something like this. The model words its answer its own way each time, but you should see a search_products call with a price limit, and that tool's result:
================================ Human Message =================================
Do you have a wireless mouse under $50 that works with a Mac?
================================== Ai Message ==================================
Tool Calls:
search_products (call_1)
Call ID: call_1
Args:
query: wireless mouse mac
max_price: 50
================================= Tool Message =================================
log-m240: Logitech M240 Silent, $32, works with Mac
key-k380: Logitech K380 (keyboard), $40, works with Mac
================================== Ai Message ==================================
Yes! The *Logitech M240 Silent* is $32 and works with Mac.
Notice that the search also returned a keyboard. The tool is crude on purpose: the model reads the results and recommends the mouse. You now have an agent that answers from real data. If you get AuthenticationError, check OPENAI_API_KEY in .env.
7. Hand text messages to the agent
The last step connects the two halves. It changes bot.py in three places, so here is the whole file:
import logging
import os
from contextlib import asynccontextmanager
from dotenv import load_dotenv
load_dotenv() # before importing the agent: the model reads OPENAI_API_KEY when it's created
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request
from langchain.messages import HumanMessage
import kapso
from agent import agent
from kapso import Button, InboundMessage, InteractiveReply, KapsoClient, KapsoError
API_KEY = os.environ["KAPSO_API_KEY"]
WEBHOOK_SECRET = os.environ["KAPSO_WEBHOOK_SECRET"]
log = logging.getLogger("bot")
MENU = [
Button(id="hours", title="Opening hours"),
Button(id="location", title="Where are you?"),
Button(id="human", title="Talk to a person"),
]
SORRY = "Sorry, I can't answer that right now. Try again in a minute, or tap *Talk to a person*."
@asynccontextmanager
async def lifespan(app: FastAPI):
async with KapsoClient(API_KEY) as client: # one connection pool for the whole app
app.state.kapso = client
app.state.seen = set()
yield
app = FastAPI(lifespan=lifespan)
@app.post("/webhooks/kapso")
async def webhook(request: Request, background: BackgroundTasks):
raw = await request.body() # the exact bytes Kapso signed
if not kapso.verify(raw, request.headers.get("x-webhook-signature"), WEBHOOK_SECRET):
raise HTTPException(status_code=401, detail="invalid signature")
for msg in kapso.parse(raw, request.headers.get("x-webhook-event")):
if msg.dedup_key in request.app.state.seen: # Kapso retries: same message, same key
continue
request.app.state.seen.add(msg.dedup_key)
background.add_task(answer, request.app.state.kapso, msg)
return {"ok": True} # answer fast: Kapso waits 10 seconds, then retries
async def answer(client: KapsoClient, msg: InboundMessage) -> None:
m = client.messages
try:
await m.mark_read(msg.phone_number_id, msg.message_id, typing=True)
match msg.content:
case InteractiveReply(id="hours"):
await m.reply_text(msg, "We're open Monday to Saturday, 9am to 7pm.")
case InteractiveReply(id="location"):
await m.send_location(
msg.phone_number_id,
msg.sender,
18.4735,
-69.8840,
name="TechShop",
address="Calle El Conde 101, Santo Domingo",
)
case InteractiveReply(id="human"):
await m.reply_text(msg, "Got it! Someone from the team will write you here shortly.")
case _ if msg.text: # typed text, a voice note's transcript, or a photo's caption
await m.reply_text(msg, await ask_agent(msg))
if msg.is_new_conversation:
await m.send_buttons(msg.phone_number_id, msg.sender, "Or pick one of these:", MENU)
case _:
await m.send_buttons(msg.phone_number_id, msg.sender, "Hi! π How can I help?", MENU)
except KapsoError as e:
# status, code and request_id are enough to debug, and never contain the user's text
log.error("reply failed: status=%s code=%s request_id=%s", e.status_code, e.code, e.request_id)
async def ask_agent(msg: InboundMessage) -> str:
try:
result = await agent.ainvoke(
{"messages": [HumanMessage(msg.text)]},
# one memory per Kapso conversation; recursion_limit stops a model that loops on tools
config={"configurable": {"thread_id": msg.conversation_id}, "recursion_limit": 10},
)
except Exception as e:
log.error("agent failed: %s", type(e).__name__) # the type only: the message can quote the user
return SORRY
return (result["messages"][-1].text or SORRY)[:4096] # WhatsApp's limit for one text message
What changed: text goes to the agent
answer() has a new case, case _ if msg.text:. msg.text is the SDK's "text to act on" for every kind of message: what the user typed, Kapso's transcript of a voice note, or a photo's caption. So voice notes reach the agent with no extra code, and only messages with no text at all (a sticker, a photo with no caption) still get the menu.
ask_agent() is the only place the two halves meet:
-
thread_id=msg.conversation_idgives each WhatsApp conversation its own memory, so "the M240 then" makes sense to the agent. Kapso opens a new conversation after an old one closes, so the agent starts fresh with returning customers. -
recursion_limit=10caps the steps in one run. If the model keeps asking for tools without answering, LangGraph stops it with an error instead of spending your money in a loop. - If anything goes wrong (the model provider is down, the limit is hit), the customer gets a short apology instead of silence. The log gets the exception's type only, because its message can quote what the customer wrote.
- A WhatsApp text message can be at most 4096 characters. The system prompt asks for short replies, but the slice makes sure. Without it, the SDK would raise a
ValueErrorbefore sending.
On the first message of a conversation, the bot also sends the menu after the agent's answer, so the customer sees the shortcuts. Kapso marks that message as the start of a conversation, and the SDK exposes it as msg.is_new_conversation.
load_dotenv() now has a second job: it must run before from agent import agent, because the model is created when agent.py is imported.
What changed: answer fast, think later
Until now the route answered inside the request, which was fine for a menu. An agent that calls a model two or three times can take longer than the 10 seconds Kapso gives your endpoint to return 200. When that happens, Kapso sends the same webhook again, and if it keeps failing, the webhook gets paused.
So the route now only verifies, parses and queues the work. FastAPI's BackgroundTasks runs answer() after the response has gone out.
Retries still happen (a slow network is enough), so the same message can arrive twice. Every InboundMessage has a dedup_key, which is its WhatsApp message ID and stays the same across retries. The bot skips keys it has already seen. Without this, a retry would run the agent twice, and the second run might create a second order.
What changed: the typing bubble
mark_read(..., typing=True) shows the blue ticks and a "typingβ¦" bubble right away. With an agent this matters: the customer sees the bot working while the model thinks. The bubble goes away when the reply arrives.
Checkpoint: talk to it
Save, let fastapi dev reload, and from WhatsApp send:
-
"Hi, I'm looking for a wireless mouse under $50 that works with a Mac". The agent calls
search_productsand recommends what came back. Then the menu shows up. - "The M240 then. 1 unit to Calle Duarte 12". It repeats the order back and asks you to confirm, because the system prompt says so.
-
"Yes". Now it calls
create_order. - "Do you have the K380 keyboard?". It's out of stock. A good agent says so and offers something else. If yours invents stock, tighten the system prompt: it's your main lever.
Tap the buttons too (they still answer instantly), and try a voice note.
If every message gets the apology, the agent is failing, and the terminal's agent failed: line names the exception. See Troubleshooting.
What you built
You have built a WhatsApp bot that answers fixed questions from buttons and hands everything else to an agent that works from real inventory. The final agent.py and bot.py are in the starter repo, if you want to compare them with yours.
You can now:
- Accept only the webhooks Kapso signed, and turn each delivery into typed messages
- Keep a webhook fast when the real work is slow, and handle retries without doing the work twice
- Put any LangGraph agent behind a WhatsApp number, with one memory per conversation
The WhatsApp code doesn't change if you swap the model, add tools, or move to another graph. Everything agent-related stays in ask_agent().
Troubleshooting
KeyError: 'KAPSO_WEBHOOK_SECRET' or KeyError: 'KAPSO_API_KEY'
Cause: the bot started without a .env file next to bot.py, or the file is missing that line.
Fix: create .env as in step 1, in the same folder you run fastapi dev from.
"POST /webhooks/kapso HTTP/1.1" 401 Unauthorized
Cause: the KAPSO_WEBHOOK_SECRET in .env isn't the webhook's secret.
Fix: copy the Secret from the webhook in Kapso again, then stop the bot and start it again.
No POST /webhooks/kapso line at all
Cause: Kapso can't reach your laptop: ngrok isn't running, or the webhook still has the URL from an earlier ngrok session.
Fix: check that ngrok is running, and that the webhook's Endpoint URL is the current ngrok URL plus /webhooks/kapso.
agent failed: AuthenticationError
Cause: OpenAI rejected the OPENAI_API_KEY in .env.
Fix: create a new key, put it in .env and start the bot again.
reply failed: ... code=131047
Cause: more than 24 hours have passed since the customer's last message, so WhatsApp only accepts templates.
Fix: send any message from your phone to open the window again.
Before you go to production
-
Memory that survives restarts.
InMemorySaverforgets everything when the process stops. LangGraph has Postgres and SQLite checkpointers (langgraph-checkpoint-postgres,langgraph-checkpoint-sqlite) that drop in with the samethread_id. -
Memory across conversations.
thread_id=msg.conversation_idstarts fresh when Kapso opens a new conversation. To remember a returning customer, use the sender's ID as the thread instead. -
One message at a time per conversation. People send three short messages in a row. With this code, three runs start at once on the same thread. Queue messages per
conversation_id, or turn on the webhook's Debounce rapid messages into batches option: Kapso then delivers the burst together,parse()hands you the messages as a list, and you join their texts into one agent call. -
Real tools need real guards.
create_orderhere trusts the model's arguments. In your shop, check the product, quantity and price in code before charging anyone. -
See what the agent did. Set
LANGSMITH_TRACING=trueand aLANGSMITH_API_KEY, and every run, tool call and token shows up in LangSmith. It's the fastest way to find out why the agent said something. -
The 24-hour window. You can only send free-form messages within 24 hours of the user's last message. After that, only approved templates go through (
client.messages.send_template(...)), and anything else raisesKapsoErrorwithcode=131047. The sandbox can't send templates, so test those on a real number. -
Accepted isn't delivered. A template send can return
acceptedand still fail a moment later. One common reason: Meta needs a payment method on your WhatsApp Business Account before it delivers templates, and without it every send fails with error131042. Failures arrive aswhatsapp.message.failedwebhooks, so subscribe to them. -
Don't log what users write.
repr()of kapso-python's messages and senders leaves out text, phone numbers, names and media URLs, solog.info("%r", msg)won't leak them. Log IDs instead. -
Dedup across processes. Swap the
setfor Redis or a database table with a unique column as soon as you run more than one worker. -
Media. Photos and voice notes come as
MediaMessage.await client.media.download(msg.content.media, phone_number_id=msg.phone_number_id)gives you the bytes, with a size cap and a checksum check, if you want to pass an image to a vision model. -
Webhooks for your own numbers. The dashboard is fine for the sandbox. For your own numbers you can also create webhooks with Kapso's Platform API (
POST /platform/v1/whatsapp/phone_numbers/{phone_number_id}/webhooks), where you pick the secret yourself.
Where to go next
-
Other kinds of messages (lists, images and documents, templates, reactions, WhatsApp Flows): kapso-python's sending guide. There's also a sync client,
KapsoSyncClient, if you're not on asyncio. - Memory in a database: LangGraph persistence.
- Other webhook events and batching: Kapso's webhook docs.
kapso-python is unofficial (not affiliated with Kapso) and alpha, so the API can still change. Install it with pip install kapso-python. If you build something with it, or it breaks on a message it should understand, open an issue. I'd love to see it.

Top comments (0)