WhatsApp Order Capture: How AI Turns Trading-Group Chat Into Auditable Orders
By Prasanna Patil, Zuneko Labs
Commodity traders negotiate in WhatsApp groups, and the real orders are buried under general conversation. This system reads those groups, converts informal, mixed-language chat into structured trade orders, grounds every extracted value in the original message, and sends only the lines it is unsure about to a human reviewer. The output is a live Trade Book with a full revision history.
Snapshot
The problem: orders buried in WhatsApp trading chat
In these groups, trade happens entirely in chat, and the real orders are buried under general conversation. There is no structure, no shared format, and no reliable way to tell an order from a greeting. That makes order-taking slow, error-prone, and impossible to audit.
A single WhatsApp message can be an order, an offer, a market-rate quote, a payment note, a loading instruction, a cancellation, or just a greeting. The specific pain points were:
- Orders are buried. Most messages are general chat, and orders sit among thousands of them.
- The language is informal and mixed. Traders write in Hinglish and shorthand, for example “chana ka bhav kya hai?”, with abbreviations, units, and pack sizes written inconsistently.
- Orders change over time. People reply to an earlier message with “make it 60”, “cancel this”, or a corrected party name. Without linking, these edits look like unrelated new orders.
- Nothing is auditable. There is no history of who changed what, and no way to trust a number without re-reading the thread.
The design goal in one line: never invent data. Every extracted value must be traceable to the words in the message.
The build was scoped against six hard goals, each a requirement the system is held to rather than a nice-to-have: capture every message reliably and keep the raw record immutable; classify each message and extract the order lines; never invent data; track an order’s full lifecycle and every amendment, including reply-based edits; surface only ambiguous or low-confidence items to humans, each with a clear reason; and run on a single VPS with monitoring, security, and CI.
How the system is built: four services, one database
The system runs as four services over one PostgreSQL database, designed to deploy to a single VPS. The split keeps the raw WhatsApp record separate from the AI’s interpretation of it, which is what makes the whole thing auditable.
- WhatsApp engine (Go). Handles QR login, message, reply, and reaction events, history sync, and session recovery. No browser or phone has to stay open. It sends webhooks to the backend with a shared secret.
- Backend (Node.js / Express). Runs JWT auth (15-minute access tokens, 90-day refresh), rate limiting, encrypted message storage, Socket.IO live updates, the trade REST API, and a background parser worker.
- Frontend (React + Vite + TypeScript). Provides login, the WhatsApp connection dashboard, an admin panel, and the Trade Book UI.
- PostgreSQL. Carries 39 versioned migrations with up and down scripts.
- Ops. Docker Compose, nginx, Uptime Kuma monitoring, Sentry, and Winston logging, plus secret-generation and deploy scripts and a GitHub Actions regression pipeline that includes gitleaks secret scanning.
The data model: evidence, interpretation, business state, audit
The data model separates what was said from what the system concluded. Raw messages are never edited. The AI’s reading of them lives in its own layer, and every human correction and state change is recorded rather than overwritten.
| Layer | Tables | Rule |
|---|---|---|
| Evidence | recovery.wa_messages | Raw WhatsApp ledger, encrypted at rest, never modified by the pipeline |
| Interpretation | trade.message_extractions, trade.extraction_lines | One row per message and parser version, one row per extracted order line |
| Business state | trade.orders, order_events, order_message_links | Live orders, their lifecycle, and the messages that touched them |
| Audit | extraction_line_corrections, order_events | Every human correction and state change is recorded, never overwritten |
How the extraction pipeline works
The pipeline moves a message from WhatsApp to a reviewed order in a fixed sequence: webhook, raw ledger, parser job queue, worker, pipeline, review queue, UI. The core idea is that the AI reads the message, but a deterministic check decides whether to trust what it read.
- Cheap gate. Skip empty messages only, for cost control. Everything else goes to the AI.
- Conversation context. A bounded window of recent chat, plus any open order, is passed to the model as disambiguation input only, never as a source of values.
- AI extraction. An OpenAI-compatible LLM provider classifies the message into one of 16 types (ORDER, ORDER_UPDATE, ORDER_CANCEL, OFFER, MARKET_RATE, PAYMENT, NAME_CHANGE, INQUIRY, GREETING, and more) and extracts the order lines. The prompt is versioned, now v8, so extractions can be reprocessed per version.
- Validation and hallucination guard. A deterministic tokenizer re-derives values from the text. Each line carries a source span, and any value whose cited text is not in the message is discarded. Tolerant span matching handles punctuation drift.
- Entity resolution. Raw names are mapped to canonical parties, products, and brands through an alias master, auto-creating records when needed.
- Confidence engine. Explainable per-field scores are produced. The AI is primary and the rule parser corroborates or disagrees. Overall confidence is the minimum of the field scores, and every score ships with a human-readable reason.
- Idempotent persistence. Lines are persisted idempotently, and a line a human has reviewed is never overwritten.
- Order pipeline. The line is linked to an existing order or creates a new one through an explicit state machine: draft, confirmed, loaded, completed, or cancelled. Invalid transitions are rejected.
- Learning loop. Human corrections to classifications are promoted to few-shot examples in later prompts.
Why AI-first, with rules as a check
The pipeline was deliberately reversed during the build. It started deterministic-first, with regex rules and the AI as a fallback. It was flipped to AI-first with deterministic corroboration, because the rules missed informal language while the AI handled it well. The rules stayed valuable as an independent check rather than as a gate.
How the system avoids inventing order data
The system avoids inventing data with structure, not with prompting alone. Every extracted field carries the exact span of source text it came from. A deterministic tokenizer then re-derives the value from the message, and any value whose cited text is absent is thrown away before it can reach an order.
This matters because a plausible-but-wrong number is worse than no number in a trade record. The source-span check is what lets the Trade Book be trusted without re-reading the chat.
Common questions about the extraction
How does an AI system extract structured orders from chat messages?
An AI model reads each message, classifies what it is, and pulls out the order fields: party, product, brand, rate, quantity, unit, and pack size. In this system the model works message by message, using a short window of recent chat only to resolve context, never as a source of values. A deterministic check then re-derives each value from the text before the order is saved. Anything the model is unsure about is sent to a human instead of guessed.
How do you stop AI from inventing order data when it reads messages?
You stop it with structure, not prompting alone. In this system every extracted field carries the exact span of source text it came from. A deterministic tokenizer re-derives the value from the original message, and any value whose cited text is not present is discarded before it can become an order. The result is that a plausible-but-wrong number never reaches the Trade Book, which is what lets the record be trusted without re-reading the chat.
How does human-in-the-loop review work for AI-captured orders?
Humans review only the lines the system is unsure about, not everything. Each extracted field gets an explainable confidence score with a human-readable reason, and low-confidence or ambiguous lines go to a review queue. A reviewer sees the confidence, the highlighted source text, and an edit form, then approves or corrects. Corrections are recorded and never overwritten, and they are promoted to examples that improve later extractions. Confident lines flow straight through.
How order changes and amendments are tracked
Order amendments are tracked by following the reply, not by guessing from timing. When a trader replies to an earlier message, the system threads the reply-quote metadata into the pipeline and links the reply to the quoted message’s order. There is no time window, so an amendment still attaches days later, and it attaches transitively through earlier amendments.
- It feeds the quoted message into the AI prompt, so a bare “make it 60” inherits the party and product from the original order.
- It handles cancellations and amendments that contain no extractable line.
- It records a revision history with per-field diffs and ignores no-op amendments that restate the current value.
- It was later extended to track party, product, and brand name changes, with display-name translation in revision timelines.
Bugs found and fixed
The honest part of this feature is how many edge cases it exposed. Fixing them is what made amendment tracking reliable.
- Case-sensitive units. The tokenizer uppercases units while the AI preserves case, so every lowercase-unit line was flagged as a disagreement and denied an order.
- Multi-line overwrite. Two lines of one message matched each other on party and product and overwrote each other’s rate. Now only an order update, a cancellation, or an explicit reply may modify an existing order.
- Collapsed brands. Different brands of the same product were merged. Brand is now part of order matching.
- Duplicate orders on reprocessing. Order creation is now idempotent.
- Infrastructure. nginx proxied to the wrong backend port, causing 502s, and the database URL pointed at a port nothing listened on.
What the Trade Book looks like
The product surface is a review-first workspace, not a raw data dump. A reviewer sees the extracted lines, the confidence behind each one, and the exact message text each value came from.
- Extractions table with URL-synced filters and presets, bulk approve, confidence bars with explanations, highlighted source spans, amended values shown struck-through with revision popovers, a Reprocess button, and filtering by source WhatsApp group.
- Review queue for ambiguous and low-confidence lines, with an edit form and a source drawer.
- Orders and Order Detail with an event timeline, linked messages, per-field diffs, and date-range filters.
- A thumbs-up reaction on approval: when a reviewer approves an extraction, the system reacts to the original WhatsApp message with a thumbs-up. It is best-effort and deduplicated, and it closes the loop back to the trader.
How reliability was engineered
Reliability was built in, not bolted on. The trade domain is covered by 24 backend unit and regression test files spanning the parser, validator, confidence engine, state machine, order linker and writer, repository, routes, and worker, alongside security, API, infrastructure, and recovery suites. The frontend is tested with MSW.
- CI. A GitHub Actions regression workflow with tracked-secret checks and gitleaks.
- Security. JWT auth, ownership middleware, webhook secret and signature validation, field-level encryption of message content, HTTPS middleware, rate limiting, and a deployment hardening guide.
- Observability. A Prometheus-style metrics service, Sentry, Winston, and Uptime Kuma.
- Measurement before change. A Phase 0 baseline froze a read-only copy of the data and recorded metrics, so improvements are measured, not assumed.
- Data hygiene. A Phase 1 backfill tool, written in Go and run dry-run first, corrected historical rows whose real message type (images, documents, audio, reactions) had been stored as text.
What this changes
The system changes how a trading desk keeps its order book. Instead of reading thousands of messages to reconstruct what was ordered, a reviewer works a short queue of uncertain lines, and every confident order is already structured and linked to its source message. Each value is grounded in the chat, every change is recorded, and humans touch only what the system flags.
If your business also bills in Tally, the same captured order can be pushed into your accounting system in one click. Read how the WhatsApp-to-Tally flow works.
What we learned
- Reversing the architecture was the right call, but it was not free. Moving from deterministic-first to AI-first meant rewriting the confidence model so rules corroborate rather than gate.
- Hallucination control needs structure, not just prompting. Source spans and a deterministic re-check catch ungrounded values that the prompt alone does not.
- Amendments are the hard part of order tracking. Matching on party and product alone is dangerous. Explicit reply-quote linkage is a far stronger signal than inference from timing.
- Idempotency matters because messages are reprocessed whenever the prompt version changes.
Inherited code also carries inherited schema. Many early migrations still reflect the old claims domain, and removing them is future cleanup.
The technology stack
Go 1.25 · Node.js 18 with Express and Socket.IO · PostgreSQL 16 · React 18 with Vite and TypeScript · an OpenAI-compatible LLM provider · Docker Compose with nginx · Uptime Kuma · Sentry · Jest with MSW · GitHub Actions with gitleaks.
Frequently asked questions
They use a system that reads the WhatsApp messages, separates real orders from general chat, and writes each order into a structured record. This case study describes one such system for commodity traders. It connects to the trading groups, classifies every message, extracts the order lines, and builds a live Trade Book of parties, products, rates, and orders, each with a full revision history. Humans step in only for messages the system cannot read with confidence.
Yes. AI can classify each message and extract the orders, even when the chat is informal and most of it is not an order at all. In this system a single message might be an order, an offer, a market rate, a payment note, a cancellation, or a greeting, and the model sorts them. The key safeguard is grounding: every value is checked back against the message text, so the system extracts what was written rather than what it assumed.
Orders are buried, the language is loose, and orders keep changing. Most messages in a trading group are general chat, so real orders sit among thousands of others. Traders write in Hinglish and shorthand, with inconsistent units and pack sizes. People also amend orders by replying “make it 60” or “cancel this”, which look like unrelated messages without linking. On top of that, plain chat leaves no audit trail of who changed what.
Yes, and handling informal mixed language is the main reason this system is AI-first. Messages like “chana ka bhav kya hai?” mix languages, use abbreviations, and write units and pack sizes inconsistently. Rule-based parsing missed this kind of text, while the AI model read it well. The project kept deterministic rules as an independent check on the AI’s output, but the AI does the reading of the messy, real-world language.
WhatsApp order capture is turning the order messages a business receives on WhatsApp into clean, structured order records. It covers reading each message, deciding whether it is an order, and extracting fields like party, product, rate, and quantity. Done well, it also tracks later changes to an order and keeps an audit trail. The goal is to replace manual re-reading of chat with a reliable order list a business can act on and trust.
The main benefit is a reliable, auditable order record without manual re-reading of chat. Orders are separated from general conversation automatically, every value is traceable to the original message, and later changes are linked to the order they amend. Staff spend their time only on the lines the system flags as uncertain, rather than on every message. The business gets a live order book it can trust instead of a scroll-back through thousands of messages.
For informal, mixed-language chat, AI reads the messages better than rules alone, but the strongest setup combines them. This project started rule-first and reversed to AI-first, because regex rules missed shorthand and Hinglish that the AI handled. The rules were kept as an independent check that corroborates or disputes the AI’s output rather than gating it. Manual entry stays in the loop only for low-confidence lines, so people handle exceptions, not every message.
Yes, a captured order can be pushed into accounting software such as Tally. In this setup the reviewed order is sent to Tally with a single click, so staff do not retype it, while Tally stays the system of record for billing. This case study focuses on the capture and extraction engine; the accounting push is covered on the WhatsApp-to-Tally integration page.
Changes are handled by following the reply, not by guessing. When a trader replies to an earlier order message with something like “make it 60” or “cancel this”, the system links that reply to the original order and applies the change. There is no time limit, so an amendment attaches even days later. Every change is saved as a revision with a field-by-field history, and cancellations are handled explicitly, so the order’s full lifecycle stays visible.
No. In this system the WhatsApp connection is handled by a dedicated service that logs in by QR code and keeps its own session, with history sync and session recovery built in. No phone or browser has to stay open for messages to be captured. Messages arrive by webhook and are stored in an immutable ledger before any processing, so nothing is lost if a component restarts.
Yes, security and auditability were core goals. Message content is encrypted at the field level, the raw WhatsApp ledger is stored encrypted and never modified, and access uses token-based authentication with rate limiting. Every human correction and every order state change is recorded and never overwritten, so there is always a trail of who changed what. The connection between services is protected with a shared secret and signature validation.
See how Zuneko’s AI automation works, or talk to the team about your workflow.
