How we built a Bangla RAG sales assistant for Facebook Messenger

Inside our Bangla AI sales assistant for Messenger: hybrid RAG, batching, memory, buying signals, guardrails, cost caps and why a 21x cheaper model lost.

Written by
DevTech365 Engineering
Published
Reading time
8 minutes

PromptCV.app is an AI CV and cover letter builder, and much of its Facebook Messenger inbox arrives in Bangla: questions about features, prices and how the product works, many from people who just tapped a paid ad. We built a RAG sales assistant that answers them in Bangla, grounded in the product's knowledge base. It has been live since July 2026.

The stack is small: a Node.js service for Meta's webhooks, Gemini for replies and embeddings, and MongoDB Atlas for the knowledge base, memory, queues and usage counters, running in Docker on AWS EC2. The hard parts are elsewhere. Customers mix Bangla script, Banglish (Bangla typed in Latin letters) and English in one message. A claims policy forbids promising jobs, inventing delivery times or quoting retired prices. Meta's standard messaging window closes 24 hours after a person's last message, and an opt-out is permanent. The model call turned out to be the smallest part of the system.

Retrieval: small chunks, two searches, one ranking

The knowledge base is a structured JSON file that mirrors the product documentation. On startup it is split into chunks, and only chunks whose content hash changed are re-embedded.

Chunk size mattered more than the search algorithm. Retrieval returns a fixed top five, so a long section that matches on one sentence drags the rest into the prompt, costing tokens and diluting the answer. We split sections into one chunk per sub-topic, FAQs into one chunk per question and sales objections into one chunk each. How-to chunks are phrased the way customers ask ("how do I change the template"), because product descriptions retrieve badly against task questions.

Each query runs two searches in parallel. Atlas Vector Search over Gemini embeddings handles paraphrase. A MongoDB text search catches exact tokens such as plan names, prices and English product terms. The two scores are not comparable, so we merge the ranked lists with Reciprocal Rank Fusion:

// Simplified: merge two ranked lists by position, not by raw score
function fuse(vectorHits: Chunk[], textHits: Chunk[], k = 60, limit = 5) {
  const scores = new Map<string, { chunk: Chunk; score: number }>();
  for (const hits of [vectorHits, textHits]) {
    hits.forEach((chunk, rank) => {
      const entry = scores.get(chunk.key) ?? { chunk, score: 0 };
      entry.score += 1 / (k + rank + 1);
      scores.set(chunk.key, entry);
    });
  }
  return [...scores.values()]
    .sort((a, b) => b.score - a.score)
    .slice(0, limit)
    .map((entry) => entry.chunk);
}

Degraded modes are designed, not accidental. If vector search fails, a circuit breaker switches it off for five minutes and skips the query embedding too, so we stop paying for vectors nothing can use, while text search keeps running. If both searches return nothing, the model gets a curated set of chunks led by the claims policy, because degraded mode is when a wrong claim is most likely.

Batching and memory

