Technical Engineering & Code Guide

An in-depth, code-level explanation of how PhinsIQ is structured, which packages are used and why, which files run first during startup, and how every function in the pipeline analyzes, routes, and renders natural language answers.

πŸ“¦ 1. Core Packages & Technical Rationale

PhinsIQ is designed to support 150+ institutions simultaneously with high concurrency and sub-millisecond middleware latency. Here is why each specific package is used:

Package Category Why It Is Used & Technical Advantage
fastapi ASGI Framework High-performance async web framework built on Starlette and Pydantic. Enables non-blocking async routes and automatic OpenAPI documentation.
motor Async Database Official non-blocking async MongoDB driver built on asyncio. Prevents database network I/O from blocking Python's event loop when querying configs for 150+ schools.
pydantic v2 Data Validation High-speed Rust-powered data parsing and schema validation for API request bodies and database models with strict type safety.
httpx Async HTTP Client Next-generation async HTTP client with built-in connection pooling and timeouts for executing ERP REST API calls concurrently.
structlog Observability Structured key-value JSON logging. Enables log correlation with request_id across all 9 pipeline stages for production debugging.
certifi Security & TLS Provides Mozilla's carefully curated collection of Root Certificates for secure, verified SSL/TLS connections to MongoDB Atlas and ERP endpoints.
uvicorn ASGI Server Lightning-fast ASGI server implementation using uvloop and httptools to serve FastAPI in production.
pytest & pytest-asyncio Testing Automated asynchronous testing harness ensuring all CRUD routes, permission checks, and pipeline mapping functions execute correctly.

πŸš€ 2. Startup Lifecycle β€” Which File Runs First?

When you run uvicorn app.main:app --reload, here is the exact chronological sequence of files and functions that execute:

Step 1: Application Entrypoint & Logging Config
app/main.py & app/core/logging.py

Uvicorn loads app/main.py. The very first statement executed is configure_logging() from app/core/logging.py. This ensures that every startup event (including server banner and DB connection logs) is formatted as structured JSON logs.

Step 2: Environment Settings Initialized
app/core/config.py

Settings() initializes by reading the .env file (MongoDB URL, Database name, Port, Environment). Settings are cached as a singleton for the entire application.

Step 3: Application Factory Created
app/main.py: create_application()

create_application() instantiates FastAPI, registers CORS middleware (allowing cross-origin requests from the web console), mounts custom exception handlers for PhinsIQException, and links the async lifespan context manager.

Step 4: Database Lifespan & Connection Pool Startup
app/core/database.py: lifespan()

During startup, FastAPI enters the lifespan generator. It calls connect_to_mongodb(), creating a single persistent AsyncIOMotorClient connection pool with TLS certificates from certifi.where() and tests the connection with an admin ping.

Step 5: API Routers Mounted & Traffic Served
app/api/v1/router.py

FastAPI mounts v1_router with prefix /api/v1:
β€’ /api/v1/health (Health check)
β€’ /api/v1/phinsiq/chat (Core natural language pipeline)
β€’ /api/v1/admin/... (CRUD studio for institutions, modules, mappings, fields, templates)

πŸ”„ 3. Deep-Dive: The 9-Stage Request Pipeline

When a student asks: "What is my pending fee?", here is how each file and function processes the request step-by-step:

Stage 1: API Request Ingestion & Validation
app/api/v1/chat.py: chat_endpoint()

Function: async def chat(request: ChatRequest)
Input: {"institution_id": "sjbhs", "role": "student", "user_id": "ST123", "message": "What is my pending fee?"}
How it works: Pydantic automatically validates the JSON payload. A unique request_id is generated for distributed log tracing, and pipeline.process(request, request_id) is called.

Stage 2: Text Pre-Processing & Normalization
app/pipeline/preprocessor.py: Preprocessor.process()

Function: def process(self, raw_message: str) -> PreprocessedMessage
Inner Logic: Strips whitespace, converts text to lowercase, removes punctuation, and checks for greetings (e.g. "hi", "hello") or profanity. If a simple greeting is detected, it short-circuits and returns an immediate response without database/ERP overhead.

Stage 3: Module Keyword Detection
app/understanding/module_detector.py: ModuleDetector.detect()

Function: def detect(self, message: str) -> ModuleDetectionResult
Inner Logic: Analyzes weighted keyword signals. For example, "pending" (1.5) and "fee" (2.0) score highest for the fees module (confidence score: 1.0). Identifies target module: "fees".

Stage 4: Role Permission Authorization
app/permissions/permission_engine.py: PermissionEngine.check()

Function: async def check(self, role_id: str, module_id: str) -> bool
Inner Logic: Queries the roles collection in MongoDB (cached in-memory) to verify if student is permitted to access the fees module. If unauthorized (e.g., student querying payroll), raises ForbiddenError.

Stage 5: Field Intent Detection & NLP Aliases
app/understanding/field_detector.py: FieldDetector.detect()

