Build Your Own ChatGPT Wrapper Safely — Architecture, Auth, Rate Limit, Logging

Manish Garg
Manish Garg Associate of (ISC)² · RingSafe
Apr 29, 2026
10 min read
Read as
Half the SaaS launches in 2024-2025 were “ChatGPT for X.” Most shipped with embarrassing security gaps: hardcoded API keys, no rate limiting, no abuse logging, prompt injection that leaks system prompts. This module is the production architecture for a chat wrapper that does not embarrass you when it gets popular.

A “ChatGPT wrapper” sounds trivial: take user input, send to OpenAI/Anthropic, return response. The minimal version is 30 lines of Python. The production version handles auth, billing, abuse, prompt injection, content moderation, observability, kill-switches, and PII redaction. This module gives you the reference architecture that costs 200 lines of code and saves you from the most common public failures.

The minimum viable architecture

Three components. Frontend: chat UI (Vercel AI SDK works well). Sends user message to your backend. Never calls OpenAI directly — that would expose the API key. Backend: REST endpoint that validates user auth, applies rate limit, does pre-flight content moderation, calls OpenAI/Anthropic with constructed prompt, post-flight moderates response, streams back. Logging + observability: every request logged with user_id, prompt hash, token counts, model version, latency, cost. Stack: Next.js app router + Vercel AI SDK + Supabase auth + Redis (Upstash) for rate limit + Sentry for errors + LangSmith or Helicone for AI observability.

API key management — the most common breach

Top causes of leaked OpenAI keys in 2024: (1) committed to GitHub; (2) shipped in client-side JavaScript; (3) logged in plaintext in error responses. Hardening: store key in environment variable accessed only by backend; never embed in NEXT_PUBLIC_*; use Vercel/AWS secrets manager not .env in repo; rotate quarterly; set per-key spending limits in OpenAI dashboard ($500/mo cap is sane for most apps); enable usage anomaly alerts. If you discover a leak, rotate immediately and investigate scope. OpenAI now scans GitHub for exposed keys and auto-revokes; do not rely on this.

Rate limiting — bot abuse will find you

Within 24 hours of public launch, every chat wrapper gets crawler-style abuse — bots probing for free LLM access. Without rate limit, your $200 in OpenAI credit evaporates overnight. Implement two layers. IP-based: 60 requests/hour per IP, sliding window. Cloudflare WAF or Upstash + Vercel Edge Function. User-based: 100 messages/day per authenticated user, 10 per minute burst. Track in Redis counters. Free-tier users get tighter limits than paid. Token-based budget: each user has a daily token quota; sum input+output tokens per request. When exceeded, return graceful “limit reached” rather than silently failing. Critical: rate limit BEFORE you call OpenAI, not after — otherwise you eat the cost regardless.

Prompt construction — minimise system-prompt leakage

Your system prompt is your IP. It will be extracted via prompt injection. Mitigations: (1) keep the system prompt simple and not contain proprietary information; (2) put the user message in a clearly delimited section (<user_message>...</user_message>); (3) use models that support better instruction-data separation (Claude 3.5+ has explicit boundaries; OpenAI Assistants API has separate instructions field); (4) accept that the system prompt will eventually leak — design accordingly. Do NOT put secrets in the system prompt. Do NOT put internal pricing rules. Do NOT put information you would not want pasted on Twitter.

Content moderation — both directions

Two classes of harm. (1) Inbound: user sends harmful prompt — child sexual abuse material, weapons synthesis instructions, illegal content. Run user input through OpenAI Moderation API or Llama Guard before sending to the main model. Reject hard-positive matches with a generic error. (2) Outbound: model emits harmful content. Run model response through the same moderation before returning to user. Two-pass adds ~100ms latency; worth it. Indian-context additions: filter for content that violates IT Act §66 (defamation, hate speech), Information Technology Rules 2021, and local cultural sensitivity rules per your platform’s ToS. Open-source moderation models do not catch these by default; you may need to train a domain-specific classifier.

Observability — what to log, what NOT to log

Log per request: request_id, user_id (hashed if needed), model_name, model_version, prompt_template_id, input_token_count, output_token_count, total_cost_usd, latency_ms, finish_reason, moderation_result, error_class. Do NOT log: full prompt content (PII risk); full response (PII + IP risk); raw API key. For debugging, log hash of prompt + first 50 chars masked. For abuse investigation, you can re-derive the prompt from your prompt_template_id + variables. Tools: Helicone (proxy that auto-instruments), Langfuse (open source observability), or roll your own with Postgres + jsonb. Cost dashboards: track per-user cost; alert on user exceeding 10× their P95 daily.

