Files
biblical-guide.com/AI_CHAT_ARCHITECTURE.md
Andrei 9b5c0ed8bb build: production build with Phase 1 2025 Bible Reader implementation complete
Includes all Phase 1 features:
- Search-first navigation with auto-complete
- Responsive reading interface (desktop/tablet/mobile)
- 4 customization presets + full fine-tuning controls
- Layered details panel with notes, bookmarks, highlights
- Smart offline caching with IndexedDB and auto-sync
- Full accessibility (WCAG 2.1 AA)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-11 20:38:01 +00:00

25 KiB

AI Chat Architecture Diagram

System Overview

┌─────────────────────────────────────────────────────────────────────────────┐
│                         BIBLICAL GUIDE - AI CHAT SYSTEM                      │
└─────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│                            FRONTEND LAYER                                     │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                               │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │ Main Layout: /app/[locale]/layout.tsx                               │   │
│  │ (FloatingChat COMMENTED OUT - Line 10 & 133)                        │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                      │                                        │
│                                      ▼                                        │
│  ┌──────────────────────────────────────────────────────────────────────┐   │
│  │           FloatingChat Component (Client-side)                      │   │
│  │  /components/chat/floating-chat.tsx                                 │   │
│  │                                                                      │   │
│  │  ┌─────────────────┐  ┌──────────────────┐  ┌──────────────────┐   │   │
│  │  │  FAB Button     │  │ Conversation     │  │  Chat Messages   │   │   │
│  │  │  (Bottom-Right) │  │ History Sidebar  │  │  Display Area    │   │   │
│  │  └─────────────────┘  └──────────────────┘  └──────────────────┘   │   │
│  │          ▲                      ▲                    ▲                │   │
│  │          │                      │                    │                │   │
│  │          └──────────┬───────────┴────────────────────┘                │   │
│  │                     │ CustomEvents                                    │   │
│  │                     │ floating-chat:open                              │   │
│  │                     │ auth:sign-in-required                           │   │
│  └──────────────────────────────────────────────────────────────────────┘   │
│                                      │                                        │
│         Dispatches from: home page, Bible reader, donate page                │
│                                                                               │
└─────────────────────────────────────────────────────────────────────────────┘
                                      │
                                      │ fetch() requests
                                      ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                          API LAYER (Backend)                                  │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                               │
│  ┌────────────────────────────────────────────────────────────────────────┐ │
│  │ POST /api/chat  (Main Chat Endpoint)                                   │ │
│  │ /app/api/chat/route.ts                                                 │ │
│  │                                                                          │ │
│  │  Input: message, conversationId, locale, history                       │ │
│  │                                                                          │ │
│  │  Processing Flow:                                                      │ │
│  │  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐                  │ │
│  │  │   Auth       │  │ Conversation │  │  Bible Verse │                  │ │
│  │  │   Check      │  │  Management  │  │  Search      │                  │ │
│  │  └──────────────┘  └──────────────┘  └──────────────┘                  │ │
│  │       ▼ Bearer        ▼ Load/Create     ▼ searchBibleHybrid()           │ │
│  │      Token           History            (5 verses max)                  │ │
│  │                                                                          │ │
│  │  ┌────────────────────────────────────────────────────────────────┐   │ │
│  │  │ Context Building: Smart History Management                     │   │ │
│  │  │                                                                 │   │ │
│  │  │  • Always include last 6 messages                              │   │ │
│  │  │  • Find relevant older messages by:                            │   │ │
│  │  │    - Keyword overlap scoring                                   │   │ │
│  │  │    - Biblical reference detection                              │   │ │
│  │  │    - Time decay (older = lower score)                          │   │ │
│  │  │  • Apply token-based truncation (~1500 max)                    │   │ │
│  │  │  • Summarize messages if needed                                │   │ │
│  │  └────────────────────────────────────────────────────────────────┘   │ │
│  │                           ▼                                             │ │
│  │  ┌────────────────────────────────────────────────────────────────┐   │ │
│  │  │ Azure OpenAI REST API Call                                     │   │ │
│  │  │ /lib/ai/azure-openai.ts                                        │   │ │
│  │  │                                                                 │   │ │
│  │  │  POST https://footprints-ai.openai.azure.com                  │   │ │
│  │  │       /openai/deployments/gpt-4o/chat/completions             │   │ │
│  │  │                                                                 │   │ │
│  │  │  Payload:                                                       │   │ │
│  │  │  {                                                              │   │ │
│  │  │    messages: [                                                  │   │ │
│  │  │      { role: "system", content: languageSpecificSystemPrompt } │   │ │
│  │  │      { role: "user", content: userMessage }                    │   │ │
│  │  │    ],                                                           │   │ │
│  │  │    max_tokens: 2000,                                            │   │ │
│  │  │    temperature: 0.7                                             │   │ │
│  │  │  }                                                              │   │ │
│  │  └────────────────────────────────────────────────────────────────┘   │ │
│  │                                                                          │ │
│  │  Response: { success, response, conversationId }                        │ │
│  └────────────────────────────────────────────────────────────────────────┘ │
│                                                                               │
│  ┌────────────────────────────────────────────────────────────────────────┐ │
│  │ GET /api/chat/conversations                                            │ │
│  │ List user's conversations (paginated)                                  │ │
│  │ Query: language, limit, offset                                         │ │
│  └────────────────────────────────────────────────────────────────────────┘ │
│                                                                               │
│  ┌────────────────────────────────────────────────────────────────────────┐ │
│  │ GET /api/chat/conversations/[id]                                       │ │
│  │ Load specific conversation with all messages                           │ │
│  │                                                                         │ │
│  │ PUT /api/chat/conversations/[id]                                       │ │
│  │ Rename conversation                                                    │ │
│  │                                                                         │ │
│  │ DELETE /api/chat/conversations/[id]                                    │ │
│  │ Soft delete conversation (isActive = false)                            │ │
│  └────────────────────────────────────────────────────────────────────────┘ │
│                                                                               │
│  ┌────────────────────────────────────────────────────────────────────────┐ │
│  │ Admin Routes (Monitoring & Management)                                 │ │
│  │ GET/POST /api/admin/chat/conversations                                 │ │
│  └────────────────────────────────────────────────────────────────────────┘ │
│                                                                               │
└─────────────────────────────────────────────────────────────────────────────┘
                                      │
                                      │ Prisma ORM
                                      ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                          DATABASE LAYER (PostgreSQL)                         │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                               │
