Spaces:
Running
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
- Open Loop / Cliffhanger: Never reveal the ending; always leave an open question.
- Pain β Solution Frame: "If you've ever felt X, this book is written for you."
- Future Pacing: "Imagine finishing this book in a weekend and finally understanding Y."
- Binary Choice Close: "Would you prefer the ebook now or paperback delivered?"
- Urgency Injection: Time-limited offers only fire if author configured a discount.
- Story Interruption: Share 2 sentences of a gripping scene, then say "that's just Chapter 1."
- Reader Identity Anchor: "Readers like you who love Z typically rate this 5 stars."
- 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
- SuperAdmin TOTP 2FA (pyotp) β required for all sensitive actions
- Author login: username + password + OTP via email (SMTP)
- JWT session tokens for Author panel (short-lived + refresh)
- HMAC-signed widget tokens (validates domain origin)
- Redis revocation blacklist for instant token invalidation
- 5-layer API token validation: HMAC β Expiry β Redis blacklist β DB record β Token budget
- Timing-safe credential comparison (
secrets.compare_digest) - Brute-force lockout after 5 failed login attempts (per IP, 15-minute lockout)
- Immutable SuperAdmin audit log (append-only SQLite table)
- Fail-safe rate limiter: Redis sliding window, falls back to in-memory if Redis crashes
- CORS domain whitelist β widget API only accepts requests from the Author's registered domain
- Input guardrails: blocks 10+ jailbreak / prompt-injection patterns
- Output boundary check: ensures system prompt was never leaked
π Document Ingestion
- Upload: PDF, EPUB, DOCX, TXT β validated by magic bytes (not just extension)
- Async processing via background threads (Celery-ready, threading fallback)
- Real-time SSE progress bar (chunking β embedding β indexing)
- Per-book ChromaDB collection (isolated per Author tenant)
- Configurable chunk size & overlap per Author
- Auto-generated book summary on upload (LLM-powered, stored as metadata)
- Support for multiple books per Author (multi-book catalog)
- Book metadata: title, genre, author name, publication year, price, buy URL, preview URL, discount code, one-line pitch, awards, review snippets
- Delete / re-ingest a book (full re-embedding)
π€ 12-Step RAG Pipeline (adapted for book sales)
- Step 1 β Context Injection: Author tone, persona, style preferences, active books
- Step 2 β Intent Classification: Detects query type (book Q&A, price inquiry, character question, plot question, buy intent, comparison, series/sequel question, general greeting)
- Step 3 β Query Rewriting: Optimizes raw query for vector search
- Step 4 β Input Guardrails: Blocks jailbreak / off-topic patterns
- Step 5 β Retrieval:
all-MiniLM-L6-v2+ ChromaDB, per-tenant collection - Step 6 β Reranking: CrossEncoder rescoring (
cross-encoder/ms-marco-MiniLM-L-6-v2) - Step 7 β Prompt Assembly: System prompt + history + ranked chunks + upsell config
- Step 8 β LLM Generation: Streaming via OpenAI / Groq / Fireworks / HuggingFace
- Step 9 β Faithfulness Check (NLI):
deberta-v3-smallverifies answer is grounded in book text - Step 10 β Output Boundary Check: Detects system prompt leakage or competitor mentions
- Step 11 β Upsell Engine: Analyzes conversation turn number + detected buy intent β injects relevant CTA, smart link, or discount code
- Step 12 β Formatter: Cleans markdown, enforces short/concise reply style
π― Upsell Engine Logic
- Turn 1: Focus on curiosity / hook (no hard sell)
- Turn 2: Introduce value + social proof (soft CTA)
- Turn 3+: Active CTA with buy link + urgency message (if configured)
- Buy-intent signal detected at any turn β immediate smart link injection
- Price question β instant buy link + value justification
- Series/sequel question β cross-sell to next book
- Configurable: Author can disable/enable upsell per book
- A/B testing slot for CTA variants (stored, switchable from admin)
π Analytics & Tracking
- Anonymous fingerprinting: SHA-256(IP + UA) β no PII
- Per-session tracking: intent detected, tokens used, latency, faithfulness score
- Per-book analytics: views, clicks, buy-link clicks (UTM tracking)
- Geo-location: MaxMind GeoLite2 (country-level only)
- Hourly aggregation Celery Beat job β daily dashboard charts
- Conversion funnel: impression β engagement β buy-link click
- Export analytics: CSV / Excel
- SuperAdmin global analytics dashboard (cross-author)
π¨ Chat Widget (Author-Customizable)
- Bot name, avatar image upload
- Welcome message (custom per book landing page)
- Widget position: bottom-right / bottom-left / center
- Theme: light / dark / custom hex colors
- Fallback behavior when bot can't answer
- Widget embed via
<script>tag with Author's signed token - Mobile-responsive widget
- Typing indicator animation
- Message delivery ticks
- Star rating at end of conversation
π₯ Multi-Tenant Author Admin Panel
- Dashboard: total readers, total conversations, conversion rate, avg session length
- Book manager: upload, edit metadata, delete, re-ingest
- Session viewer: read all reader transcripts
- Block / unblock readers
- Reply to readers manually (live agent takeover)
- End chat / archive session
- Widget config (name, avatar, colors, position, welcome message)
- Smart Links manager (buy URL, preview URL, discount code, urgency message)
- Analytics page (charts: daily readers, top books, top intents, geo map)
- Export chats (Excel / JSON)
- Password change (self-service)
- API settings (LLM provider choice per Author)
- Subscription info (token budget, expiry β read-only, managed by SuperAdmin)
π‘οΈ SuperAdmin Panel
- Manage Author accounts: create, suspend, delete
- Set token budgets per Author (monthly / total)
- Extend / revoke Author subscriptions
- Impersonate Author panel (read-only support mode)
- View cross-author analytics
- Platform-wide rate limit settings
- Audit log viewer (immutable β no delete)
- Platform health dashboard (Redis status, ChromaDB status, LLM status)
- Broadcast announcement to all Authors (shown in their admin panel)
π οΈ Deployment & Infrastructure
- Hugging Face Spaces ready (custom Dockerfile)
- Pre-downloaded models baked into Docker image (no cold-start)
- ChromaDB for vector storage (per-tenant collections)
- Redis for rate limiting, token blacklist, pub/sub (SSE progress)
- SQLite for Author accounts, audit log, subscription data
- Full async: FastAPI + asyncpg (or aiosqlite) + Redis.asyncio
- Celery (with Redis broker) for async ingestion + scheduled aggregation
- Environment-based config (
.env) β no secrets in code
Architecture Overview
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Author RAG Platform β
ββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββββββββββββ€
β SuperAdmin Panel β Author Admin Panel (per tenant) β
β /superadmin β /admin/{author_slug} β
β TOTP 2FA required β JWT + OTP auth β
ββββββββββββββββββββββββββββ΄ββββββββββββββββββββββββββββββββββββββββββββββββββ€
β FastAPI Backend β
β ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ ββββββββββββββββββ β
β β Chat API β β Ingestion APIβ β Admin API β β SuperAdmin API β β
β β /api/chat β β /api/ingest β β /api/admin/* β β /api/super/* β β
β ββββββββ¬ββββββββ ββββββββ¬ββββββββ ββββββββββββββββ ββββββββββββββββββ β
β β β β
β ββββββββΌββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β 12-Step RAG Pipeline β β
β β ContextβIntentβRewriteβGuardβRetrieveβRerankβAssembleβLLMβ β β
β β FaithfulnessβBoundaryCheckβUpsellβFormat β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β€
β Storage β
β ChromaDB (per-tenant) β SQLite (accounts, audit) β Redis (cache/rate) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Proposed File Structure
C:\Users\DELL\Desktop\Author RAG\
β
βββ app/
β βββ __init__.py
β βββ main.py # FastAPI app factory, startup
β β
β βββ core/
β β βββ __init__.py
β β βββ config.py # Pydantic settings (env-based)
β β βββ database.py # SQLite/aiosqlite setup + migrations
β β βββ security.py # TOTP, JWT, HMAC, password hashing utils
β β
β βββ models/
β β βββ __init__.py
β β βββ author.py # Author account model
β β βββ book.py # Book metadata model
β β βββ session.py # Reader session model
β β βββ audit.py # Immutable audit log model
β β
β βββ services/
β β βββ __init__.py
β β βββ embeddings.py # SentenceTransformer wrapper
β β βββ vector_store.py # ChromaDB per-tenant client
β β βββ reranker.py # CrossEncoder reranker
β β βββ llm.py # Multi-provider LLM service
β β βββ rag_pipeline.py # 12-step pipeline
β β βββ upsell_engine.py # Upsell logic & CTA injection
β β βββ faithfulness.py # DeBERTa NLI faithfulness check
β β βββ guardrails.py # Input/output guard patterns
β β βββ ingestion.py # Async file parsing + chunking
β β βββ session_store.py # Reader session CRUD (JSON files)
β β βββ rate_limiter.py # Redis sliding window + fallback
β β βββ analytics.py # Event tracking + aggregation
β β βββ notifications.py # Email (SMTP) notifications
β β
β βββ api/
β β βββ __init__.py
β β βββ schemas.py # Pydantic request/response schemas
β β βββ chat.py # /api/chat endpoints
β β βββ ingest.py # /api/ingest endpoints (SSE progress)
β β βββ widget.py # /api/widget/token (signed embed tokens)
β β
β βββ superadmin/
β β βββ __init__.py
β β βββ router.py # /api/super/* endpoints
β β βββ templates/
β β βββ superadmin.html # SuperAdmin SPA
β β
β βββ admin/
β βββ __init__.py
β βββ router.py # /api/admin/* endpoints (per-author)
β βββ templates/
β βββ admin.html # Author Admin SPA
β
βββ static/
β βββ widget.js # Embeddable chat widget script
β βββ widget.css # Widget styles
β βββ addon.html # Standalone widget test page
β
βββ data/
β βββ index/ # ChromaDB persistence
β βββ sessions/ # Reader session JSON files
β βββ author_rag.db # SQLite: authors, books, audit log
β
βββ docs/ # Default book document storage
β
βββ Dockerfile # HF Spaces compatible
βββ docker-compose.yml # Local dev with Redis
βββ requirements.txt
βββ .env.example
βββ app.py # Entry point (uvicorn)
βββ README.md
Proposed Changes (Component by Component)
Core Infrastructure
[NEW] app/core/config.py
Extended settings for multi-tenant Author RAG:
SUPERADMIN_USER,SUPERADMIN_PASS,SUPERADMIN_TOTP_SECRETJWT_SECRET_KEY,JWT_ALGORITHM,JWT_EXPIRE_MINUTESREDIS_URL(for rate limiting, blacklist, pub/sub)CHROMA_PERSIST_DIR(ChromaDB storage path)DB_PATH(SQLite path)MAXMIND_DB_PATH(GeoLite2)- All LLM provider keys (same as reference project)
FAITHFULNESS_MODEL=cross-encoder/nli-deberta-v3-smallEMBEDDING_MODEL=all-MiniLM-L6-v2
[NEW] app/core/database.py
SQLite schema via aiosqlite:
authorstable: id, slug, name, email, password_hash, totp_secret, token_budget, tokens_used, subscription_expiry, suspended, created_atbookstable: id, author_id, title, genre, pub_year, price, buy_url, preview_url, discount_code, pitch, awards, reviews_json, ingested_at, statusaudit_logtable: id, actor, action, target, detail, timestamp β NO DELETE allowed via app layerannouncementstable: id, message, created_at, created_by
[NEW] app/core/security.py
hash_password()/verify_password()via bcryptcreate_jwt()/verify_jwt()generate_totp_secret()/verify_totp(token, secret)sign_widget_token(author_slug, domain)/verify_widget_token()hmac_sign()/hmac_verify()
Services Layer
[NEW] app/services/rag_pipeline.py
The 12-step pipeline adapted for book sales:
- Replaces HRM-specific intent map with a book-sales intent map:
BOOK_QA,PRICE_INQUIRY,BUY_INTENT,CHARACTER_QUESTION,PLOT_QUESTION,SERIES_QUESTION,COMPARISON,GENERAL_GREETING - Author tone + persona injected at Step 1
- Faithfulness check at Step 9 (DeBERTa NLI)
- Upsell Engine called at Step 11
[NEW] app/services/upsell_engine.py
Rules:
- Turn 1: Hook β free teaser quote β NO buy link
- Turn 2: Value frame + social proof β soft CTA ("learn more")
- Turn 3+: Hard CTA with buy_url + urgency_message (if set)
- Any turn: BUY_INTENT detected β immediate smart link
- Any turn: PRICE_INQUIRY β buy_url + value justification
- SERIES_QUESTION: cross-sell next book in series
[NEW] app/services/faithfulness.py
- Uses
cross-encoder/nli-deberta-v3-small - Returns entailment probability score
- If score < threshold β strips the hallucinated claim from reply
[NEW] app/services/guardrails.py
- Input patterns: same 10+ jailbreak patterns from reference + book-specific off-topic blocks (e.g., "write this book for free", "give me a pirated copy")
- Output patterns: detects system prompt leakage, competitor book mentions
[NEW] app/services/vector_store.py
- ChromaDB client (replaces FAISS from reference)
- Per-author, per-book collection naming:
author_{slug}_book_{id} - Supports multi-book search (queries all author's collections)
- Hybrid search: dense (embedding) + sparse (BM25) + RRF fusion
[NEW] app/services/ingestion.py
- Magic byte validation (PDF=
%PDF, EPUB=PK header, DOCX=PK header) - Parse: PyPDF2 (PDF), ebooklib (EPUB), python-docx (DOCX), plain text
- Chunking: sentence-aware, 350 tokens, 80 overlap
- Redis Pub/Sub SSE events:
{stage: "chunking", progress: 45} - Auto-summary generation via LLM after ingestion
[NEW] app/services/analytics.py
track_event(author_id, book_id, event_type, session_id, metadata)- Event types:
chat_start,message,buy_link_click,rating - SHA-256 fingerprinting:
hash(ip + user_agent) - MaxMind GeoLite2 lookup (country only)
aggregate_daily()β Celery Beat task, hourly
API Layer
[NEW] app/api/chat.py
POST /api/chat/{author_slug}β main chat endpoint (widget calls this)POST /api/chat/{author_slug}/session/initGET /api/chat/{author_slug}/session/history/{session_id}POST /api/chat/{author_slug}/session/ratePOST /api/chat/{author_slug}/session/resetGET /api/chat/{author_slug}/eventsβ SSE for ingestion progress
[NEW] app/api/ingest.py
POST /api/admin/{author_slug}/books/uploadGET /api/admin/{author_slug}/books/upload/progressβ SSE stream
[NEW] app/api/widget.py
GET /api/widget/token?slug={author_slug}&domain={domain}β returns signed widget tokenGET /widget/{author_slug}β serves the embeddable widget HTML
Admin Panel (Per Author)
[NEW] app/admin/router.py
All routes require valid JWT for the specific Author:
- Dashboard, session list/detail, block/unblock, takeover, reply
- Book CRUD, widget config, smart links, analytics, exports
- Password change endpoint
[NEW] app/admin/templates/admin.html
Single-page application with:
- Sidebar nav: Dashboard, Books, Readers, Widget Config, Analytics, Settings
- Book upload drag-and-drop with live progress bar
- Reader session list with search + filter
- Real-time chart (Chart.js): daily readers, top books, conversion funnel
- Widget configurator: live preview of chat widget
SuperAdmin Panel
[NEW] app/superadmin/router.py
All routes require SuperAdmin JWT + TOTP verification header:
- Author CRUD (create, suspend, delete)
- Token budget management
- Impersonation (read-only)
- Audit log viewer
- Platform health dashboard
- Broadcast announcements
[NEW] app/superadmin/templates/superadmin.html
- Minimal, high-security design
- All destructive actions require re-entry of TOTP code
- Audit log displayed as immutable feed
Chat Widget
[NEW] static/widget.js
- Embed via
<script src="https://your-space.hf.space/static/widget.js" data-author="slug" data-token="signed_token"></script> - Auto-initializes on page load
- Reads
data-authoranddata-tokenattributes - 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
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.examplecovers all required settings
Manual Verification (Post-Build)
- SuperAdmin login with TOTP β create Author account
- Author login β upload a book (PDF) β see SSE progress bar
- Open widget β chat as reader β verify upsell fires on turn 3
- Admin panel β block reader β verify reader gets 403
- Admin panel β live takeover β verify admin reply appears in widget
- SuperAdmin β audit log shows all actions
- Rate limiter β send >60 requests/min β verify 429
Open Questions
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
<script>tag withdata-authorattribute.)
Q2 β Multi-Book Search Strategy: When a reader asks a general question not tied to a specific book, should the bot search ALL of the author's books and pick the best match, or ask the reader which book they mean first? (Recommended: search all, pick best β more seamless.)
Q3 β Redis Requirement: Redis is needed for rate limiting, token blacklist, and SSE. Is Redis available on your deployment environment? If not, we can implement fallback in-memory alternatives for all three (same as reference project's in-memory rate limiter pattern).
Q4 β Faithfulness Model Size:
cross-encoder/nli-deberta-v3-smalladds ~180MB to the Docker image and ~200ms per response. If this is too slow, we can make it optional (admin toggle per Author). Shall we include it by default?
Q5 β Gradio UI: The reference project uses Gradio for a testing UI. Should we keep a Gradio test UI (
/uiroute) for this project as well, or skip it entirely since we have a custom widget?