How I Built a Support Chatbot for a DTC Brand — and Why I Deliberately Avoided Half the 'AI Stack'
Most "I built an AI chatbot" posts are a victory lap. This one is the decision log the problem, what I reached for first, the options I weighed, the one I picked and why, the extra engineering I did on purpose, how I loc
Most "I built an AI chatbot" posts are a victory lap. This one is the decision log the problem, what I reached for first, the options I weighed, the one I picked and why, the extra engineering I did on purpose, how I locked it down, and what I'd do next. If you want to see how an engineer actually reasons about an agentic system under real constraints, that's what this is.
1. The story: a founder drowning in the same five questions
The client is a small direct-to-consumer wellness brand that sells silver-infused "grounding" products — sheets, mats, blankets, a pet mat, a few accessories. Nine products total. It's run, essentially, by one person: the founder.
Her problem was simple and very human. Customers kept emailing the same questions — "Which sheet is right for me?", "How do I wash it?", "Do you ship internationally?", "What's your return policy?" — and as a solo founder in a holiday retail crunch, she was answering them two days late, one at a time. Sales and goodwill were leaking out of the gap.
But there was a landmine in the mix: health questions. These are wellness products, and people ask things like "I have a pacemaker — is this safe?" Those cannot be answered by a bot guessing. Getting one wrong is a liability, not a support ticket.
So the real problem statement was:
Automate the 80% of repetitive product questions, instantly and in the brand's voice — while making the dangerous 20% (anything medical) safely hand off to a human.
2. What I reached for first (and why I stopped)
My first instinct was the thing everyone builds in 2026: RAG + a vector database + an agent framework. Ingest all the content, chunk it, embed it, stuff it in Pinecone, let an agent with tools reason over it. It's the "serious" architecture. It's what the conference talks show.
Then I actually looked at the problem and caught myself. Nine products. The complete catalog — prices, sizes, materials, care instructions, policies, FAQs — fits in about 2,500 tokens. Modern models have 128K–200K token context windows. I'd be building a retrieval system to search a haystack that's smaller than a single prompt.
That's the trap: reaching for the impressive tool instead of the right one. So before writing code, I did the most valuable hour of the whole project — I wrote down the options and compared them.
3. The options on the table — explained properly
Before writing code, I laid out the realistic ways to build this. The first fork every project faces is buy vs. build; then, if you build, the thing that actually separates the architectures is one question: how does the product knowledge get in front of the model? Keep that question in mind — it's the whole difference.
Option 0 — Buy an off-the-shelf bot (Chatbase / Voiceflow / Botpress)
What it is: sign up for a chatbot SaaS, paste in your content, drop their widget on the site. You configure; they host and run it.
Why I passed: weak brand/voice control, a recurring per-seat fee, uncertain compatibility with the client's no-code site builder, and customer data living in a third party. For a brand whose entire ask was voice and trust, renting someone else's bot was the wrong trade.
Verdict: ❌ rejected — this is a build problem.
The three build options differ only in that one line — how knowledge reaches the model.
Option A — Managed LLM + lightweight backend (prompt-stuffing)
What it is: your own thin backend calls a hosted model. The product knowledge sits in a file that gets loaded, whole, into the prompt on every request.
How it works:
user message → load the entire knowledge file
→ [ system prompt + ALL knowledge + message ] → LLM → reply
Stack: a small Node/Python API + a hosted model + one JSON/text file. That's it.
Strengths: dead simple, accurate (the model sees everything), cheap, fast (a single call).
Weakness: it's generic. Knowledge is one undifferentiated blob, the prompt has no structure, and there's no real story for guardrails, growth, or letting a non-engineer maintain it. It works — but it's a script, not a system.
Option B — Full custom RAG (retrieval pipeline)
What it is: the "serious enterprise chatbot." Instead of putting all knowledge in the prompt, you retrieve only the relevant pieces for each question using semantic search.
How it works — two phases:
Offline (build an index):
documents → split into chunks → embedding model → store vectors in a vector DB
Per request:
user message → embed the question → semantic search for the top-k nearest chunks
→ [ system prompt + ONLY those chunks ] → (optional reranker) → LLM → reply
(An **embedding* turns text into a list of numbers so "which chunks are most similar to this question?" becomes a math lookup. A vector DB stores and searches those numbers.)*
Stack: ingestion/chunking (LangChain/LlamaIndex) + an embedding model + a vector DB (Pinecone/Weaviate/Chroma) + optional reranker + the backend + the model.
When it's the right call: when the knowledge is too big to fit in the context window — thousands of documents, big FAQ libraries, PDFs.
Why it's wrong here: the entire catalog is ~2,500 tokens. You'd be building a search engine to find a needle in a haystack that's smaller than a single prompt. Worse, with only a handful of vectors, similarity search gets noisy — it can fetch the wrong chunk and make the bot less accurate than simply showing it everything. Pile on the extra cost, the extra failure points (chunking strategy, embedding drift, re-indexing), and a founder who could never maintain a vector DB.
Verdict: ❌ NOT RECOMMENDED — it solves a problem this brand doesn't have.
Option C — Structured knowledge + LLM ✅ (picked)
What it is: like A in spirit (knowledge in the prompt, one model call) but engineered as a real system. The catalog is kept as separate, structured files — products.json, policies.json, brand-voice.md, safety-language.md, escalation-rules.md — and a prompt composer assembles them into a clean, sectioned system prompt at runtime.
How it works:
user message → prompt composer builds the system prompt from structured sections
(identity · voice · products · policies · safety · escalation · security)
→ LLM → validate the output → reply
Why it's not just Option A:
- Externalized & structured knowledge — a non-engineer edits one JSON file and it hot-reloads, no deploy.
- Composable prompt — each concern (voice, safety, escalation…) is its own section you can change in isolation.
- Real seams — the backend has defined places for guardrails, escalation, monitoring, and later a retrieval layer, without rewrites. It's A's simplicity with a system's discipline. Strengths: highest accuracy (everything in context — nothing to retrieve wrong), lowest cost, fastest, smallest security surface, and genuinely maintainable by the founder.
Side by side:
| Criteria | O: Buy SaaS | A: Prompt-stuff | B: Full RAG | C: Structured + LLM |
|---|---|---|---|---|
| Fits budget & timeline | ⚠️ ongoing fee | ✅ | ❌ | ✅ |
| Accuracy | Medium | High | Medium (retrieval noise) | Highest — all knowledge in context |
| Operational cost | Subscription | Low | High | Lowest |
| Brand / voice control | ❌ | ✅ | ✅ | ✅ |
| Founder can maintain it | ⚠️ | ⚠️ (edits a blob) | ❌ | ✅ (edits a structured file) |
| Security / privacy surface | External | Small | Large | Smallest |
| Extensible to Phase 2/3 | ❌ locked in | OK | Already heavy | Clean seams |
Why C won, in one line: it's the smallest system that solves the whole problem — the accuracy and simplicity of prompt-stuffing, but structured and seamed like real software, so a non-engineer can run it today and I can grow it tomorrow. The framing I kept returning to: this is not "just a system prompt" — it's a real system that is simply smart enough to know a tiny catalog doesn't need a retrieval engine.
4. The extra engineering I did on purpose (that costs ~nothing but saves the future)
Here's the nuance that separates a one-off demo from a system you can grow. I added a few things that don't meaningfully move today's cost, but lay the groundwork so the next phase is an addition, not a rewrite. Each one reuses infrastructure I already had.
1. A two-provider abstraction. The bot runs on OpenAI gpt-4o-mini by default and Google Gemini gemini-2.5-flash-lite, behind one interface, switchable by an env var.
// llm.service.ts — one interface, two backends
type LlmProvider = 'openai' | 'gemini';
async *streamChat(systemPrompt: string, messages: LlmMessage[]) {
if (this.provider === 'openai') yield* this.streamOpenAI(systemPrompt, messages);
else yield* this.streamGemini(systemPrompt, messages);
}
Cost today: basically zero (the budget models are within pennies of each other). Payoff: no vendor lock-in, and the seam where automatic failover will later live is already there. To be honest about the limit: today this is a deliberate manual switch, not automatic mid-outage failover — if a provider errors mid-request the user gets a graceful error, and recovery means flipping one env var. Wiring true auto-failover is a small next step (see §7), and I'd rather say that than overclaim it.
2. A retrieval (RAG) seam — built, proven, and deliberately switched off. This is the one I want to be most precise about, because it's where an architect's job is to evaluate, not just build. I added the pgvector extension to the existing PostgreSQL (no separate vector DB, no new bill) and wrote a complete retrieval path with graceful degradation:
// rag.service.ts — graceful degradation baked in
async search(query: string, limit = 3): Promise<string[]> {
try {
const embedding = await this.embeddingService.embed(query);
const results = await this.db.all(
`SELECT content FROM document_embeddings
ORDER BY embedding <=> $1::vector LIMIT $2`, // <=> = cosine distance
[`[${embedding.join(',')}]`, limit]);
return results.map(r => r.content);
} catch (error) {
this.logger.warn(`RAG search failed (non-critical): ${error.message}`);
return []; // fall back to the system prompt
}
}
Then I did the part that actually matters: I evaluated whether it should run — and concluded it shouldn't, not yet. Two reasons:
- It's redundant. The entire 9-product catalog already lives in the prompt, so retrieval can only hand back duplicates of what the model already sees — in exchange for an embedding call on every message.
- It's worse than redundant — it can quietly lower accuracy. The catalog is edited as files that hot-reload into the prompt instantly, but embeddings only re-sync on restart. So right after the founder fixes a price, the live prompt shows the new price while the vector store could still inject the old one as "context." For a bot whose first rule is never state a wrong price, a redundant feature that can resurrect stale data is a net negative.
So I put it behind a flag — RAG_ENABLED, default off — and the system serves every answer straight from the structured prompt. The extension, schema, code, and tests stay in place as a dormant, documented capability with one explicit trigger: switch it on the day there's long-form content that doesn't fit the prompt (a blog, a research library, a big FAQ). That's the honest version of "future-proofing": not shipping an idle feature and hoping, but building the seam, proving it works, and leaving it off until the data earns it. Having the judgment to disable your own code is the senior move — not having written it.
3. A composable, hot-reloading prompt. The system prompt is assembled at runtime from seven independent sections. The founder edits a product or policy file and it reloads with no deploy. Each knowledge area is independent, so updates don't risk the rest.
4. Modular structure + 208 tests. Built on NestJS with dependency injection, so the guardrail stack, the provider abstraction, and the RAG layer are each independently testable and swappable. That's what lets Phase 2/3 features bolt on without touching the core — and what lets me make safety claims with a straight face.
5. Token-usage logging + a /stats endpoint. Every model call's token count is recorded. Today it powers cost circuit breakers; tomorrow it's the raw material for the analytics dashboard, at zero extra cost now.
The theme: build the seams, not the features. None of this inflates the monthly bill. All of it means "when the data grows" is a one-day job instead of a rebuild.
5. How it actually works (the agentic workflow)
"Agentic" doesn't have to mean a model looping over tools. For a health-adjacent bot, an open tool-loop is a liability — unbounded cost and a model improvising near medical topics. What I built is a bounded, deterministic pipeline with the model as one stage inside a wall of controls.
flowchart TD
A[Customer message] --> B{Abuse filter}
B -- toxic/cost-abuse --> Z[Canned safe reply]
B -- ok --> C{Token budget<br/>session / daily / monthly}
C -- exceeded --> Y[Graceful 'come back later' + email]
C -- ok --> D{Medical signals?<br/>keywords + context}
D -- yes --> E[Force escalation<br/>2-layer: keywords + context]
D -- no --> F{Response cache hit?}
F -- yes --> G[Return cached reply]
F -- no --> H[RAG retrieval<br/>dormant · flag-gated · off]
E --> H
H --> I[Compose system prompt<br/>identity + voice + products + policies<br/>+ safety + escalation + security]
I --> J[Stream from LLM<br/>OpenAI or Gemini]
J --> K{Mid-stream output filter<br/>+ hard length cap}
K -- unsafe --> L[Replace with safe text]
K -- ok --> M[Stream token to widget]
M --> N{Escalation phrase?}
N -- yes --> O[Email the founder via Resend]
N -- no --> P[Done]
The decision I care most about: which calls the model is allowed to make, and which are pinned down in deterministic code. Medical questions are force-escalated by a two-layer deterministic check — the operator's exact keyword list, plus hardcoded health-context patterns that catch paraphrases the list misses ("my heart device," "is this safe for me with an implant") while leaving general product-safety questions ("is it safe in the dryer?") answered directly. I will not let the model decide whether a pacemaker question is safe. That line is the entire product.
As-built architecture
graph TB
subgraph Browser
W[Vanilla JS widget<br/>one script tag, SSE]
end
subgraph "NestJS backend"
API[Chat / Escalate controllers]
GUARD[Guardrails<br/>abuse · output filter · budgets · cache]
PROMPT[Prompt composer<br/>7 sections, hot-reload]
LLM[LLM service<br/>OpenAI / Gemini]
RAG[RAG service<br/>pgvector · dormant seam]
ESC[Escalation → email]
end
KB[Knowledge files<br/>products · policies · voice · safety · rules]
PG[(PostgreSQL + pgvector<br/>sessions · tokens · embeddings)]
subgraph External
OAI[OpenAI]
GEM[Google Gemini]
RES[Resend]
end
W -->|HTTPS / SSE| API --> GUARD --> RAG --> PG
GUARD --> PROMPT --> KB
PROMPT --> LLM --> OAI
LLM --> GEM
API --> ESC --> RES
API <--> PG
Stack: NestJS 12 (SSE streaming) · PostgreSQL + pgvector · OpenAI gpt-4o-mini / Gemini gemini-2.5-flash-lite · Resend (email) · ~12KB vanilla-JS widget · Docker / Heroku.
6. How I protected it — and the security frameworks I applied
The moment you expose a chat box to the internet, you open three attack surfaces at once: the classic web/API surface, the LLM-specific surface (prompt injection, prompt extraction, model abuse), and the economic surface (making the model generate expensive output is a denial-of-service). No single control covers all three.
So I didn't invent a security model — I applied established frameworks and mapped controls to them. Here's exactly which, and where:
| Framework | Type | Where it's applied | Controls |
|---|---|---|---|
| STRIDE | Threat modeling (design) | Up front — enumerated spoofing/tampering/info-disclosure/DoS/elevation threats and assigned each a control | Produced the threat register |
| OWASP LLM Top 10 | AI-layer standard | The model stage — prompt injection, insecure output, model DoS, info disclosure, excessive agency | ~8 controls |
| OWASP API Security Top 10 | Web/API standard | Controllers & transport — input validation, rate limiting, error handling, resource limits | ~7 controls |
| Defense in depth | Architectural principle | The whole system — 7 layers, so a bypass at one is caught at the next | 30+ controls total |
| Privacy by design / data minimization | Privacy principle | Data layer — collect the minimum, mask it, auto-delete it | ~5 controls |
Net: 3 formal frameworks + 2 principles, realized as 30+ controls across 7 layers, and backed by 208 tests (two suites are adversarial by design).
The seven layers
Layer 1 — Input: a recursive SanitizePipe strips null bytes/control chars from every field at every nesting depth; a ValidationPipe enforces types, UUID session IDs, and a 1,000-char cap; a pre-LLM abuse filter rejects threats/slurs/hacking before they cost a token.
Layer 2 — API: Helmet security headers (CSP, HSTS, anti-clickjacking); CORS pinned to the one origin; rate limiting (20 req/60s per IP) + max 10 new sessions per IP/hour; a global exception filter that returns sanitized errors (no stack traces).
Layer 3 — AI/LLM (OWASP LLM Top 10):
| OWASP LLM risk | Control |
|---|---|
| LLM01 Prompt Injection | User text delimited as untrusted; security rules hardcoded into the prompt (not loaded from editable files, so a content compromise can't rewrite them); refusal instructions; output filter as a second line |
| LLM02 Insecure Output Handling | Model/user text rendered via textContent, never as HTML, so a reply can't inject a script (innerHTML only for static developer markup); CSP backstop |
| LLM06 Sensitive Info Disclosure | Output filter scans the stream for prompt fragments and secret patterns and swaps the whole reply if matched; the prompt holds no secrets, so extraction leaks nothing |
| LLM04 Model Denial of Service | Cost-abuse pattern filter + token-budget circuit breakers + rate limits + a 10-message history cap |
| LLM08/09 Excessive Agency / Overreliance | No tools, no autonomous actions; medical questions force-escalated by a two-layer deterministic match (exact keywords + health-context patterns), never by model judgment |
The output filter is intentionally blunt — any leak signal → safe canned reply:
private readonly blockedPatterns: RegExp[] = [
/system\s*prompt/i, /my\s*instructions\s*are/i,
/OPENAI_API_KEY/i, /GEMINI_API_KEY/i, /RESEND_API_KEY/i,
/sk-proj-[a-zA-Z0-9]{20,}/, /re_[a-zA-Z0-9]{20,}/, // key shapes
];
Layer 4 — Cost (because "make it talk forever" is a real attack): a dedicated filter catches token-exhaustion prompts ("write 5,000 words", "never stop"), and three-tier budget circuit breakers (per-session / per-day / per-month) stop calling the model when a ceiling is hit. There's no input that produces an unbounded bill.
Layer 5 — Session: crypto.randomUUID() IDs (unguessable), sessions bound to IP + User-Agent, 30-minute timeout, 50-message cap, full isolation between sessions.
Layer 6 — Data (privacy by design): all SQL parameterized; the only PII collected is an email at escalation, and emails are masked in logs (j***[email protected]); transcripts are never dumped to logs (short truncated snippets can appear in debug lines — so the honest claim is minimized and masked, not none); a nightly cron auto-deletes conversations after 30 days.
Layer 7 — RAG (dormant by default): the retrieval seam is off unless explicitly enabled. When it is switched on, hash-based sync re-embeds only changed files so the vector store can't silently serve stale or poisoned knowledge — and because it's gated, the current build has zero retrieval attack surface at all.
The principle underneath all of it: assume input is hostile and the model will be manipulated, and make sure that when something slips one layer, the next one catches it. In this domain the guardrails aren't overhead — they are the product.
7. How I'd improve it next
Shipping is a checkpoint, not the finish line. In priority order:
The bar before I'd call it production-grade (the P0s I won't hand-wave):
- An evaluation harness — this is a launch requirement, not a nice-to-have. I assert high accuracy; nothing measures it continuously. A fixed set of product questions with known-correct answers, plus the adversarial/safety prompts, should run on every knowledge or prompt change and block the deploy on a regression. For prices and safety language, a silent regression is exactly the failure you can't afford — so "highest accuracy" is a claim until this exists.
-
A model swap must re-run that suite. "Provider-switchable" is true at the API layer but not behaviorally —
gpt-4o-miniandgemini-flash-litediffer in voice adherence and safety. Flipping providers is gated on re-running the evals against the new model, never treated as a free config change. - Medical detection needs recall, not just precision. It already runs two deterministic layers (keywords + health-context patterns). That closes the obvious gaps, but deterministic matching has a ceiling; the robust version adds a lightweight LLM intent-classifier as a third layer — accepting its latency/cost precisely because, in this domain, a missed medical question is the one error that actually matters.
Hardening the current build (honest TODOs):
- Automatic mid-request failover. Today the two-provider setup gives portability, not auto-recovery. Catch a provider error and retry on the backup — the abstraction already makes this a small change.
- Trust the proxy, not the client, for IP. Per-IP limits currently read a client-suppliable header; behind a known proxy, configure a trusted hop count so the IP can't be spoofed.
Phase 2 (growth):
- An analytics dashboard on the token/escalation data I'm already logging — top questions, deflection rate, escalation trends.
- Prompt caching for the static system-prompt prefix to shave latency and cost as volume grows.
-
Turn the RAG seam on — correctly — when long-form content arrives. Flip
RAG_ENABLED, and at the same time close the gaps that made it unsafe to run today: index only the long-form docs (never the catalog that's already in the prompt), pin a single embedding provider/dimension (OpenAI 1536-dim vs Gemini 768-dim differ, so a provider switch without re-indexing would break search), and re-embed on file change so retrieval never drifts from the hot-reloaded prompt. The groundwork from §4 means this is a content job, not a rebuild.
Phase 3 (capability):
- This is where it earns the word "agent." Real tools — order-status lookup, inventory, booking a consult — mean function-calling and a bounded multi-step loop become justified, because now the model performs actions with side effects, not just answers.
The takeaways
- Right-sizing is the senior move. The hard part isn't building RAG — it's the judgment to not, and the ability to defend it.
- A plan is a hypothesis; the build is where it meets reality. Writing down why I changed course is what separates engineering from flailing.
- Build the seams, not the features. Cheap options on the future beat expensive bets on it.
- Security is a layer of the architecture, not a checklist at the end — and in a sensitive domain, the guardrails are the product.
The flashy architecture would have taken far longer, been less accurate, and left the founder unable to touch it. The boring-on-purpose one ships in weeks, costs a rounding error to run, defends three attack surfaces at once, and has a clean runway to become a real tool-using agent the day there's an API worth calling.
Knowing the difference is the job.
Building something similar and weighing RAG-vs-prompt, single-vs-multi-provider, or how to lock down an LLM endpoint? Happy to compare notes in the comments.
About the author
I'm Khalid Rasool, a Solution Architect/AI engineer. I design and build LLM-powered products — agentic workflows, RAG systems, and the guardrails that make them safe to ship in production. If this was useful, come say hi:
- LinkedIn: linkedin.com/in/khalidrasool/
- GitHub: github.com/Ranakhalid123
- Website: khalidrasool.com
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.