Function: def detect(self, message: str, field_definitions: list[dict]) -> FieldDetectionResult
Inner Logic: Loads field definitions and natural language aliases from MongoDB (fields collection). Matches phrase *"pending fee"* against aliases for pending_amount (aliases: "pending", "pending fee", "balance", "amount due"). Extracts target field: ["pending_amount"].

Stage 6: Institution & API Registry Lookup
app/repositories/institution.py & registry.py

Function: await institution_repo.get_active_by_id("sjbhs") and await registry_repo.get_registry("sjbhs", "student", "fees", "summary")
Inner Logic: Loads institution's Base URL (https://demo.parrophins.in/sjbhs), HTTP Method (POST), Path (/student/apiviewFeePaymentInfo), Body Template ({"row_id": "{user_id}"}), and dynamic response_mapping.

Stage 7: Asynchronous ERP API Call
app/router/api_router.py: ERPRouter.call()

Function: async def call(self, institution_config, registry_entry, user_id) -> dict
Inner Logic: Replaces {user_id} in the body template with "ST123" and executes an async non-blocking POST request using httpx.AsyncClient with timeout handling. Returns raw ERP JSON.

Stage 8: Dynamic ERP Response Field Mapping
app/router/response_mapper.py: ResponseMapper.map()

Function: def map(self, raw_response, response_mapping, response_root) -> dict
Inner Logic: Iterates through the database-driven mapping dictionary (e.g. "pending_amount": "pending_amount", "total_fee": "total_fee_amount") using dot-notation resolver (get_nested_value) to produce standard PhinsIQ data dict: {"pending_amount": 15000, "total_fee": 50000}.

Stage 9: Response Template Rendering & Serialization
app/response/template_engine.py: TemplateEngine.render()

Function: def render(self, requested_fields, mapped_data, templates_doc) -> str
Inner Logic: Loads the template for pending_amount: "Your pending fee amount is β‚Ή{pending_amount}.", formats the currency value, and interpolates: "Your pending fee amount is β‚Ή15,000."
Returns structured ChatResponse in ~20ms without invoking expensive Claude/LLM tokens!

πŸ—ΊοΈ 4. Why Dynamic Mapping Means ZERO Code Changes

Different schools use completely different ERP systems. One returns total_fee_amount, another returns totalfeepayment, and a third nests it under data.billing.due.

PhinsIQ never hardcodes these keys in Python. The database maps any arbitrary ERP JSON into standard keys:

// Client A (SJBHS) ERP Response:
{ "total_fee_amount": 50000, "instalment_amt": 25000 }
↓ Mapped in DB api_registry:
{ "total_fee": "total_fee_amount", "installment_amount": "instalment_amt" }

// Client B (Zenith Academy) ERP Response:
{ "totalfeepayment": 50000, "due_bal": 15000 }
↓ Mapped in DB api_registry:
{ "total_fee": "totalfeepayment", "pending_amount": "due_bal" }

// Result for Both:
Standardized PhinsIQ Data: { "total_fee": 50000, "pending_amount": 15000 }

πŸ“‚ 5. Directory Structure & Key Files

Directory / File Responsibility
app/main.py Application factory, lifespan context, CORS, error handling, route mounting.
app/core/database.py Single Motor MongoDB client instance, connection pool lifecycle.
app/core/config.py Pydantic Settings loading environment variables from .env.
app/core/logging.py Structured JSON logging configuration.
app/api/v1/chat.py FastAPI route for student & staff chat queries (/api/v1/phinsiq/chat).
app/api/v1/admin.py Complete CRUD REST endpoints for institutions, modules, mappings, templates, and Live ERP tester.
app/pipeline/pipeline.py The central orchestrator connecting understanding, permissions, ERP call, and templates.
app/understanding/ module_detector.py (keyword intent) & field_detector.py (alias matching).
app/repositories/ Data access layers (institution.py, registry.py, module_repo.py) with in-process caching.
app/router/ api_router.py (async httpx dispatcher) & response_mapper.py (dot-notation field mapper).
app/response/template_engine.py Deterministic template interpolation and currency/percentage formatting.
index.html Visual Web Admin Studio & Live Chat Playground.

πŸ› οΈ 6. How to Onboard a New Client (3 Simple Steps via Web UI)

  1. Add Institution: Open the Admin Studio -> 🏒 Clients -> Click + Add New Client. Enter Institution Slug (e.g. zenith_academy), Base URL, and Auth type.
  2. Configure API Registry & Mappings: Open πŸ—ΊοΈ ERP Mapper -> Select zenith_academy & fees. Set the endpoint path (e.g. /api/v1/fee-details) and map their ERP keys (e.g. total_fee ← totalfeepayment). Click Save Mapping.
  3. Test Live in Playground: Open πŸ’¬ Playground -> Select zenith_academy and ask "What is my fee?". The pipeline will automatically route the query, call the new ERP, map fields, and render the response without modifying or deploying any Python backend code!