Skip to content

nicolasguelfi/formchat

Repository files navigation

FormChat - Dynamic Form Chatbot

🎯 Overview

FormChat is an intelligent chatbot system that guides users through dynamic form completion using advanced AI agents. The system leverages JSON Schema configuration with custom extensions to create sophisticated, conditional forms with real-time validation and calculations.

πŸ—οΈ Architecture

Technology Stack

  • Backend: LangGraph + LangChain (Multi-agent orchestration)
  • Frontend: LobeChat (Modern chat interface with custom plugins)
  • Database: PostgreSQL + Redis (Data persistence and caching)
  • Deployment: Railway (Cloud deployment)
  • Configuration: JSON Schema + Pydantic (Dynamic validation)

Key Features

  • πŸ€– Multi-Agent System: Specialized agents for orchestration, validation, calculation, and file processing
  • πŸ“ Dynamic Forms: JSON Schema-driven forms with conditional logic and calculations
  • πŸ”Œ Plugin Architecture: Modular LobeChat plugins for enhanced functionality
  • ⚑ Real-time Communication: WebSocket integration for instant feedback
  • 🌍 Multi-language Support: Internationalization with dynamic translation
  • πŸ”’ RGPD Compliance: Built-in data protection and privacy controls
  • πŸ“Š Google Integration: Automatic export to Google Sheets and Drive

πŸš€ Quick Start

Prerequisites

  • Python 3.11+
  • Node.js 18+ (for LobeChat frontend)
  • PostgreSQL 14+
  • Redis 6+

Installation

  1. Clone the repository
git clone https://github.com/your-username/formchat.git
cd formchat
  1. Backend Setup

Option A: Script Automatique (RecommandΓ© pour dΓ©buter)

./setup-dev.sh

Option B: Installation Manuelle avec requirements.txt

# Using uv (recommended)
uv venv
uv pip install -r requirements.txt
uv pip install -r requirements-dev.txt

# Or using pip
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
pip install -r requirements.txt
pip install -r requirements-dev.txt

Option C: Installation Moderne avec pyproject.toml

# Installation complète en mode développement
uv pip install -e ".[dev]"
  1. Frontend Setup
cd frontend
npm install
  1. Database Setup
# Start PostgreSQL and Redis
# Configure database connection in config/database.yaml
uv run python scripts/setup_database.py
  1. Run the Application
# Start backend
uv run python backend/main.py

# Start frontend (in another terminal)
cd frontend
npm run dev

πŸ“‹ Project Structure

formchat/
β”œβ”€β”€ backend/                    # LangGraph + LangChain backend
β”‚   β”œβ”€β”€ agents/                # Multi-agent system
β”‚   β”œβ”€β”€ config/                # JSON Schema parser and validation
β”‚   β”œβ”€β”€ models/                # Data models and schemas
β”‚   β”œβ”€β”€ services/              # Business logic services
β”‚   └── api/                   # FastAPI endpoints + WebSocket
β”œβ”€β”€ frontend/                   # LobeChat frontend
β”‚   β”œβ”€β”€ plugins/               # Custom FormChat plugins
β”‚   β”œβ”€β”€ themes/                # UI themes and personas
β”‚   └── integrations/          # LangGraph connectors
β”œβ”€β”€ config/                     # Configuration files
β”‚   β”œβ”€β”€ forms/                 # JSON Schema form definitions
β”‚   β”œβ”€β”€ schemas/               # Validation schemas
β”‚   β”œβ”€β”€ locales/               # Translation files
β”‚   └── lobechat/              # LobeChat configuration
β”œβ”€β”€ storage/                    # File storage and sessions
β”œβ”€β”€ deployment/                 # Docker and Railway configs
└── docs/                      # Documentation

πŸ”§ Configuration

JSON Schema Extensions

FormChat extends JSON Schema with custom properties:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "title": "Registration Form",
  "properties": {
    "email": {
      "type": "string",
      "format": "email",
      "title": "Email Address"
    },
    "age": {
      "type": "integer",
      "minimum": 18,
      "maximum": 100,
      "title": "Age"
    }
  },
  "x-calculations": {
    "eligibility_score": {
      "formula": "age >= 18 ? 100 : 0",
      "description": "Calculate eligibility based on age"
    }
  },
  "x-conditional": {
    "additional_info": {
      "condition": "age >= 65",
      "action": "show",
      "message": "Additional information required for seniors"
    }
  },
  "x-persona": {
    "name": "Marie",
    "avatar": "professional_woman",
    "tone": "friendly_professional",
    "language": "fr"
  }
}

