Arag / implementation_plan.md
AuthorBot
Restructure project for HF Spaces deployment
772f852
|
Raw
History Blame Contribute Delete
26.5 kB

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

  1. Upload: PDF, EPUB, DOCX, TXT β€” validated by magic bytes (not just extension)
  2. Async processing via background threads (Celery-ready, threading fallback)
  3. Real-time SSE progress bar (chunking β†’ embedding β†’ indexing)
  4. Per-book ChromaDB collection (isolated per Author tenant)
  5. Configurable chunk size & overlap per Author
  6. Auto-generated book summary on upload (LLM-powered, stored as metadata)
  7. Support for multiple books per Author (multi-book catalog)
  8. Book metadata: title, genre, author name, publication year, price, buy URL, preview URL, discount code, one-line pitch, awards, review snippets
  9. Delete / re-ingest a book (full re-embedding)

πŸ€– 12-Step RAG Pipeline (adapted for book sales)

  1. Step 1 β€” Context Injection: Author tone, persona, style preferences, active books
  2. Step 2 β€” Intent Classification: Detects query type (book Q&A, price inquiry, character question, plot question, buy intent, comparison, series/sequel question, general greeting)
  3. Step 3 β€” Query Rewriting: Optimizes raw query for vector search
  4. Step 4 β€” Input Guardrails: Blocks jailbreak / off-topic patterns
  5. Step 5 β€” Retrieval: all-MiniLM-L6-v2 + ChromaDB, per-tenant collection
  6. Step 6 β€” Reranking: CrossEncoder rescoring (cross-encoder/ms-marco-MiniLM-L-6-v2)
  7. Step 7 β€” Prompt Assembly: System prompt + history + ranked chunks + upsell config
  8. Step 8 β€” LLM Generation: Streaming via OpenAI / Groq / Fireworks / HuggingFace
  9. Step 9 β€” Faithfulness Check (NLI): deberta-v3-small verifies answer is grounded in book text
  10. Step 10 β€” Output Boundary Check: Detects system prompt leakage or competitor mentions
  11. Step 11 β€” Upsell Engine: Analyzes conversation turn number + detected buy intent β†’ injects relevant CTA, smart link, or discount code
  12. Step 12 β€” Formatter: Cleans markdown, enforces short/concise reply style

🎯 Upsell Engine Logic

  1. Turn 1: Focus on curiosity / hook (no hard sell)
  2. Turn 2: Introduce value + social proof (soft CTA)
  3. Turn 3+: Active CTA with buy link + urgency message (if configured)
  4. Buy-intent signal detected at any turn β†’ immediate smart link injection
  5. Price question β†’ instant buy link + value justification
  6. Series/sequel question β†’ cross-sell to next book
  7. Configurable: Author can disable/enable upsell per book
  8. A/B testing slot for CTA variants (stored, switchable from admin)

πŸ“Š Analytics & Tracking

  1. Anonymous fingerprinting: SHA-256(IP + UA) β€” no PII
  2. Per-session tracking: intent detected, tokens used, latency, faithfulness score
  3. Per-book analytics: views, clicks, buy-link clicks (UTM tracking)
  4. Geo-location: MaxMind GeoLite2 (country-level only)
  5. Hourly aggregation Celery Beat job β†’ daily dashboard charts
  6. Conversion funnel: impression β†’ engagement β†’ buy-link click
  7. Export analytics: CSV / Excel
  8. SuperAdmin global analytics dashboard (cross-author)

🎨 Chat Widget (Author-Customizable)

  1. Bot name, avatar image upload
  2. Welcome message (custom per book landing page)
  3. Widget position: bottom-right / bottom-left / center
  4. Theme: light / dark / custom hex colors
  5. Fallback behavior when bot can't answer
  6. Widget embed via <script> tag with Author's signed token
  7. Mobile-responsive widget
  8. Typing indicator animation
  9. Message delivery ticks
  10. Star rating at end of conversation

πŸ‘₯ Multi-Tenant Author Admin Panel

  1. Dashboard: total readers, total conversations, conversion rate, avg session length
  2. Book manager: upload, edit metadata, delete, re-ingest
  3. Session viewer: read all reader transcripts
  4. Block / unblock readers
  5. Reply to readers manually (live agent takeover)
  6. End chat / archive session
  7. Widget config (name, avatar, colors, position, welcome message)
  8. Smart Links manager (buy URL, preview URL, discount code, urgency message)
  9. Analytics page (charts: daily readers, top books, top intents, geo map)
  10. Export chats (Excel / JSON)
  11. Password change (self-service)
  12. API settings (LLM provider choice per Author)
  13. Subscription info (token budget, expiry β€” read-only, managed by SuperAdmin)

πŸ›‘οΈ SuperAdmin Panel

  1. Manage Author accounts: create, suspend, delete
  2. Set token budgets per Author (monthly / total)
  3. Extend / revoke Author subscriptions
  4. Impersonate Author panel (read-only support mode)
  5. View cross-author analytics
  6. Platform-wide rate limit settings
  7. Audit log viewer (immutable β€” no delete)
  8. Platform health dashboard (Redis status, ChromaDB status, LLM status)
  9. Broadcast announcement to all Authors (shown in their admin panel)

πŸ› οΈ Deployment & Infrastructure

  1. Hugging Face Spaces ready (custom Dockerfile)
  2. Pre-downloaded models baked into Docker image (no cold-start)
  3. ChromaDB for vector storage (per-tenant collections)
  4. Redis for rate limiting, token blacklist, pub/sub (SSE progress)
  5. SQLite for Author accounts, audit log, subscription data
  6. Full async: FastAPI + asyncpg (or aiosqlite) + Redis.asyncio
  7. Celery (with Redis broker) for async ingestion + scheduled aggregation
  8. 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_SECRET
  • JWT_SECRET_KEY, JWT_ALGORITHM, JWT_EXPIRE_MINUTES
  • REDIS_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-small
  • EMBEDDING_MODEL = all-MiniLM-L6-v2

[NEW] app/core/database.py

SQLite schema via aiosqlite:

  • authors table: id, slug, name, email, password_hash, totp_secret, token_budget, tokens_used, subscription_expiry, suspended, created_at
  • books table: id, author_id, title, genre, pub_year, price, buy_url, preview_url, discount_code, pitch, awards, reviews_json, ingested_at, status
  • audit_log table: id, actor, action, target, detail, timestamp β€” NO DELETE allowed via app layer
  • announcements table: id, message, created_at, created_by

[NEW] app/core/security.py

  • hash_password() / verify_password() via bcrypt
  • create_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/init
  • GET /api/chat/{author_slug}/session/history/{session_id}
  • POST /api/chat/{author_slug}/session/rate
  • POST /api/chat/{author_slug}/session/reset
  • GET /api/chat/{author_slug}/events β€” SSE for ingestion progress

[NEW] app/api/ingest.py

  • POST /api/admin/{author_slug}/books/upload
  • GET /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 token
  • GET /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-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

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

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 with data-author attribute.)

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-small adds ~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 (/ui route) for this project as well, or skip it entirely since we have a custom widget?