Version 2.2 β Single Database, Multi-Domain Architecture | Bilingual Support
An advanced AI-powered system designed to interact with multiple business domains within a single PostgreSQL database using natural language. The system uses a Domain Router + Dual-LLM Validation Architecture to understand context, handle ambiguity across domains, and self-correct SQL errors.
π v2.2 Architecture Update: Migrated from multiple databases to a Single Database, Multi-Domain architecture. All tables now reside in one PostgreSQL instance with domain-based isolation via
ALLOWED_TABLES.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SINGLE PostgreSQL DATABASE β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β βββββββββββββββββββ βββββββββββββββββββ ββββββββββββββββββ β
β β HR OPERATIONS β β SALES CRM β β MAINTENANCE β β
β β DOMAIN β β DOMAIN β β DOMAIN β β
β β β β β β β β
β β β’ checklist β β β’ fms_leads β β β’ maintenance_ β β
β β β’ delegation β β β’ enquiry_to_ β β task_assign β β
β β β’ users β β order β β β β
β β β’ leave_request β β β’ make_quotationβ β β β
β β β’ visitors β β β’ login β β β β
β β β’ ticket_book β β β β β β
β β β’ request β β β β β β
β β β’ resume_requestβ β β β β β
β β β’ + 10 more... β β β β β β
β βββββββββββββββββββ βββββββββββββββββββ ββββββββββββββββββ β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββ΄ββββββββββ
β DOMAIN ROUTER β
β (AI-Powered) β
βββββββββββ¬ββββββββββ
β
βββββββββββββββββΌββββββββββββββββ
βΌ βΌ βΌ
HR Agent Sales Agent Maintenance Agent
(sees 18 tables) (sees 4 tables) (sees 1 table)
- Schema-Aware Routing: The router analyzes the actual table & column names of each domain, not just keywords.
- Single Connection: All domains share the same database connection, reducing complexity.
- Ambiguity Protocol: If a query term appears in multiple domains, the agent pauses and asks for clarification.
- Clarification Memory: Once clarified, it merges context with the original question.
- Generate-Validate-Regenerate Loop:
- Generator (LLM 1): Writes SQL using semantic schema + business rules.
- Validator (LLM 2): Checks against column restrictions, intent matching, LOWER() enforcement.
- Refiner: Auto-rewrites with feedback (max 3 attempts).
- Domain Isolation: Each agent only sees its
ALLOWED_TABLES.
- Understands mixed Hindi-English queries:
"aaj ke pending tasks dikhao"β Show today's pending tasks"jinka leave approve nhi hua unka naam batao"β Names with unapproved leave"sabka travel data do"β Show everyone's travel data
Employee & HR management covering tasks, leaves, travel, hiring, and visitors.
| Table | Purpose | Key Columns |
|---|---|---|
checklist |
Daily/routine tasks | name, department, task_description, submission_date, status |
delegation |
One-time assigned tasks | name, given_by, planned_date, submission_date |
users |
Employee info & login | user_name, department, role, email_id, status |
leave_request |
Leave management | employee_name, from_date, to_date, request_status, approved_by |
visitors |
Visitor gate pass | visitor_name, purpose_of_visit, person_to_meet, approval_status |
ticket_book |
Travel bills | person_name, type_of_bill, total_amount, charges |
request |
Travel requests | person_name, type_of_travel, from_city, to_city |
resume_request |
Hiring pipeline | candidate_name, experience, interviewer_status, joined_status |
| + 10 more | Finance, subscriptions, documents | ... |
Full-cycle sales: Lead β Enquiry β Quotation β Order.
| Table | Purpose | Key Columns |
|---|---|---|
fms_leads |
Lead tracking | lead_source, status (Hot/Warm/Cold), is_order_received |
enquiry_to_order |
Conversion tracking | timestamp, planned, actual, is_order_received |
make_quotation |
Quotation management | quotation_no, prepared_by, company_name, grand_total |
login |
CRM user accounts | username, password, usertype |
Machine repairs and maintenance tasks.
| Table | Purpose | Key Columns |
|---|---|---|
maintenance_task_assign |
Maintenance tasks | Machine_Name, Doer_Name, Task_Start_Date, Actual_Date |
Business Rules:
Actual_Date IS NULLβ Task is PENDINGActual_Date IS NOT NULLβ Task is COMPLETEDβ οΈ Uses Mixed-Case columns (requires quoting in SQL)
flowchart TD
U("π€ User")
RT{"π Domain Router"}
subgraph DB ["π Single PostgreSQL Database"]
D1["π HR Domain<br/>18 Tables"]
D2["πΌ Sales Domain<br/>4 Tables"]
D3["βοΈ Maintenance Domain<br/>1 Table"]
end
subgraph AGENT ["π€ Dual-LLM Agent"]
SG["SQL Generator<br/>LLM 1"]
SV{"Validator<br/>LLM 2"}
EX["Executor"]
end
SY["π Answer Synthesizer"]
U --> RT
RT -->|"HR Intent"| D1
RT -->|"Sales Intent"| D2
RT -->|"Maintenance Intent"| D3
D1 --> AGENT
D2 --> AGENT
D3 --> AGENT
SG --> SV
SV -->|"β Reject"| SG
SV -->|"β
Approve"| EX
EX --> SY
SY --> U
Sagar_tmt_DB_assistant/
βββ Backend_New/ # FastAPI Python Backend
β βββ main.py # Application entry point
β βββ .env # Environment variables
β βββ app/
β β βββ core/
β β β βββ router.py # Domain Router (AI-powered)
β β β βββ config.py # Single DATABASE_URL + settings
β β β βββ security.py # SQL injection prevention
β β β βββ auth.py # Authentication
β β βββ domains/ # π Domain Modules (share same DB)
β β β βββ hr_operations/ # HR Operations Domain
β β β β βββ config.py # ALLOWED_TABLES, ALLOWED_COLUMNS
β β β β βββ connection.py # Uses shared DATABASE_URL
β β β β βββ prompts.py # Domain-specific prompts
β β β β βββ workflow.py # LangGraph workflow
β β β βββ sales_crm/ # Sales CRM Domain
β β β βββ maintenance/ # Maintenance Domain
β β βββ services/
β β β βββ cache_service.py # Semantic query cache (ChromaDB)
β β β βββ context_manager.py # Conversation context
β β β βββ session_manager.py # Multi-user sessions
β β βββ api/routes/
β β βββ chat.py # Chat streaming endpoint (SSE)
βββ Frontend/ # Chat UI (HTML/JS)
βββ Database_Schemas/ # Schema documentation
βββ SYSTEM_DOCUMENTATION.md # Complete system docs
βββ DOMAIN_INTEGRATION_GUIDE.md # How to add new domains
βββ README.md # This file
- Python 3.10+
- PostgreSQL Database (single instance with all tables)
- OpenAI API Key
- pip (Python package manager)
-
Clone & Setup:
git clone <repo_url> cd Sagar_tmt_DB_assistant
-
Create Virtual Environment:
python -m venv .venv # Windows .venv\Scripts\activate # Linux/Mac source .venv/bin/activate
-
Install Dependencies:
cd Backend_New pip install -r requirements.txtKey dependencies:
fastapi+uvicornβ API serverlangchain-community+langchain-openaiβ LLM frameworklanggraphβ Agent state machinepsycopg2-binaryβ PostgreSQL driverchromadbβ Semantic cachepython-dotenv+pydantic-settingsβ Configuration
-
Environment Variables: Create a
.envfile inBackend_New/:# ============================================ # SINGLE DATABASE CONNECTION # ============================================ # One PostgreSQL database with multiple domains DATABASE_URL=postgresql://user:pass@host:5432/main_database # ============================================ # LLM Configuration # ============================================ OPENAI_API_KEY=sk-... LLM_MODEL=gpt-4o-mini # ============================================ # Optional Tuning # ============================================ MAX_VALIDATION_ATTEMPTS=3 CONFIDENCE_THRESHOLD=70 CACHE_SIMILARITY_THRESHOLD=0.92
-
Run the Backend:
cd Backend_New uvicorn main:app --reloadThe API will start at
http://127.0.0.1:8000. -
Open the Frontend:
Open
Frontend/index.htmlin your browser or navigate tohttp://localhost:8000/app.
Since all domains share the same database, adding a new domain only requires:
-
Create Domain Module: Create a folder under
app/domains/your_new_domain/with:config.pyβROUTER_METADATA,ALLOWED_TABLES,ALLOWED_COLUMNS,SEMANTIC_SCHEMAconnection.pyβ Uses sharedsettings.DATABASE_URL+RestrictedSQLDatabaseprompts.pyβ Generator, Validator, and Answer Synthesis promptsworkflow.pyβ LangGraph agent workflow
-
Register in Router: Import your metadata in
app/core/router.py:from app.databases.your_new_domain.config import ROUTER_METADATA, SEMANTIC_SCHEMA REGISTERED_DOMAINS = [ ... (YOUR_DOMAIN_META, YOUR_DOMAIN_SCHEMA), ]
-
Connection Template (
connection.py):from app.core.config import settings def get_db_instance(): return RestrictedSQLDatabase( connection_string=settings.DATABASE_URL, schema="public", include_tables=ALLOWED_TABLES, )
See DOMAIN_INTEGRATION_GUIDE.md for a full step-by-step walkthrough.
- Add to
ALLOWED_TABLESinapp/domains/<domain>/config.py - Add to
ALLOWED_COLUMNSinapp/domains/<domain>/config.py - Add to
SEMANTIC_SCHEMAinapp/domains/<domain>/config.py - Update
target_tablesinapp/domains/<domain>/workflow.py - Update prompts in
app/domains/<domain>/prompts.py
Each domain module defines its own ALLOWED_TABLES:
# HR Domain (checklist/config.py)
ALLOWED_TABLES = ["checklist", "delegation", "users", "leave_request", ...]
# Sales Domain (lead_to_order/config.py)
ALLOWED_TABLES = ["fms_leads", "enquiry_to_order", "make_quotation", "login"]
# Maintenance Domain (sagar_db/config.py)
ALLOWED_TABLES = ["maintenance_task_assign"]The RestrictedSQLDatabase class filters the schema to only show allowed tables, even though all tables exist in the same database.
| Issue | Cause | Fix |
|---|---|---|
| "Ambiguous Query" loop | Router metadata descriptions too similar | Make ROUTER_METADATA descriptions more distinct |
| "Column does not exist" | PostgreSQL mixed-case columns | Add quotes in config (e.g., "Machine_Name") |
| Agent sees wrong tables | ALLOWED_TABLES not updated |
Add table name to domain's config.py |
| "No result returned" | Empty query results or graph error | Check debug logs; empty results now handled gracefully |
| Hindi words used as filter | Glossary incomplete | Add new words to HINDI GLOSSARY in prompts.py |
| Excessive validation loops | Validator too strict | Review validator prompt strictness settings |
Architecture Changes:
- β Migrated from 3 separate databases to single PostgreSQL database
- β
All domain modules now use shared
DATABASE_URLconnection - β
Domain isolation via
ALLOWED_TABLESper domain module - β Simplified configuration β one connection string instead of three
- β Updated terminology: "databases" β "domains" throughout codebase
Files Modified:
Backend_New/app/core/config.pyβ SingleDATABASE_URLwith legacy aliasesBackend_New/app/core/router.pyβ Renamed toREGISTERED_DOMAINSBackend_New/app/domains/*/connection.pyβ All usesettings.DATABASE_URLBackend_New/.env.exampleβ New single-database configuration
New Tables Integrated:
ticket_bookβ Ticket bookings & travel billsleave_requestβ Employee leave management with multi-level approvalvisitorsβ Visitor gate pass tracking with inline UI image renderingrequestβ Employee travel requestsresume_requestβ Candidate resume intake & hiring pipeline
Improvements:
- Empty Result Handling β Empty SQL results now generate AI-powered friendly messages
- Hindi/Hinglish Glossary β Bilingual word recognition in prompts
- Negation-Aware Intent Rules β "not approved", "not completed" mapped correctly
- Column-Level Security β Each table has explicit allowed/forbidden columns
- LOWER() Enforcement β Case-insensitive matching across all tables
For bugs or feature requests, check the debug logs in the terminal output or contact the development team.
- SYSTEM_DOCUMENTATION.md β Complete system architecture and workflow diagrams
- DOMAIN_INTEGRATION_GUIDE.md β Step-by-step guide to add new domains
- BACKEND_NEW_WORKFLOW.md β LangGraph workflow details