│  ┌────────────────────────────────────────────────────────────────────────┐ │
│  │ ChatConversation Table                                                 │ │
│  │                                                                         │ │
│  │ id (UUID)              │ User's conversation ID                        │ │
│  │ userId (UUID)          │ FK to User (nullable)                         │ │
│  │ title (String)         │ Auto-generated from first message             │ │
│  │ language (String)      │ 'ro' | 'en' | 'es' | 'it'                   │ │
│  │ isActive (Boolean)     │ Soft delete flag                              │ │
│  │ createdAt (DateTime)   │ Timestamp                                     │ │
│  │ updatedAt (DateTime)   │ Last update                                   │ │
│  │ lastMessageAt (DateTime) │ For sorting recent conversations            │ │
│  │                                                                         │ │
│  │ Indexes:                                                                │ │
│  │ • (userId, language, lastMessageAt)                                    │ │
│  │ • (isActive, lastMessageAt)                                            │ │
│  └────────────────────────────────────────────────────────────────────────┘ │
│                                      │                                        │
│                                      ▼                                        │
│  ┌────────────────────────────────────────────────────────────────────────┐ │
│  │ ChatMessage Table                                                      │ │
│  │                                                                         │ │
│  │ id (UUID)              │ Message ID                                     │ │
│  │ conversationId (UUID)  │ FK to ChatConversation (CASCADE)              │ │
│  │ userId (UUID)          │ FK to User (nullable, backward compat)        │ │
│  │ role (Enum)            │ USER | ASSISTANT                              │ │
│  │ content (Text)         │ Message content                                │ │
│  │ metadata (JSON)        │ Optional: verse references, etc.               │ │
│  │ timestamp (DateTime)   │ When message was created                       │ │
│  │                                                                         │ │
│  │ Indexes:                                                                │ │
│  │ • (conversationId, timestamp)                                          │ │
│  └────────────────────────────────────────────────────────────────────────┘ │
│                                                                               │
└─────────────────────────────────────────────────────────────────────────────┘

Data Flow Diagram

┌────────────────────┐
│   User Inputs      │
│   "Ask biblical    │
│    question"       │
└────────────────────┘
         │
         ▼
┌────────────────────────────────┐
│ FloatingChat Component          │
│ • Validates input              │
│ • Shows loading state          │
│ • Adds user message to UI      │
└────────────────────────────────┘
         │
         ▼
┌────────────────────────────────────────────────┐
│ POST /api/chat                                 │
│                                                │
│ 1. Verify Bearer Token (Auth)                 │
│ 2. Check Subscription Limits                  │
│ 3. Load/Create Conversation                   │
│ 4. Fetch Bible Verses (searchBibleHybrid)     │
│ 5. Build Smart Context                        │
│ 6. Call Azure OpenAI API                      │
│ 7. Save Messages to Database                  │
│ 8. Return Response                            │
└────────────────────────────────────────────────┘
         │
         ▼