Messenger users rarely send one complete message. They send "hi", then "price koto?" (what's the price?), then a second question. Answering each fragment costs money and reads like a bot, so every incoming message joins one buffer per person and a debounce window of a few seconds collects the burst. The webhook wakes the worker when the window closes; a slow poll only recovers jobs stranded by a restart.

The buffer is a small job queue and got the same care as any API and backend development work. Workers claim it atomically with a lease, so two never answer the same person, and crashed claims are reclaimed a bounded number of times. If a send fails, the already paid-for reply is reused, but only while the buffer holds exactly the messages it answered. A delivery marker written before the claim closes stops recovery from sending the answer twice. The joined turn is capped in length, keeping the newest text, so a paste cannot become an unbounded bill.

Memory combines a recent window of the last 15 exchanges, verbatim, with semantic recall of a few older messages, found by vector search filtered to that person and deduplicated against the window. We embed both sides of the conversation. When only customer messages were embedded, the assistant could not recall questions it had already asked, so it asked them again. Bare acknowledgements such as "ok" or "ধন্যবাদ" (thanks) are skipped, but the minimum length is low on purpose: "কত টাকা?" (how much?) is eight characters and one of the strongest buying signals there is.

When a human admin replies from the Page inbox, the assistant pauses for that person for ten minutes. A global pause in the admin dashboard stops every automated reply at once.

Buying signals and follow-ups live in code

Deciding when to move toward a sale is too important to leave to the model. A deterministic detector with Unicode-aware patterns for Bangla, Banglish and English classifies a message as a service request, purchase intent, or a plan, payment or price question. When one fires, the prompt gets a short instruction for that closing move, and the model still writes the reply.

A few rules carry most of the value:

  • Precision over recall. A false positive pitches someone who was only browsing. A miss just leaves the stage to the model.
  • Declines win. "lagbe na" (I don't need it) suppresses every signal in the message.
  • Scripts break word boundaries. \b does not work for Bangla, so patterns anchor on any character that is not a letter or digit.
  • Opt-outs match loosely and last forever. A false positive costs one lead; a false negative puts the Page at risk.

A detected signal can also arm one follow-up if the person goes quiet. It goes out only inside Meta's window, never during quiet hours in Bangladesh time, and is dropped rather than sent late. Each person has a lifetime cap, code appends the opt-out line, and if the follow-up settings cannot be read, nothing is sent.

Paid traffic needs care too. Meta reports ad clicks differently for first-time and returning visitors, so we handle both shapes and store the referral, first touch winning. When the assistant later shares the order link, code appends the campaign parameters, so the order traces back to the ad. The model never types those URLs, because long query strings are exactly what language models silently mangle. Organic visitors get untagged links, which keeps the campaign's numbers honest.

Guardrails before every send

Every reply is graded against the claims policy before it leaves: no job guarantees, unhedged delivery promises, prices for retired products, invented buttons or retired URLs. A violation triggers one repair pass with an instruction naming the broken rule. If that still fails, the customer gets a safe fallback line and the team gets a Telegram alert with the rule and the blocked text.

The hard part was not catching bad replies but letting good ones through. Asked "chakri hobe to?" (will I get a job?), the correct answer is a clear denial, and every natural denial contains the word for guarantee, so our first pattern flagged exactly the replies we wanted most. The fix had to respect both languages: English negates before the verb ("we cannot guarantee"), Bangla after it. The check window also stops at sentence punctuation, including the Bangla danda (।), so a denial in one sentence cannot excuse a claim in the next.

Cost limits and the cheaper model we rolled back

Paid AI calls sit behind two independent limits: a per-user hourly cap, so one person or script cannot turn a flood of messages into a flood of model calls, and a global daily cap as the backstop for webhook storms and retry loops. The per-user check runs first, so a blocked spammer cannot spend everyone else's budget. If the counter store is down, the limiter fails open, because going mute on customers is the worse failure.

The daily cap is a dollar budget counted in calls, so it must be recalculated whenever the cost per reply changes. Every reply records prompt, cached, thinking and output tokens plus the model version the response reports. The version is pinned, because a floating alias can move to a pricier model without any code change.

Then came a tempting experiment: we switched to a model from another provider that was 21 times cheaper per reply. To check it, we ran both on the same cold-open and multi-turn scenarios, several passes each, graded first by our guardrails and then by blind pairwise comparison, with answer order randomized and judge models from other vendors.

The cheaper model was just as safe. It sold worse. Asked for something cheaper, it named the lowest price and stopped, where Gemini offered a lower-cost service and the referral route. Given a two-part objection, it answered one half. It recommended plans the fit rules did not support. We reverted to Gemini and recalculated the daily cap, since a cap sized for the cheaper model would have allowed far more spend.

Testing and deployment

The service has 30 test suites on Node's built-in test runner. They cover retrieval, batching and claim recovery, buying signals, guardrails, follow-ups, campaign links, token telemetry and the admin routes.

Unit tests cannot tell you whether a prompt still sells, so two smoke scripts run against the live model. One plays fixed sales scenarios through the real prompt, each stating what a good reply must and must not do, and grades the replies with the same guardrails instead of a judge model. The other checks how the assistant ends conversations, including when to send nothing. Scenarios change in the same commit as the prompt.

Every push to main deploys through GitHub Actions. The workflow syncs the code to EC2 without touching server-side secrets, rebuilds the containers with Docker Compose and fails if the public webhook stops responding. An authenticated admin dashboard shows health, traffic and AI spend, and operational alerts go to Telegram.

What we'd do again

  • Put decisions in code and language in the model. Buying signals, links, opt-outs and attribution are deterministic.
  • Keep chunks small and the fallback curated. Hybrid search with rank fusion is simple and degrades gracefully.
  • Grade every reply before it is sent, with one repair pass and a safe fallback.
  • Record token usage from day one and pin model versions.
  • Judge models on the outcome you sell. The cheaper model passed every safety check and still lost.

Most of this is ordinary engineering discipline applied to AI development: queues, limits, tests and telemetry around the model. For deciding where a model belongs in the first place, see where AI pays off in business software.

  • RAG
  • AI chatbot development
  • Gemini

DevTech365 Engineering

Software engineering team

The engineers who build DevTech365's mobile apps, web platforms, APIs and AI systems, writing about the decisions behind production software.

Have a software idea?Let's turn it into something real.

Tell us what you want to build and where you are today. We'll reply with questions, next steps and an honest view of how we can help.