# Author RAG — Implementation Plan ## AI-Powered Book Sales Chatbot (Multi-Tenant SaaS) **Target directory:** `C:\Users\DELL\Desktop\Author RAG` **Reference project:** `C:\Users\DELL\Desktop\RAGv1v2\RAG 1.2_pushed` (READ-ONLY — no changes will be made) --- ## Background The Author RAG project is a brand-new SaaS platform that deploys a persuasive AI chatbot on any author's website. The bot knows the author's full book catalog (from uploaded summaries/documents), engages visitors in brief conversations, and strategically converts curiosity into purchases — using Cialdini's six principles of persuasion and a 12-step RAG pipeline adapted from the proven HRM chatbot architecture. Unlike the HRM chatbot (which is informational), this bot's **primary KPI is conversion** — turning a casual website visitor into a buyer in 1-3 messages. --- ## Persuasion & Book-Selling Strategy (Research-Backed) The following strategies are baked into the system prompt, upsell engine, and intent pipeline: ### The 6 Cialdini Principles (applied per turn) | Principle | How It's Applied | |---|---| | **Reciprocity** | Bot offers a free teaser quote or hook line before any CTA | | **Scarcity** | Surfaces discount expiry or signed-copy limits from author config | | **Authority** | Injects author accolades, bestseller tags, awards in first response | | **Social Proof** | Cites reader count, reviews, or star ratings from author config | | **Liking** | Speaks in the author's own voice/tone to feel personal | | **Commitment** | Starts with a tiny ask ("Want to hear the first twist?") before the buy CTA | ### Conversion Micro-Tactics 1. **Open Loop / Cliffhanger**: Never reveal the ending; always leave an open question. 2. **Pain → Solution Frame**: "If you've ever felt X, this book is written for you." 3. **Future Pacing**: "Imagine finishing this book in a weekend and finally understanding Y." 4. **Binary Choice Close**: "Would you prefer the ebook now or paperback delivered?" 5. **Urgency Injection**: Time-limited offers only fire if author configured a discount. 6. **Story Interruption**: Share 2 sentences of a gripping scene, then say "that's just Chapter 1." 7. **Reader Identity Anchor**: "Readers like you who love Z typically rate this 5 stars." 8. **The One-Line Pitch**: Every book gets a 1-sentence punchy pitch stored in the author's config. ### What the Bot Will NEVER Do - Reveal the full plot / ending of any book - Fabricate reviews, awards, or claims not in the source document - Pressure users with aggressive language - Discuss competitors' books or redirect to external sites without author permission --- ## Roles & Access Control ### Role Hierarchy ``` SuperAdmin └── Author (one per website) └── Reader (end-user, anonymous) ``` ### Role: SuperAdmin - Full platform control - Can create / suspend / delete Author accounts - Can set global token budgets (per Author) - Can view cross-author analytics - Can revoke API tokens instantly (Redis blacklist) - Requires **TOTP 2FA** on every sensitive action - All actions write to an **immutable audit log** (append-only table, no DELETE) - Can impersonate any Author panel for support - Can configure platform-level rate limits ### Role: Author - Isolated tenant — sees ONLY their own data - Can upload books (PDF, EPUB, DOCX, TXT) — async ingestion - Can view their own chat sessions / reader analytics - Can configure their bot persona (name, avatar, welcome message, tone) - Can configure smart links (buy URL, preview URL, discount code) - Can set purchase urgency messages - Can set book-specific pitches, awards, review snippets - Can manage their own admin password (enforced strength policy) - Can export chat logs (Excel / JSON) - Can block/unblock individual reader sessions - Cannot access other authors' data - Subject to token budget enforced by SuperAdmin ### Role: Reader (End User) - Anonymous — identified by SHA-256 fingerprint (IP + UA), no PII stored - Can chat with the bot (subject to rate limiting) - Can rate the conversation (1-5 stars) - Can start new chat threads --- ## Complete Feature List ### 🔐 Security & Authentication 1. SuperAdmin TOTP 2FA (pyotp) — required for all sensitive actions 2. Author login: username + password + OTP via email (SMTP) 3. JWT session tokens for Author panel (short-lived + refresh) 4. HMAC-signed widget tokens (validates domain origin) 5. Redis revocation blacklist for instant token invalidation 6. 5-layer API token validation: HMAC → Expiry → Redis blacklist → DB record → Token budget 7. Timing-safe credential comparison (`secrets.compare_digest`) 8. Brute-force lockout after 5 failed login attempts (per IP, 15-minute lockout) 9. Immutable SuperAdmin audit log (append-only SQLite table) 10. Fail-safe rate limiter: Redis sliding window, falls back to in-memory if Redis crashes 11. CORS domain whitelist — widget API only accepts requests from the Author's registered domain 12. Input guardrails: blocks 10+ jailbreak / prompt-injection patterns 13. Output boundary check: ensures system prompt was never leaked ### 📚 Document Ingestion 14. Upload: PDF, EPUB, DOCX, TXT — validated by magic bytes (not just extension) 15. Async processing via background threads (Celery-ready, threading fallback) 16. Real-time SSE progress bar (chunking → embedding → indexing) 17. Per-book ChromaDB collection (isolated per Author tenant) 18. Configurable chunk size & overlap per Author 19. Auto-generated book summary on upload (LLM-powered, stored as metadata) 20. Support for multiple books per Author (multi-book catalog) 21. Book metadata: title, genre, author name, publication year, price, buy URL, preview URL, discount code, one-line pitch, awards, review snippets 22. Delete / re-ingest a book (full re-embedding) ### 🤖 12-Step RAG Pipeline (adapted for book sales) 23. **Step 1 — Context Injection**: Author tone, persona, style preferences, active books 24. **Step 2 — Intent Classification**: Detects query type (book Q&A, price inquiry, character question, plot question, buy intent, comparison, series/sequel question, general greeting) 25. **Step 3 — Query Rewriting**: Optimizes raw query for vector search 26. **Step 4 — Input Guardrails**: Blocks jailbreak / off-topic patterns 27. **Step 5 — Retrieval**: `all-MiniLM-L6-v2` + ChromaDB, per-tenant collection 28. **Step 6 — Reranking**: CrossEncoder rescoring (`cross-encoder/ms-marco-MiniLM-L-6-v2`) 29. **Step 7 — Prompt Assembly**: System prompt + history + ranked chunks + upsell config 30. **Step 8 — LLM Generation**: Streaming via OpenAI / Groq / Fireworks / HuggingFace 31. **Step 9 — Faithfulness Check (NLI)**: `deberta-v3-small` verifies answer is grounded in book text 32. **Step 10 — Output Boundary Check**: Detects system prompt leakage or competitor mentions 33. **Step 11 — Upsell Engine**: Analyzes conversation turn number + detected buy intent → injects relevant CTA, smart link, or discount code 34. **Step 12 — Formatter**: Cleans markdown, enforces short/concise reply style ### 🎯 Upsell Engine Logic 35. Turn 1: Focus on curiosity / hook (no hard sell) 36. Turn 2: Introduce value + social proof (soft CTA) 37. Turn 3+: Active CTA with buy link + urgency message (if configured) 38. Buy-intent signal detected at any turn → immediate smart link injection 39. Price question → instant buy link + value justification 40. Series/sequel question → cross-sell to next book 41. Configurable: Author can disable/enable upsell per book 42. A/B testing slot for CTA variants (stored, switchable from admin) ### 📊 Analytics & Tracking 43. Anonymous fingerprinting: SHA-256(IP + UA) — no PII 44. Per-session tracking: intent detected, tokens used, latency, faithfulness score 45. Per-book analytics: views, clicks, buy-link clicks (UTM tracking) 46. Geo-location: MaxMind GeoLite2 (country-level only) 47. Hourly aggregation Celery Beat job → daily dashboard charts 48. Conversion funnel: impression → engagement → buy-link click 49. Export analytics: CSV / Excel 50. SuperAdmin global analytics dashboard (cross-author) ### 🎨 Chat Widget (Author-Customizable) 51. Bot name, avatar image upload 52. Welcome message (custom per book landing page) 53. Widget position: bottom-right / bottom-left / center 54. Theme: light / dark / custom hex colors 55. Fallback behavior when bot can't answer 56. Widget embed via `` - Auto-initializes on page load - Reads `data-author` and `data-token` attributes - Validates signed token on first message (backend verifies HMAC + domain) - Persistent session via localStorage - SSE polling for admin live replies - Typing indicator, delivery ticks, star rating --- ### Entry Point & Deployment #### [NEW] `app/main.py` - FastAPI app factory - Mounts all routers - Startup: loads ChromaDB, downloads models, creates DB tables - Lifespan events (replaces deprecated `@app.on_event`) #### [NEW] `Dockerfile` ```dockerfile FROM python:3.11-slim # Pre-download models during build RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('all-MiniLM-L6-v2')" RUN python -c "from sentence_transformers.cross_encoder import CrossEncoder; CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')" RUN python -c "from sentence_transformers.cross_encoder import CrossEncoder; CrossEncoder('cross-encoder/nli-deberta-v3-small')" ``` #### [NEW] `requirements.txt` ``` fastapi uvicorn[standard] chromadb sentence-transformers pydantic-settings pydantic[email] pypdf2 ebooklib python-docx python-dotenv numpy httpx python-multipart pandas openpyxl rank_bm25 bcrypt python-jose[cryptography] pyotp qrcode[pil] aiosqlite redis[asyncio] celery[redis] geoip2 maxminddb ``` --- ## Verification Plan ### Automated Checks - `uvicorn app.main:app --reload` — server starts without errors - All import paths resolve (no circular imports) - `.env.example` covers all required settings ### Manual Verification (Post-Build) 1. SuperAdmin login with TOTP → create Author account 2. Author login → upload a book (PDF) → see SSE progress bar 3. Open widget → chat as reader → verify upsell fires on turn 3 4. Admin panel → block reader → verify reader gets 403 5. Admin panel → live takeover → verify admin reply appears in widget 6. SuperAdmin → audit log shows all actions 7. Rate limiter → send >60 requests/min → verify 429 --- ## Open Questions > [!IMPORTANT] > **Q1 — Widget Hosting**: Should the chat widget be hosted on the same HF Space URL, or should authors embed a separate JS snippet that calls back to the space? (Recommended: single space, embed via `