┌────────────────────────────────────────────────┐
│ Azure OpenAI (gpt-4o)                          │
│                                                │
│ System Prompt (Language-specific):             │
│ • "You are a Biblical AI assistant..."         │
│ • "Cite verses as [Version] Reference"         │
│ • Include Bible verses context                 │
│ • Include conversation history                 │
│                                                │
│ User Message:                                  │
│ • The actual question                          │
│                                                │
│ Returns:                                       │
│ • AI-generated biblical response               │
│ • Formatted with citations                     │
└────────────────────────────────────────────────┘
         │
         ▼
┌────────────────────────────────────────────────┐
│ Response Processing                            │
│                                                │
│ • Extract response text                        │
│ • Check for content filtering                  │
│ • Handle errors gracefully                     │
│ • Return formatted JSON response               │
└────────────────────────────────────────────────┘
         │
         ▼
┌────────────────────────────────────────────────┐
│ Database Storage (Prisma)                      │
│                                                │
│ Save in transaction:                           │
│ • ChatMessage (user message)                   │
│ • ChatMessage (assistant response)             │
│ • Update ChatConversation.lastMessageAt        │
└────────────────────────────────────────────────┘
         │
         ▼
┌────────────────────────────────────────────────┐
│ Frontend Update                                │
│                                                │
│ • Add assistant message to UI                  │
│ • Update conversation ID if new                │
│ • Refresh conversation list                    │
│ • Show typing animation → Response             │
│ • Scroll to latest message                     │
└────────────────────────────────────────────────┘
         │
         ▼
┌────────────────────┐
│   User Sees        │
│   Response with    │
│   Bible References │
└────────────────────┘

Key Integration Points

1. Authentication Flow

User logged in? 
    ├─ YES → Load stored token from localStorage
    │         └─ Send with every request: Authorization: Bearer <token>
    └─ NO  → Show sign-in prompt
             └─ Disabled chat UI
             └─ Event: auth:sign-in-required

2. Conversation Limits

Free Tier User Creates New Conversation:
    ├─ Check: checkConversationLimit(userId)
    │   ├─ Reached monthly limit?
    │   │   ├─ YES → Return 403 with upgrade URL
    │   │   └─ NO  → Continue
    │   └─ Increment: incrementConversationCount(userId)
    └─ Premium Users → Unlimited conversations

3. Bible Verse Integration

User Message → searchBibleHybrid(message, locale, 5)
    ├─ Embed message using Azure embeddings
    ├─ Search pgvector database
    ├─ Filter by language
    ├─ Return top 5 verses with:
    │   ├─ Reference (e.g., "John 3:16")
    │   ├─ Text
    │   └─ Source table (for version info)
    └─ Include in system prompt context

4. Multi-Language Support

Locale Parameter (ro | en | es | it)
    ├─ System Prompt Language
    │   └─ Romanian, English, or Spanish
    ├─ UI Language (via next-intl)
    │   └─ Messages from /messages/{locale}.json
    └─ Search Filtering
        └─ Only Bible versions in that language

Environment Dependencies

Azure OpenAI Configuration:
├─ AZURE_OPENAI_KEY=<key>
├─ AZURE_OPENAI_ENDPOINT=https://footprints-ai.openai.azure.com
├─ AZURE_OPENAI_DEPLOYMENT=gpt-4o
├─ AZURE_OPENAI_API_VERSION=2025-01-01-preview
├─ AZURE_OPENAI_EMBED_DEPLOYMENT=Text-Embedding-ada-002-V2
├─ AZURE_OPENAI_EMBED_API_VERSION=2023-05-15
└─ EMBED_DIMS=1536

Database:
├─ DATABASE_URL=postgresql://user:password@host:port/db
└─ Tables created via: npm run db:migrate

Authentication:
├─ JWT_SECRET=<secret>
└─ NEXTAUTH_SECRET=<secret>

Enabling AI Chat

Step 1: Edit /app/[locale]/layout.tsx
    Line 10:  Uncomment: import FloatingChat from '@/components/chat/floating-chat'
    Line 133: Uncomment: <FloatingChat />

Step 2: Verify environment variables
    npm run dev (starts with existing .env.local)

Step 3: Database migration
    npm run db:migrate

Step 4: Test
    └─ Navigate to app
    └─ Click chat icon
    └─ Try sending a message