Environment Variables

Create a .env file in the root directory:

# Database
DATABASE_URL=postgresql://user:password@localhost:5432/formchat
REDIS_URL=redis://localhost:6379

# AI Models
OPENAI_API_KEY=your_openai_key
ANTHROPIC_API_KEY=your_anthropic_key
GOOGLE_AI_API_KEY=your_google_key

# Google Integration
GOOGLE_SHEETS_CREDENTIALS=path/to/credentials.json
GOOGLE_DRIVE_FOLDER_ID=your_folder_id

# Security
SECRET_KEY=your_secret_key
ENCRYPTION_KEY=your_encryption_key

# Deployment
RAILWAY_ENVIRONMENT=production

πŸ€– Agent System

Available Agents

  1. Form Orchestrator: Manages conversation flow and form progression
  2. Field Validator: Validates user input with real-time feedback
  3. Calculation Engine: Performs dynamic calculations based on form data
  4. File Processor: Handles file uploads and processing
  5. Export Manager: Manages data export to Google services

Adding Custom Agents

from backend.agents.base_agent import BaseAgent

class CustomAgent(BaseAgent):
    def __init__(self, config: Dict[str, Any]):
        super().__init__("custom_agent", config)
    
    async def process(self, message: Dict[str, Any]) -> Dict[str, Any]:
        # Custom processing logic
        return {"result": "processed"}

πŸ”Œ LobeChat Plugins

Plugin Structure

from frontend.plugins.base_plugin import BaseFormChatPlugin

class MyCustomPlugin(BaseFormChatPlugin):
    def __init__(self, **kwargs):
        super().__init__("my_custom_plugin", **kwargs)
    
    async def process_message(self, message: Dict[str, Any]) -> Dict[str, Any]:
        # Plugin logic
        return {"type": "response", "content": "Plugin response"}

Available Plugins

  • FormChat Agent: Main conversation handler
  • File Upload: File processing and validation
  • Real-time Validation: Instant field validation
  • Progress Tracker: Form completion tracking
  • Calculation Display: Dynamic calculation results

🌍 Multi-language Support

Adding New Languages

  1. Create translation file in config/locales/
  2. Update language configuration in config/lobechat/persona_configs.yaml
  3. Test with different language personas

Example Translation

{
  "chat": {
    "welcome": "Bonjour ! Je suis {name}, votre assistante pour ce formulaire.",
    "field_success": "Parfait ! Passons Γ  la question suivante.",
    "validation_error": "Il semble y avoir une erreur. Pouvez-vous vΓ©rifier ?"
  },
  "validation": {
    "required": "Ce champ est obligatoire",
    "email_format": "Veuillez entrer une adresse email valide"
  }
}

πŸš€ Deployment

Railway Deployment

  1. Connect to Railway
railway login
railway link
  1. Configure Environment Variables
railway variables set DATABASE_URL=your_production_db_url
railway variables set REDIS_URL=your_production_redis_url
# ... other variables
  1. Deploy
railway up

Docker Deployment

# Build and run with Docker Compose
docker-compose up --build

πŸ“Š Performance

Target Metrics

  • 3000 concurrent users
  • < 200ms API response time
  • 99.9% uptime
  • Multi-language support (5+ languages)
  • File upload up to 10MB

Monitoring

The application includes comprehensive monitoring:

  • Application logs via structured logging
  • Performance metrics via Prometheus
  • Health checks for all services
  • Error tracking and alerting

πŸ”’ Security & Compliance

RGPD Compliance

  • Data encryption at rest and in transit
  • User consent management
  • Right to be forgotten implementation
  • Data anonymization for exports
  • Audit trail for all data operations

Security Features

  • Input validation and sanitization
  • Rate limiting and DDoS protection
  • Secure file upload handling
  • API authentication and authorization

πŸ“š Documentation

πŸ“š Documentation

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ†˜ Support

πŸ™ Acknowledgments

  • LangGraph for multi-agent orchestration
  • LobeChat for the modern chat interface
  • FastAPI for the high-performance API framework
  • Railway for seamless deployment

FormChat - Making form completion intelligent and conversational πŸ€–βœ¨

Releases

No releases published

Packages

No packages published

Languages