Cost discipline — the engineering decisions that matter

Five tactics that cut API spend 40-70% with minimal UX impact. (1) Tiered models — use cheap GPT-4o-mini for first-pass; only escalate to GPT-4o for genuinely hard queries (route based on query complexity classifier). (2) Prompt caching — Anthropic and OpenAI both support caching repeated context; for chatbots with long system prompts, this saves 50%+ on input tokens. (3) Streaming + early stop — let user see tokens as they generate; if their question was already answered in 50 tokens, the rest is wasted; UX-driven stop saves money. (4) Output token caps — set max_tokens=500 default; raise only when needed. (5) Embeddings cache — for RAG, hash query+doc-version, cache embeddings forever (they do not change). Saves repeated embedding API calls on the same content.

Reference architecture — production chatbot with auth, logging, rate limit

Stack: Frontend Next.js 15 with the AI SDK for streaming. Edge layer Cloudflare Workers or Vercel Edge Functions for IP-based rate limit (use Cloudflare Turnstile to filter bots). API layer Node/Hono or Python/FastAPI with: (a) authentication via Clerk / Supabase Auth / NextAuth (verify JWT on every request); (b) per-user token-bucket rate limit (Upstash Redis is free tier and fast); (c) input length cap and content-type check; (d) prompt construction with delimiters separating system prompt from user input. LLM layer via LiteLLM gateway pointing at Anthropic / OpenAI / Bedrock; gateway handles retries, fallback, prompt cache, cost tracking. Logging every conversation to your DB with: user-id, timestamp, input hash, output hash, model used, token count, cost. Output filtering via Llama Guard 2 or NVIDIA NeMo Guardrails before returning to user. Storage Postgres for users + history (Supabase or Neon). Total monthly cost at MVP scale: $20-100. Time to production: 2-3 weeks for an experienced full-stack engineer. This is the bare-minimum production stack — anything less and you are pre-production.

Operational playbook — what breaks first and how to fix

In production order: (1) Cost always breaks first — a bug or abuse causes runaway token spend. Mitigate: hard daily spend cap per user (refuse with friendly error when hit) + total daily cap on the account + alarms on cost-vs-trend. (2) Latency degrades when a model has an outage; multi-provider failover via LiteLLM is required. (3) Quality regression when you upgrade models — eval on a frozen test set before promoting. (4) Abuse — someone tries to use your wrapper for unrelated content (jailbreak attempts, off-topic spam). Add intent classification at edge and refuse off-topic. (5) Data leak — a user reports another user’s data appearing in their chat (PostHog had this in 2023 with inadequate session isolation). Mitigate: never share LLM context across users; clear per-session; audit all multi-tenant boundaries. (6) Prompt injection — covered in the dedicated module. Plan for each of these before launch; you do not get to ship “we will fix it later” once a regulator or paying customer is involved.

Indian payment + onboarding — Razorpay, UPI, GST for AI products

Building an AI SaaS for Indian customers requires a India-native commerce layer. Payments: Razorpay (most popular, supports cards + UPI + netbanking + wallets, ~2% MDR), Cashfree, Stripe India (for international flows). UPI is the dominant retail method — must work first-try. Subscription billing: Razorpay Subscriptions for recurring; otherwise roll your own via webhooks + state machine in Postgres. GST: AI services are taxable at 18% IGST/CGST+SGST. Charge GST on B2C invoices; B2B requires GSTIN capture and reverse-charge handling for international vendors. Invoice format: must include GSTIN, HSN/SAC code (998314 for IT services), state, place of supply. Auto-generate via Razorpay/Zoho Books integration. TDS: Indian B2B customers may withhold TDS; provide PAN; reconcile quarterly. Currency: charge INR domestically; multi-currency for international customers. Onboarding KYC: for B2B SaaS, GSTIN verification suffices; for fintech-adjacent products that touch financial data, full KYC (PAN + Aadhaar via DigiLocker / Aadhaar OTP) may be required by partner banks. Receipt requirements: tax invoice within 30 days; e-invoicing required if turnover > ₹5cr. Free trial: India market expects generous free tiers; conversion at ~3-7% from free-to-paid is healthy. Pricing psychology: ₹999/month perceived very differently than ₹1,000/month — same as $9.99 vs $10. Avoid USD pricing unless your customer is global. Support: WhatsApp Business is non-negotiable for Indian SMB customers; integrate via Twilio or 360dialog. None of this is AI-specific, but ignoring it kills Indian SaaS launches faster than feature gaps.

