- 
                Notifications
    
You must be signed in to change notification settings  - Fork 1
 
CMS + Chatbot System #530
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            hardbyte
  wants to merge
  17
  commits into
  main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
feature/cms
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
                
     Open
            
            CMS + Chatbot System #530
Conversation
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
    4d41f32    to
    6765538      
    Compare
  
    6765538    to
    2615b1a      
    Compare
  
    …tion and webhook tasks
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
      
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Overview
The Wriveted Chatbot System is a comprehensive solution that replaces Landbot with a custom, flexible chatbot platform. It provides a graph-based conversation flow engine with branching logic, state management, CMS integration, and analytics capabilities.
Project Goals
Architecture Overview
Hybrid Execution Model
The system uses a hybrid execution model optimized for the FastAPI/PostgreSQL/Cloud Tasks stack:
Execution Model
Core Components
1. Database Schema
CMS Models
cms_content: Stores all content types (jokes, facts, questions, quotes, messages, prompts)cms_content_variants: A/B testing variants with performance trackingflow_definitions: Chatbot flow definitions (replacing Landbot flows)flow_nodes: Individual nodes within flows (message, question, condition, action, webhook, composite)flow_connections: Connections between nodes with conditional logicconversation_sessions: Active chat sessions with state management and concurrency controlconversation_history: Complete interaction historyconversation_analytics: Performance metrics and analyticsSession State Management
Session state is persisted in PostgreSQL with JSONB columns for flexible data storage:
2. Chat Runtime Implementation
Repository Layer (
app/crud/chat_repo.py)ChatRepository class provides:
revisionandstate_hashKey methods:
get_session_by_token(): Retrieve session with eager loadingcreate_session(): Create new session with initial stateupdate_session_state(): Update session state with concurrency controladd_interaction_history(): Record user interactionsend_session(): Mark session as completed/abandonedRuntime Service (
app/services/chat_runtime.py)ChatRuntime main orchestration engine features:
Core Node Processors:
Extended Processors (
app/services/node_processors.py)Security-Enhanced Processors
ActionNodeProcessor implements:
{session_id}:{node_id}:{revision}WebhookNodeProcessor implements:
3. API Endpoints (
app/api/chat.py)RESTful chat interaction endpoints:
/chat/start/chat/sessions/{token}/interact/chat/sessions/{token}/chat/sessions/{token}/end/chat/sessions/{token}/history/chat/sessions/{token}/stateFeatures:
Node Types and Flow Structure
Flow Structure
A flow consists of:
Node Types
1. Message Node
Displays content to the user without expecting input.
{ "id": "welcome_msg", "type": "message", "content": { "messages": [ { "type": "text", "content": "Welcome to Bookbot! 📚", "typing_delay": 1.5 }, { "type": "image", "url": "https://example.com/bookbot.gif", "alt": "Bookbot waving" } ] }, "connections": { "default": "ask_name" } }2. Question Node
Collects input from the user.
{ "id": "ask_name", "type": "question", "content": { "question": "What's your name?", "input_type": "text", "variable": "user_name", "validation": { "required": true, "pattern": "^[a-zA-Z\\s]{2,50}$", "error_message": "Please enter a valid name" } }, "connections": { "default": "greet_user" } }3. Condition Node
Branches flow based on logic.
{ "id": "check_age", "type": "condition", "content": { "conditions": [ { "if": { "and": [ {"var": "user.age", "gte": 13}, {"var": "user.age", "lt": 18} ] }, "then": "teen_content" }, { "if": {"var": "user.age", "gte": 18}, "then": "adult_content" } ], "else": "child_content" } }4. Action Node
Performs operations without user interaction.
{ "id": "save_preferences", "type": "action", "content": { "actions": [ { "type": "set_variable", "variable": "profile.completed", "value": true }, { "type": "api_call", "method": "POST", "url": "/api/users/{user.id}/preferences", "body": { "genres": "{book_preferences}", "reading_level": "{reading_level}" } } ] }, "connections": { "success": "show_recommendations", "error": "error_handler" } }5. Webhook Node
Calls external services.
{ "id": "get_recommendations", "type": "webhook", "content": { "url": "https://api.wriveted.com/recommendations", "method": "POST", "headers": { "Authorization": "Bearer {secret:wriveted_api_token}" }, "body": { "user_id": "{user.id}", "preferences": "{book_preferences}", "age": "{user.age}" }, "response_mapping": { "recommendations": "$.data.books", "count": "$.data.total" }, "timeout": 5000, "retry": { "attempts": 3, "delay": 1000 } }, "connections": { "success": "show_books", "error": "fallback_recommendations" } }6. Composite Node
Custom reusable components (similar to Landbot Bricks).
7. API Call Action
Internal service integration for dynamic data and processing.
{ "id": "get_recommendations", "type": "action", "content": { "actions": [ { "type": "api_call", "config": { "endpoint": "/api/recommendations", "method": "POST", "body": { "user_id": "{{user.id}}", "preferences": { "genres": "{{temp.selected_genres}}", "reading_level": "{{user.reading_level}}", "age": "{{user.age}}" }, "limit": 5 }, "response_mapping": { "recommendations": "recommendations", "count": "recommendation_count" }, "circuit_breaker": { "failure_threshold": 3, "timeout": 30.0 }, "fallback_response": { "recommendations": [], "count": 0, "fallback": true } } } ] }, "connections": { "success": "show_recommendations", "failure": "recommendation_fallback" } }{ "id": "reading_profiler", "type": "composite", "content": { "inputs": { "user_age": "{user.age}", "previous_books": "{user.reading_history}" }, "outputs": { "reading_level": "profile.reading_level", "interests": "profile.interests" } }, "connections": { "complete": "next_step" } }Wriveted Platform Integration
Chatbot-Specific API Endpoints
The system provides three specialized endpoints optimized for chatbot conversations:
1. Book Recommendations (
/chatbot/recommendations)Provides simplified book recommendations with chatbot-friendly response formats:
{ "user_id": "uuid", "preferences": { "genres": ["adventure", "mystery"], "reading_level": "intermediate" }, "limit": 5, "exclude_isbns": ["978-1234567890"] }Response includes:
2. Reading Assessment (
/chatbot/assessment/reading-level)Analyzes user responses to determine reading level with detailed feedback:
{ "user_id": "uuid", "assessment_data": { "quiz_answers": {"correct": 8, "total": 10}, "comprehension_score": 0.75, "vocabulary_score": 0.82 }, "current_reading_level": "intermediate", "age": 12 }Features:
3. User Profile Data (
/chatbot/users/{user_id}/profile)Retrieves comprehensive user context for personalized conversations:
Response includes:
Internal API Integration
These endpoints are designed as "internal API calls" within the Wriveted platform:
Variable Scoping & Resolution
Explicit Input/Output Model
Composite nodes use explicit I/O to prevent variable scope pollution:
Variable Resolution Syntax:
{{user.name}}- User data (session scope){{input.user_age}}- Composite node input{{local.temp_value}}- Local scope variable{{output.reading_level}}- Composite node output{{context.locale}}- Context variable (session scope){{secret:api_key}}- Secret reference (injected at runtime from Secret Manager)State Structure
{ "session": { "id": "uuid", "started_at": "2024-01-20T10:00:00Z", "current_node": "ask_preference", "history": ["welcome", "ask_name"], "status": "active" }, "user": { "id": "user-123", "name": "John Doe", "age": 15, "school_id": "school-456" }, "variables": { "book_preferences": ["adventure", "mystery"], "reading_level": "intermediate", "quiz_score": 8 }, "context": { "channel": "web", "locale": "en-US", "timezone": "America/New_York" }, "temp": { "current_book": {...}, "loop_index": 2 } }Data Migration from Landbot
Migration Results
Successfully migrated 732KB of Landbot data:
Migration Tools
scripts/migrate_landbot_data_v2.py: Production migration scriptscripts/archive/analyze_landbot_data.py: Data structure analysis (archived)Landbot to Flow Engine Mapping
Event-Driven Integration
Database Events ✅ IMPLEMENTED
PostgreSQL triggers emit real-time events for all flow state changes with comprehensive event data:
Real-time Event Listener ✅ IMPLEMENTED
The
FlowEventListenerservice (app/services/event_listener.py) provides:Webhook Notifications ✅ IMPLEMENTED
The
WebhookNotifierservice (app/services/webhook_notifier.py) enables external integrations:Features:
Webhook Payload Structure:
{ "event_type": "node_changed", "timestamp": 1640995200.0, "session_id": "uuid", "flow_id": "uuid", "user_id": "uuid", "data": { "current_node": "ask_preference", "previous_node": "welcome", "status": "ACTIVE", "revision": 3 } }Webhook Configuration:
Cloud Tasks Integration
Asynchronous node execution for ACTION and WEBHOOK nodes via background tasks with critical reliability patterns:
Idempotency for Async Nodes⚠️ 
Each ACTION/WEBHOOK processor must include an idempotency key to prevent duplicate side effects on task retries:
Event Ordering Protection⚠️ 
Cloud Tasks may deliver out-of-order. Every task includes the parent session revision:
Error Handling & Circuit Breaker
Circuit Breaker Pattern
Robust fallback handling for external webhook calls with failure threshold and timeout management.
Error Recovery
Performance Optimization
PostgreSQL-Based Optimization
Current Implementation Status
✅ Completed
Core Chat Runtime (MVP)
Async Processing Architecture
Security Implementation
Data Migration
Real-time Event System
Database Events & Real-time Notifications
Variable Substitution Enhancement
{{user.}},{{context.}},{{temp.}},{{input.}},{{output.}},{{local.}},{{secret:}})Enhanced Node Processors
{{input.}},{{output.}},{{local.}})Wriveted Platform Integration
/chatbot/recommendations: Book recommendations with chatbot-optimized responses/chatbot/assessment/reading-level: Reading level assessment with detailed feedback/chatbot/users/{user_id}/profile: User profile data for conversation contextOngoing
❌ Planned (Post-MVP)
Advanced Features
Security Considerations
Core Security Requirements
Critical Security Patterns
Webhook Secrets Management ❗
Never embed API tokens directly in flow definitions. Use secret references that are injected at runtime:
{ "type": "webhook", "content": { "url": "https://api.example.com/endpoint", "headers": { "Authorization": "Bearer {secret:api_service_token}", "X-API-Key": "{secret:external_api_key}" } } }Implementation:
{secret:key_name}CORS & CSRF Protection ✅ IMPLEMENTED
For the
/chat/sessions/{token}/interactendpoint and other state-changing chat operations:Implementation Details (
app/security/csrf.py):secrets.token_urlsafe(32)for cryptographic securityUsage in Chat API (
app/api/chat.py):Client Implementation Example: