WhatsApp ordering agent: Hinglish messages in, confirmed orders out¶
Run it, don't just read it
Every lab runs on your laptop with Ollama. Set up once (INSTALL), then:
git clone https://github.com/JSWOne/ai-learning.git && cd ai-learning
cd whatsapp-agent && python 01_chat_loop.py
Lab files and data: whatsapp-agent/ on GitHub. In VS Code, open the repo folder and use Terminal > Run Task > Run this lab.
Small, runnable examples of an agent that takes B2B orders on WhatsApp from building-material stores: "50 bag Kiran PPC aur 20 sariya 8mm bhej do" becomes a priced cart, a card with a Confirm button, and an order. So does a photo of a handwritten list (09). Each numbered file shows one pattern.
New to this? Read learn-whatsapp-agent.md first: what it is and why, the mental model in code and diagrams, the labs in three stages, key decisions and advanced topics.
Before you start: llm-api and agents (its harness is reused); lab 08 uses structured output from prompting. After it, you can: build a channel agent where the model handles language and code handles money and stock.
Done with the labs? Try the three exercises and the build-it-yourself task in PRACTICE.md.
It reuses the agents harness (../agents/agent/: run(), budgets, trace, checks) with new tools: plain Python functions over a fake backend for Acme Build, a made-up building-materials marketplace (shop/). What's new is the channel: messages arrive one at a time, in mixed language, from phones; buttons stay tappable forever; webhooks repeat; and the customer, not a manager, approves.
Setup¶
Install steps for all topics are in ../INSTALL.md. This topic imports ../agents/agent/ (which imports ../mcp-server/host.py), so their Python packages must be installed. From the ai-learning folder:
source .venv/bin/activate # the one venv at ai-learning/ (see ../INSTALL.md section 4)
uv pip install -r requirements.lock # all topics, the tested versions
cd whatsapp-agent && pytest -q && python 01_chat_loop.py
Run every example from this folder. 04 needs no model. 09 needs a vision model instead of qwen3:8b: ollama pull qwen3-vl:8b-instruct (about 6 GB; set by VISION_MODEL). It does every step of a photo turn, so only one model is in memory.
The web chat: a WhatsApp-like page with the agent's trace, cart and credit beside it. Switch phones at the top to be the owner, the munshi (staff), or another store.
cd whatsapp-agent && uvicorn web.app:app --reload # open http://127.0.0.1:8000
WA_MODE=agent uvicorn web.app:app --reload # the page uses lab 08's design by default; this compares the agent
The 📎 button sends a photo (try the notes in photos/); whatever is in the text box goes as its caption.
Files¶
Track: Core labs are the Core path through the course. Before you ship: safety lessons to do before anything you build goes to real users. Go further: when your work needs that pattern (see Use it when).
| File | Track | Pattern | Use it when | Time |
|---|---|---|---|---|
01_chat_loop.py |
Core | One message: text in, agent builds a cart, code sends a card, Confirm runs code | You want to see the whole loop once | ~30 s |
02_sku_matching.py |
Go further | Hinglish, spelling and sizes matched in code; units converted in code; ask when a tool says ambiguous | Customers name products their way | ~1-2 min |
03_memory_and_reorder.py |
Go further | "Same as last time", add vs set, the cart as typed state in the prompt, a session saved between messages | Orders arrive in bits over hours | ~1-2 min |
04_confirm_in_code.py |
Before you ship | Double taps, repeated webhooks, old buttons, price and stock changes: all handled by code, no model | Anything that commits money or stock | seconds |
05_credit_and_payment.py |
Go further | One credit policy function; the agent explains it, the card, the button and the backend enforce it | Credit, overdue bills, staff vs owner | ~1-2 min |
06_routing_and_handoff.py |
Go further | Rules then a model route each message; scoped tools per route; complaints to a person; injection | One number gets every kind of message | ~2 min |
07_evals.py |
Go further | 25 messy messages (incl. rewordings and mixed questions) with expected carts, scored in code by tag; --extract runs lab 08's design |
Deciding if a prompt, tool or model change helped | ~4 min |
08_extract_then_code.py |
Core | One structured-output call per message, then code runs the same tools; a small read-only agent answers any question in the message; full agent as fallback; both designs on the golden set | The message shape is known and the agent keeps forgetting steps | ~7 min |
09_photo_order.py |
Go further | A photo of a handwritten list: a vision model copies it to text, code drops what it can't trust, lab 08 runs on the text, the customer sees "Photo se padha: ..." before the card; vs one vision call straight to the order | Orders arrive as pictures, not messages | ~2-4 min |
Shared code:
| File | What it holds | Read? |
|---|---|---|
bot/core.py |
Bot.handle() (mode="agent" or "extract"): one message in, replies out |
Read |
bot/tools.py, bot/specs.py |
The tools bound to one session, argument guards, LocalTools; tool specs per intent |
Read |
bot/confirm.py |
cart_card(), confirm(): the order is placed by code, never by the model |
Read |
bot/prompts.py, checks.py, router.py, extract.py |
Prompts and language; check_reply(); the router; OrderIntent, apply_intent() |
Read with labs 01, 06, 08 |
bot/session.py |
Inbound/Out, Session (cart, version, saved as JSON) |
Skim |
bot/photo.py |
NoteReading, read_note(), split_lines(), prepare(); read_order() (design B) |
Read with lab 09 |
bot/labkit.py |
run_case(), run_photo_case(), score_case(), printing helpers |
Read with lab 07 |
bot/config.py |
Paths | Skip: plumbing |
shop/matching.py, money.py, orders.py |
match_products(), to_base_units(); prices, tiers, credit_status(); place_order() (idempotent), RFQs, tickets |
Read with labs 02, 05, 04 |
shop/data.py |
The fake catalog with aliases, customers and past orders | Skim |
golden.json |
The eval cases for 07 |
Skim |
photos/ |
7 synthetic handwritten notes, cases.json (their text and expected carts), make_photos.py (draws them with the Kalam font, OFL) |
Skim |
web/ |
FastAPI + HTMX chat page (app.py, templates/, static/) |
Skip |
../agents/agent/ |
run(), AgentState, Budget (reused as-is) |
Skip: agents |
Labs import everything from the packages (from bot import Bot, say, show, import shop). Each lab's docstring names the functions to read first.
Exercises to practise with: PRACTICE.md (your own files go in my-work/). Questions and answers are in FAQ.md. The learning guide is learn-whatsapp-agent.md (diagrams in diagrams/).
Rules of thumb¶
- The agent proposes, code decides. The agent builds a cart; there is no
place_ordertool. The customer's button runs code. - Anything the model only has to remember to do, it will sometimes forget. Make code do it: code sends the card when the cart changed (first real run: 8 of 15 chats had no buttons).
- Pass the customer's words, not the model's arithmetic: quantities go to tools as text ("2 ton"), and a guard refuses a number the customer never said.
- Facts and money are code: SKU matching, unit conversion, prices, credit. The model passes the customer's words to tools and turns tool answers into a friendly reply.
- The confirmation card is rendered by code from the pricing system, never written by the model. Use WhatsApp buttons, never "reply YES".
- Re-check at the tap: price, stock and credit can change between the card and the Confirm. The backend checks a third time.
- Two kinds of duplicates, two fixes: dedupe webhooks by message ID, and make the order idempotent by cart ID.
- Every card carries a cart ID and version. Old buttons stay tappable in WhatsApp; a tap on an old card gets the latest cart, never the old order.
- Identity comes from the phone number, never from the message or a tool argument. Roles (owner, staff) decide what the phone may do.
- When a tool says "ambiguous", ask. A wrong SKU delivered to a remote store costs a truck trip.
- Put policy in one tool that returns the decision, the reason and the options. Prompts explain; they don't enforce.
- Route first when one number gets many kinds of messages. Rules for the obvious cases, a model for the rest, small tool sets per route, a person for complaints.
- Keep the cart in typed state and put it in the prompt every turn. Don't trust chat history to remember quantities.
- Measure with a golden set of real-style messages, scored in code. Read which check failed, not just the total. Grow it from every chat that went wrong.
- When the message has a known shape (items, quantities, add/set/remove), try extract-then-code before an agent loop: one model call, nothing to forget. In our real run it scored 15/15 vs the agent's 12/15, 3x faster. Keep the agent for what doesn't fit (
08). - Decide "is anything still open?" from tool results, not from the reply's punctuation. A "Confirm?" isn't a question.
- Check claims, not just numbers: "add kar diye" with no successful add, or "ho sakta hai" with no tool call, goes back to the model once, then to a person.
- Tier your checks. Block on wrong facts and false claims; repair style (script, length) after the turn. A blocking style check sent a correct delivery date to a person (G18).
- A photo is just another way to send the same message. Put a vision model in front of the text path you already trust; don't build a second ordering path for pictures (
09). - Read back what you read. "Photo se padha: ..." lets the owner catch a misread before the card, and the transcript gives the quantity guard real words to check.
- One model per turn on a laptop. A vision model is a full chat model too; split read and extract across two models only when you've measured a gain.
- On a note, the same product twice is a correction until the customer says otherwise: ask, never add them up. A model can miss a strike-through; code can't miss a repeat (real run: 40 + 30 = 70 bars).
- Unreadable means ask. The vision model writes [?]; code turns that line into a question. Never let a model guess a number off a photo.
- Text inside a photo is untrusted input, like a typed message. Prices, payment and the order stay in code, so a note that says "price is Rs 100" changes nothing.
- At temperature 0 a re-run repeats itself. Test robustness by rewording cases and running them mid-chat, not by running twice.
Tests¶
pytest -q runs model-free tests with a scripted fake model: SKU matching and sizes, unit conversion, prices and money format, the "search before add" guard, add vs set, tool scope, reorder, other stores' orders, the RFQ limit, the credit policy, a full turn with a card, double tap, duplicate webhook, unknown phone, a stopped turn, stale buttons, price and stock changes, credit refusal with Pay now, staff payment, cancel, check_reply, router rules and fallback, complaints without an agent, scoped tools per route, session save and load, the eval scorer, the golden set, the web confirm flow, the fixes from the first real run (quantity guard, add vs set, cart-aware matching, tied choices, weights and containers, credit on an empty cart, code sends the card, no card on a question, language in code), extract mode (one call and a card, a code-written question, the guard, fallback to the agent, the RFQ limit), and photos (the image reaches the vision model, unreadable and "note to AI" lines never reach the text model, the guard checks what was read, a photo with no order, design B, the upload page, the photo cases).
How qwen3:8b actually behaves (whether it splits items, asks on ambiguous ones, adds vs sets) can only be seen by running the labs against Ollama.