Boilerplate — copy-pasteable production AI app skeleton (Next.js + Hono)

A minimal but production-real starter. Stack: Next.js 15 frontend, Hono API, Anthropic SDK, Supabase auth + DB + Redis (via Upstash). API route (Hono, edge): app.post('/chat', authMiddleware, rateLimit({windowMs:60000, max:10}), async (c) => { const {message} = await c.req.json(); if (message.length > 4000) return c.text('too long', 400); const userId = c.get('userId'); const dailyTokens = await redis.get('tokens:'+userId); if (dailyTokens > 100000) return c.text('daily cap exceeded', 429); const stream = await anthropic.messages.stream({model: 'claude-haiku-4-5-20251001', system: SAFE_SYSTEM_PROMPT, messages: [{role:'user', content: message}], max_tokens: 1024}); /* stream to client; track usage */ }). Auth middleware: verify JWT from Supabase; set userId in context; reject expired. Rate limit: token bucket in Redis; 10 requests / minute / user; 100k tokens / day / user. Logging: every conversation to conversations table — user_id, timestamp, input_hash, output_hash, model, input_tokens, output_tokens, cost_cents. Use hashes instead of raw text if PII-sensitive. Output filter: pass response through Llama Guard 2 (self-hosted on Modal or via Anthropic Workbench); block on high-confidence policy violation; log all blocks. System prompt: short, declarative, scope-limiting. Avoid “do not do X” — prefer “you only help with Y”. Frontend: Vercel AI SDK useChat hook + Zod schema validation on inputs. Cost monitoring: Posthog or Langfuse logs each call; daily report to Slack; alert on cost > 2x trailing 7-day average. Deploy: Vercel for frontend + API edge (free tier covers MVP); Supabase free tier for DB + auth; Upstash free tier for Redis. Total time: 2 weekends for a competent full-stack engineer. Repo template: search “Vercel AI SDK starter” + “Anthropic SDK example”; both vendors maintain quality starters.

FAQ

OpenAI vs Anthropic vs self-hosted for a wrapper?

For most apps: Anthropic Claude (best safety + tool use), with OpenAI as fallback. Self-hosted only when DPDP / data sovereignty mandates it. Multi-provider (LiteLLM proxy) lets you swap or A/B test cheaply.

How do I stop "ignore previous instructions" from leaking my prompt?

You cannot stop it 100%. Reduce by: using Claude or GPT-4o (better resistance), framing user input clearly as data not instructions, keeping system prompt minimal so leak damage is small. Accept it will sometimes leak.

What is a sane MVP launch budget?

$50/mo if you cap per-user usage tightly. $500/mo for early traction (100 active users). $5K+ for serious volume. Set spend alerts at every level — most “AI startup blew up its credit” stories are missing alerts.

How do I set a per-user spend cap?

Track tokens-per-user in Redis with a daily key. On every LLM call, increment by the API’s usage report (Anthropic and OpenAI both return token counts). Refuse new calls when above cap. For free tiers, set conservative limits (10k tokens/day = ~$0.05); for paid, scale with subscription. Reset daily via Redis TTL. This is a 50-line change; do it before you have abuse, not after.

What is the cheapest model that is "good enough" for a customer support chatbot?

In 2026: Claude Haiku 3.5 ($0.25/$1.25 per M tokens), Llama 3.3 70B via Together AI ($0.88/$0.88), or GPT-4o-mini ($0.15/$0.6) are all competent. Cheaper local Llama 3.1 8B can work for narrow domains after fine-tuning. The wrong question is “cheapest” — ask “cheapest that meets quality bar on my eval set.” Set up a 100-question eval, benchmark candidates, pick the cheapest above quality threshold.


⚖️ Legal: Use AI security techniques only on systems you own or have explicit written authorisation to test. In India, unauthorised access is punishable under IT Act §66 (up to 3 years + fine). Pair AI red-teaming with signed Statement of Work or Rules of Engagement before testing.

Need help with this?

Book a free 30-minute scoping call

Our senior consultants will review your stack and tell you honestly what to fix first. No slide deck. No obligation. Indian businesses only.

Book scoping call Replies in 4 working hrs · India-only · Senior consultants