PhinsIQ Enterprise AI Engine
PhinsIQ is a hybrid, enterprise-grade AI academic assistant engine designed for school ERPs. It integrates ultra-fast deterministic templated execution (<50ms, βΉ0 cost), a built-in Local Subject Engine (18 Math & 3 Science Engines, <5ms), a Website Knowledge Crawler & Question Answering DB (role: "website"), and an intelligent Claude AI Fallback (Haiku 4.5) featuring multi-layer prompt caching and persistent 6-hour fuzzy semantic response reuse.
System Architecture & Core Philosophy
π‘ The Core Philosophy: Why PhinsIQ was Built This Way
Traditional chatbot architectures send every single question (e.g. "What is my fee?", "Show my homework") to a large language model. This causes three critical problems:
- High Cost: Calling an LLM 100,000 times a day costs hundreds of dollars per day.
- High Latency: LLMs take 1,500msβ4,000ms to respond, making apps feel sluggish.
- Hallucination Risk: LLMs can misread fee balances or calculate attendance percentages incorrectly.
PhinsIQ splits queries into two distinct paths:
- Deterministic Template Engine: For structured ERP data questions (Fees, Attendance, Homework, etc.), PhinsIQ extracts the data, computes aggregations mathematically, and formats responses in under 50 milliseconds at βΉ0 cost with 100% mathematical accuracy.
- Claude Haiku 4.5 Fallback: For open-ended, subjective, academic advice, or conversational questions, PhinsIQ gathers all student context and lets Claude formulate personalized advice with multi-layer caching.
π The 10-Stage Pipeline Execution Lifecycle
Every incoming question sent to POST /api/v1/phinsiq/chat flows through this sequential, fail-safe 10-stage execution pipeline in app/pipeline/pipeline.py:
institution_id and role permissions matrix in MongoDB.fields definitions.POST with {"row_id": "{user_id}"} (or GET for calendar) via async httpx.βΉ50,000), dates, and status text.["/fees", "/attendance"]) and clickable suggestion chips.Every Module Explained with In-Depth NLP Text Analysis
When a user types a message (like "What is my pending fee?"), how does PhinsIQ know with 100% certainty that this belongs to the Fees module instead of Attendance or Homework? And how does it know the user wants the pending balance rather than the total fee? Below is the full step-by-step NLP text analysis breakdown for every module.
π° 1. Fees & Payment Module (fees)
Parents and students need instant, accurate updates on pending tuition fees, paid receipts, and payment deadlines without waiting in administrative queues.
Maps ERP installment structures, calculates total term fees vs pending balance, and formats currency cleanly with rupee symbols (βΉ).
- Text Normalization: Input
"What is my pending fee?"is converted to lowercase and tokenized into words:["what", "is", "my", "pending", "fee"]. - Module Classification (Why NOT Attendance or Homework?):
feesmatrix check: Tokens match keywords"pending"(+2.0) and"fee"(+3.0) → Score: 5.0 / 5.0 (Selected Winner)attendancematrix check: Looks for"present","absent","attendance"→ Score: 0.0 (Rejected)homeworkmatrix check: Looks for"homework","assignment"→ Score: 0.0 (Rejected)
- Sub-Field Specificity Matching (Why
pending_feeand NOTtotal_fee?):- Alias matching against MongoDB
fieldscollection forfees: pending_feealiases:["pending fee", "balance fee", "due fee"]→ RapidFuzztoken_set_ratio("what is my pending fee", "pending fee")= 100% Match!total_feealiases:["total fee", "full fee"]→token_set_ratio= 50%paid_feealiases:["paid fee", "amount paid"]→token_set_ratio= 50%
- Alias matching against MongoDB
- Pipeline Execution: Fetches ERP
POST /student/apiviewFeePaymentInfo, extractspending_fee: 29300, renders template"Your pending fee balance is {{pending_fee}}."→ Output: "Your pending fee balance is βΉ29,300." (Route:/fees).
"What is my pending fee?"
POST /student/apiviewFeePaymentInfo
{"row_id": "ST123"}
{"pending_fee": 29300, "total_fee": 50000}
Route: /fees
π
2. Attendance Tracking Module (attendance)
Schools record daily student attendance as raw arrays of 50β200 individual day records. Students need instant summary percentages and absent counts.
The array aggregator automatically counts present vs absent, computes percentage (51/61)*100 = 83.6%, and extracts specific absent dates.
- Tokenization:
"how many days was i absent"→["how", "many", "days", "was", "i", "absent"]. - Module Classification: Keyword
"absent"scores 4.0 for attendance (0.0 for fees, homework, calendar) → Selected:attendance. - Sub-Field Matching: Alias
"days absent"inabsent_countmatches with 95% RapidFuzz score → Target Field:absent_count. - Array Aggregation: Calls ERP
POST /student/apiviewAttendance, filters 61 records withstatus == "absent"→ Computesabsent_count = 10. - Output: "You have been absent for 10 days this academic year." (Route:
/attendance).
"how many days was i absent?"
[{"date":"2026-06-03","status":"present"}, ...] (61 items)
count_where(status='absent') = 10
Route: /attendance
π 3. Homework & Assignments Module (homework)
Students often forget daily assignments and homework deadlines assigned across multiple subjects (Math, Science, English).
Filters active pending homework, highlights submission dates, and allows subject-specific filtering (e.g. "What is my math homework?").
- Tokenization:
["show", "my", "pending", "homework"]. - Module Classification: Keyword
"homework"scores 5.0. (Even though "pending" is in fees, "homework" has 2x weight multiplier) → Selected:homework. - Filter Resolution:
status = "pending"→ DispatchesPOST /student/apimyHomeworkwith{"row_id": "9385"}. - Output: "You have 3 pending homework assignments: Math Chapter 4, English Essay, Physics Lab." (Route:
/homework).
π 4. Multi-Module Query NLP Analysis (e.g. "my attendance and total fee")
Users frequently ask questions combining two or more distinct concepts in a single sentence: e.g. "my attendance and total fee".
PhinsIQ detects both modules simultaneously, executes both ERP calls in parallel, independently renders each template, and returns both navigation routes in routes: ["/fees", "/attendance"].
- Tokenization:
["my", "attendance", "and", "total", "fee"]. - Multi-Module Classifier:
attendancescore = 5.0 (keyword:attendance)feesscore = 5.0 (keywords:total,fee)- Classifier detects
len(detected_modules) == 2→ Triggers Multi-Module Parallel Pipeline!
- Parallel ERP Calls:
- Call 1:
POST /student/apiviewAttendance→attendance_percentage = 83.6% - Call 2:
POST /student/apiviewFeePaymentInfo→total_fee = βΉ50,000
- Call 1:
- Template Rendering: Renders attendance template + fee template and concatenates with
\n\n. - Routes Array Generation: Returns
routes: ["/fees", "/attendance"].
"my attendance and total fee"
Fees POST β βΉ50,000
Attendance POST β 83.6%
Here is your attendance summary:
π Overall: 83.6% (51/61 days)"
routes: ["/fees", "/attendance"]
NLP, Intent Analysis & Fuzzy Matching Deep Dive
π The 3-Tier NLP Matching Pipeline Architecture
PhinsIQ processes every student question through three specialized matching tiers to achieve sub-millisecond accuracy without expensive LLM classification:
Checks MongoDB learned_patterns for exact or semantically equivalent questions verified by admins. If similarity is ≥ 75%, resolves intent in <1ms.
Computes keyword frequency scores across all enabled modules (fees, attendance, homework, etc.) using domain-weighted dictionaries to select single or multi-module paths.
Scans the detected module's field dictionary to determine whether the user is asking for a specific metric (e.g. pending_fee) or a full summary card.
β‘ RapidFuzz C++ SIMD Vectorization Explained
PhinsIQ uses RapidFuzz, a C++ implementation of the Levenshtein distance algorithm compiled with AVX2 SIMD instructions:
from rapidfuzz import fuzz
def _calculate_similarity(self, text_a: str, text_b: str) -> float:
# Token set ratio gives semantic word-order independence
token_score = fuzz.token_set_ratio(text_a, text_b)
# Exact Levenshtein sequence similarity ratio
ratio_score = fuzz.ratio(text_a, text_b)
# Weighted blend giving priority to semantic token overlap
return (token_score * 0.7) + (ratio_score * 0.3)
ERP Routing, HTTP Protocol & Aggregations
β‘ Strict HTTP Protocol Rules
| Module | HTTP Method | Endpoint Path | Payload Format |
|---|---|---|---|
fees | POST | /student/apiviewFeePaymentInfo | {"row_id": "{user_id}"} |
attendance | POST | /student/apiviewAttendance | {"row_id": "{user_id}"} |
homework | POST | /student/apimyHomework | {"row_id": "{user_id}"} |
notification | POST | /student/apimyNotificationsApi | {"row_id": "{user_id}"} |
profile | POST | /student/apiprofile | {"row_id": "{user_id}"} |
study_materials | POST | /student/apiviewstudyMaterials | {"row_id": "{user_id}"} |
calendar / holiday | GET | /student/apicalender/?row_id={user_id} | Query param in URL |
π‘οΈ Why In-Memory Array Aggregations Matter
Instead of making slow, repeated SQL database queries on school servers, PhinsIQ fetches the module payload once and executes lightning-fast memory operations in app/router/array_aggregator.py:
count_where: Computes counts matching specific conditions (e.g.status == "absent").percentage: Calculates formatted ratios (e.g.83.6%).filter_dates: Extracts sorted lists of absent dates or upcoming holiday dates.filter_by_key: Extracts arrays of pending homework assignments.
Claude AI Fallback & Dual-Layer Caching Engine
π€ Why Claude Haiku 4.5 & Strict Academic System Prompt
When a question cannot be answered by a single deterministic template (e.g. "How am I doing in school?" or "How can I improve my math grades?"), PhinsIQ routes the query to Claude Haiku 4.5 with full student ERP context.
The system prompt strictly forbids answering questions unrelated to school/education (e.g. movies, general trivia, coding puzzles), keeping the assistant 100% focused on student learning.
Restricting Claude responses to 500 tokens guarantees concise, punchy advice cards formatted in clean Markdown without bloated latency.
β‘ Dual-Layer Caching Architecture
Why: If a student asks "how is my academic performance" and 10 minutes later asks "how am i doing in school" (>= 50% RapidFuzz match), PhinsIQ retrieves the saved response from MongoDB claude_responses in 0ms at βΉ0 API cost!
Why: Uses cache_control: {"type": "ephemeral"} in system prompt and student context blocks with header "anthropic-beta": "prompt-caching-2024-07-31", cutting input token costs on Claude's server by 50%β90%!
Client Navigation Routes Array & Suggestion Engine
π§ Why routes: list[str] Array is Essential
Mobile and web applications need to know which screens to navigate to when a student receives an answer:
- When asking about Fees: returns
routes: ["/fees"]. - When asking a Multi-Module Query (Attendance + Fees): returns
routes: ["/fees", "/attendance"]. - When receiving a 360Β° Academic Snapshot: returns all active portal screens:
routes: ["/profile", "/fees", "/attendance", "/calendar", "/homework", "/notifications", "/study-materials"].
π‘ Dynamic 3-Question Suggestion Engine
Implemented in app/router/suggestion_engine.py, this engine generates exactly 3 highly contextual follow-up questions for every response, encouraging student engagement and portal exploration.
MongoDB Collections & Multi-Tenant Architecture
ποΈ MongoDB Schema Reference
| Collection Name | Why It Is Used | Stored Information |
|---|---|---|
institutions | Multi-tenant school configs | School ID, Base API URLs, enabled modules, custom module routes. |
roles | Access control matrix | Role ID (student, parent, staff), accessible module lists. |
fields | NLP query vocabulary | Field aliases, formats (currency, percentage), array aggregations. |
api_registry | ERP Endpoint mappings | Target URL, HTTP method (POST/GET), header parameters. |
templates | Response phrasing templates | Single field and summary response Markdown templates. |
learned_patterns | Verified NLP intents | Question pattern embeddings, verified answers. |
claude_responses | Persistent 6-hour cache | User ID, question, answer, token usage, timestamp (IST). |
Package & Technology Stack Deep Dive (Why, How & Code Examples)
Every dependency in PhinsIQ was specifically chosen to maximize execution speed (<50ms), asynchronous concurrency (10,000+ simultaneous students), memory efficiency, and bulletproof type safety. Below is the full breakdown of every package, why it was chosen over alternatives, how it works in PhinsIQ, and practical code examples.
β‘ 1. FastAPI (REST API Engine)
Flask and standard Django are synchronous (WSGI) β a single slow ERP call blocks the whole thread. FastAPI is natively asynchronous (ASGI), handling thousands of concurrent school queries per second on a single worker.
Orchestrates all incoming student chat requests at /api/v1/phinsiq/chat, validates payloads via Pydantic, manages DB connection lifespans, and automatically generates interactive Swagger documentation at /docs.
from fastapi import APIRouter, Depends, status
from app.models.chat import ChatRequest, ChatResponse
from app.pipeline.pipeline import pipeline
router = APIRouter(prefix="/phinsiq", tags=["Chat"])
# Native async endpoint with automatic request validation & OpenAPI docs
@router.post("/chat", response_model=ChatResponse, status_code=status.HTTP_200_OK)
async def chat_endpoint(request: ChatRequest) -> ChatResponse:
# Non-blocking async execution through 10-stage pipeline
return await pipeline.process(request)
ποΈ 2. Motor (Async MongoDB Driver)
Standard pymongo blocks the Python event loop while waiting for MongoDB network queries. motor wraps MongoDB with non-blocking asyncio primitives, allowing hundreds of concurrent DB queries without stalling.
Manages connection pooling to MongoDB Atlas for reading multi-tenant school configs (institutions), role permissions (roles), NLP aliases (fields), API routes (api_registry), and persistent 6-hour cache (claude_responses).
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
# Initialize async MongoDB connection pool
client: AsyncIOMotorClient = AsyncIOMotorClient(settings.mongodb_uri, maxPoolSize=50)
db: AsyncIOMotorDatabase = client[settings.mongodb_database]
# Non-blocking async query with index filtering
async def get_recent_claude_cache(institution_id: str, user_id: str, cutoff_time: datetime):
cursor = db.claude_responses.find({
"institution_id": institution_id,
"user_id": user_id,
"created_at": {"$gte": cutoff_time}
})
return await cursor.to_list(length=50)
π 3. RapidFuzz (High-Performance C++ String & Semantic Matching)
Standard Python fuzzy matching libraries (thefuzz, difflib) are written in pure Python and take 5msβ15ms per search. rapidfuzz is implemented in C++ with AVX2 SIMD vectorization, matching 100 aliases in < 0.2ms (15xβ30x faster).
1. Matches user questions to sub-fields (e.g. "fee total" -> total_fee).
2. Matches learned question patterns in MongoDB.
3. Computes the >= 50% semantic similarity threshold for persistent 6-hour Claude caching.
from rapidfuzz import fuzz
# Token Set Ratio: ignores word ordering ("my pending fee" vs "fee pending for me")
token_score = fuzz.token_set_ratio("my pending fee", "what is my pending fee balance") # -> 92.5
# Levenshtein Ratio: catches typos ("atendance" vs "attendance")
typo_score = fuzz.ratio("atendance", "attendance") # -> 94.7
# Persistent 6-Hour Cache >= 50% Match Evaluation:
for doc in recent_cached_docs:
similarity = (fuzz.token_set_ratio(user_question, doc["question"]) * 0.7) + (fuzz.ratio(user_question, doc["question"]) * 0.3)
if similarity >= 50.0:
return doc["answer"] # 0ms Instant Cache Hit!
π 4. Pydantic v2 (Rust-Powered Data Validation & Schema Engine)
Pydantic v2 is rewritten in Rust (pydantic-core), offering 5xβ15x faster parsing than v1 or Marshmallow, with strict type coercion and automatic JSON schema generation for APIs.
Validates all incoming payloads (ensuring non-empty strings, valid roles, allowed institutions), formats outgoing unified JSON responses (response, message, routes: [], suggestion_questions: []), and parses environment variables via BaseSettings.
from pydantic import BaseModel, Field
from typing import Optional
class ChatRequest(BaseModel):
institution_id: str = Field(..., min_length=1, description="Tenant school identifier")
role: str = Field(..., description="User role: student, parent, or staff")
user_id: str = Field(..., description="Student/Staff ID in school ERP")
message: str = Field(..., min_length=1, description="Natural language question")
class ChatResponse(BaseModel):
success: bool = True
response: str
message: str
routes: list[str] = Field(default_factory=list)
route: str = "/dashboard"
suggestion_questions: list[str] = Field(default_factory=list)
π 5. HTTPX (Next-Generation Async HTTP Client)
requests is completely synchronous and blocks the worker thread. httpx provides modern async/await support, HTTP/2 support, strict connection pooling, and standard timeout controls.
1. Calls school ERP endpoints asynchronously via HTTP POST with {"row_id": "{user_id}"} (or GET for calendar).
2. Calls Anthropic Claude Haiku 4.5 API with custom headers (anthropic-beta: prompt-caching-2024-07-31) and prompt caching content blocks.
import httpx
# Async ERP Call with connection pool & 10s strict timeout
async with httpx.AsyncClient(timeout=10.0) as client:
resp = await client.post(
"https://demo.parrophins.in/sjbhs/student/apiviewFeePaymentInfo",
json={"row_id": "ST123"},
headers={"Content-Type": "application/json"}
)
data = resp.json() # Non-blocking async response parsing
π 6. Structlog (Structured Observability & JSON Logging)
Standard logging dumps raw unindexed strings like "User 123 asked fee at 10:00" which cannot be queried or graphed. structlog generates structured key-value JSON log events with ISO timestamps, latency in milliseconds, and request correlation IDs.
Tracks request lifecycle, ERP latency (duration_ms=25), module detection scores, cache hits/misses, and Claude prompt caching token metrics (cache_read_input_tokens).
from app.core.logging import get_logger
logger = get_logger(__name__)
# Emits machine-readable JSON structured logs for Datadog / CloudWatch
logger.info(
"pipeline_response_generated",
request_id="req_8f2a1b",
institution_id="sjbhs",
modules=["fees", "attendance"],
claude_used=False,
duration_ms=32,
cache_hit=True
)
π 7. Jinja2 & String Formatting (Safe Response Templating Engine)
Raw string formatting (f"Your fee is {fee}") throws crashes if keys are missing or null. Jinja2 provides safe variable resolution, pluralization filters, fallback default strings, and clean Markdown formatting.
Renders scalar single-field responses (e.g. "Your total fee is {{total_fee}}.") and multi-line summary cards from MongoDB templates documents with zero risk of runtime crashes.
from jinja2 import Template
# Dynamic template rendered with mapped ERP variables
template_str = (
"Here is your attendance summary:\n\n"
"π Overall: {{attendance_percentage}}\n"
"β
Present: {{present_count}} days\n"
"β Absent: {{absent_count}} days\n"
"π
Total Classes: {{total_classes}} days"
)
rendered = Template(template_str).render({
"attendance_percentage": "83.6%",
"present_count": 51,
"absent_count": 10,
"total_classes": 61
})
π§ͺ 8. Pytest & Pytest-Asyncio (Automated Test & Verification Suite)
Pytest provides clean fixture dependency injection, native async/await test execution via pytest-asyncio, powerful mock patching, and compact test assertions without boilerplate class hierarchies.
Runs all 97 automated test cases across all ERP modules (fees, attendance, homework, calendar, profile, study materials, Claude prompt caching, multi-routes array, and admin endpoints) in under 50 seconds.
import pytest
from fastapi.testclient import TestClient
from app.main import app
@pytest.fixture
def client():
with TestClient(app) as c:
yield c
def test_multi_module_query_routes(client: TestClient):
"""Verify asking a query touching attendance and fees returns both routes."""
payload = {
"institution_id": "sjbhs",
"role": "student",
"user_id": "ST123",
"message": "tell me my attendance and fees"
}
resp = client.post("/api/v1/phinsiq/chat", json=payload)
assert resp.status_code == 200
data = resp.json()
assert data["success"] is True
assert "/attendance" in data["routes"]
assert "/fees" in data["routes"]
assert len(data["suggestion_questions"]) == 3
π 9. Uvicorn (Lightning-Fast ASGI Production Server)
Uvicorn is an ASGI web server implementation for Python powered by uvloop (a fast drop-in replacement for the asyncio event loop implemented in C) and httptools (Node.js HTTP parser written in C), delivering near C-speed HTTP request throughput.
Serves the live application on port 8001 (uvicorn app.main:app --reload --port 8001), handling WebSocket/HTTP request parsing, hot reloading during development, and graceful signal handling on shutdown.
Local Academic Subject Engine Architecture
βοΈ 1. Core Philosophy: Zero-LLM Deterministic Intelligence
Large Language Models (LLMs) can hallucinate intermediate arithmetic, introduce non-deterministic step sequences, add 1500ms+ network latency, and incur recurring per-token cloud API bills. For school curriculum questions (LKG through PUC / Grade 12), the rules of mathematics and laws of science are absolute and invariable.
PhinsIQ's Local Subject Engine executes directly inside FastAPI using exact symbolic engines (SymPy), unit engines (Pint), numeric solvers (NumPy), stoichiometry nullspace balancers, and rapid fuzzy ontology indices (RapidFuzz). Questions are parsed, computed with step-by-step mathematical proofs, and returned locally with 0 Claude API invocations.
Ensures administrative queries (fees, attendance, homework, calendar, profile) are routed to ERP data aggregators and never hijacked by academic solvers.
ScienceClassifier and regex pre-screeners rapidly identify whether a question is Mathematics, Physics, Chemistry, or Biology.
Dispatches to the specialized sub-engine to generate exact numeric results, applied laws/formulas, and formatted markdown cards.
Returns route: "NA" and routes: ["NA"] so client frontends display pure academic cards without triggering ERP screen changes.
Local Mathematics Engine (LKG β PUC / 18 Solvers)
π 18 Curriculum-Standard Mathematical Engines
Covers arithmetic fundamentals up through higher secondary differential calculus and linear algebra with step-by-step working:
BODMAS expressions, fraction additions/multiplications, prime factorization, HCF/GCD, LCM, and divisibility rules.
Single-variable linear equations ($ax+b=c$), algebraic term simplification, polynomial expansion, and factorization.
$ax^2+bx+c=0$, discriminant calculation ($\Delta = b^2-4ac$), real/complex roots, step-by-step quadratic formula & factoring.
Simultaneous 2-variable and 3-variable equations solved via Cramer's Determinant rule and elimination method.
Polynomial degree, roots/zeroes, long division algorithm, and Remainder Theorem validation.
Circles ($A=\pi r^2, C=2\pi r$), triangles, right-triangle hypotenuse ($a^2+b^2=c^2$), and polygon interior angles.
Surface area and volume of spheres, hemispheres, cylinders ($V=\pi r^2 h$), cones ($V=\frac{1}{3}\pi r^2 h$), and cuboids.
Exact standard angles ($\sin 30^\circ = 0.5, \tan 45^\circ = 1$), Pythagorean identities ($\sin^2\theta + \cos^2\theta = 1$), heights and distances.
Symbolic differentiation $\frac{d}{dx}$, definite/indefinite integration $\int f(x)dx$, chain rule, product rule, and quotient rule via SymPy.
Distance formula $d=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}$, section formula, midpoint, slope $m=\frac{y_2-y_1}{x_2-x_1}$, and line equation.
Matrix addition, scalar/matrix multiplication, determinant $|A|$, inverse $A^{-1}$, transpose $A^T$, and matrix rank.
Arithmetic Progression ($T_n = a + (n-1)d, S_n = \frac{n}{2}(2a+(n-1)d)$), Geometric Progression ($T_n = ar^{n-1}, S_n = \frac{a(r^n-1)}{r-1}$).
Permutations $nPr = \frac{n!}{(n-r)!}$, Combinations $nCr = \frac{n!}{r!(n-r)!}$, and Binomial theorem expansions.
Mean, median, mode, sample variance, population variance, standard deviation ($\sigma$), and range.
Classical probability $P(E)=\frac{n(E)}{n(S)}$, independent/mutually exclusive events, dice rolls, coin flips, and deck of cards.
Simple Interest ($I=\frac{PRT}{100}$), Compound Interest ($A=P(1+\frac{r}{n})^{nt}$), EMI monthly loan payments, Profit & Loss %.
Dimensionally-safe conversions across length, mass, temperature (Β°C, Β°F, K), volume, speed (km/h to m/s), and digital storage (MB to GB).
Curated theorems (Pythagoras, Thales Basic Proportionality, Remainder Theorem, Fundamental Theorem of Arithmetic) and definitions.
Local Science Engine (Physics, Chemistry & Biology)
β‘ 1. Physics Engine Subsystem
Dynamic solvers and curriculum concept knowledge bases:
Newton's 2nd Law ($F = m \cdot a$), equations of motion ($v=u+at$, $s=ut+\frac{1}{2}at^2$, $v^2=u^2+2as$), acceleration ($a=\frac{v-u}{t}$), momentum ($p=mv$).
Mechanical Work ($W=F \cdot d \cos\theta$), Kinetic Energy ($KE=\frac{1}{2}mv^2$), Gravitational Potential Energy ($PE=mgh$), Electrical/Mechanical Power ($P=W/t$).
Ohm's Law ($V = I \cdot R$), Electrical Power ($P=VI=I^2R=\frac{V^2}{R}$), Series Resistance ($R_s = R_1 + R_2$), Parallel Resistance ($\frac{1}{R_p} = \frac{1}{R_1} + \frac{1}{R_2}$).
Wave velocity ($v = f \cdot \lambda$), period ($T = 1/f$), Echo sonar ($d = \frac{vt}{2}$), Lens/Mirror power ($P = 1/f$), Lens formula ($\frac{1}{f} = \frac{1}{v} - \frac{1}{u}$), Snell's Law.
Truth tables and Boolean laws for AND ($Y=A\cdot B$), OR ($Y=A+B$), NOT ($Y=\bar{A}$), NAND, NOR, and XOR gates, P-N junction diodes.
Newton's 3 Laws of Motion, Universal Law of Gravitation ($F=G\frac{m_1m_2}{r^2}$), Speed vs Velocity, Refraction, and Photoelectric Effect.
π§ͺ 2. Chemistry Engine Subsystem
Covers common compounds, periodic elements, reaction balancing, molar mass, and pH:
Instant lookup for curriculum compounds: Water ($\text{H}_2\text{O}$), Heavy Water ($\text{D}_2\text{O}$), Common Salt ($\text{NaCl}$), Baking Soda ($\text{NaHCO}_3$), Washing Soda ($\text{Na}_2\text{CO}_3\cdot 10\text{H}_2\text{O}$), Bleaching Powder ($\text{CaOCl}_2$), Quicklime ($\text{CaO}$), Slaked Lime ($\text{Ca(OH)}_2$), Limestone ($\text{CaCO}_3$), Plaster of Paris ($\text{CaSO}_4\cdot \frac{1}{2}\text{H}_2\text{O}$), Blue Vitriol ($\text{CuSO}_4\cdot 5\text{H}_2\text{O}$), Glucose ($\text{C}_6\text{H}_{12}\text{O}_6$), Sucrose, Methane, Ethanol, Rust, Ozone, etc.
Atomic numbers ($Z$), Atomic masses ($u$), Valency, Electronic Configurations (e.g. $[\text{Ar}]\; 4s^2 3d^6$), Groups, Periods, and Blocks ($s, p, d, f$).
Parses complex parenthesized formulas $\text{Al}_2(\text{SO}_4)_3$, hydrates $\text{CuSO}_4\cdot 5\text{H}_2\text{O}$, and lowercase student inputs (h2so4), computing molar mass and elemental mass percentages.
Uses integer null-space matrix reduction to balance chemical reactions: $2\text{H}_2 + \text{O}_2 \to 2\text{H}_2\text{O}$, $4\text{Fe} + 3\text{O}_2 \to 2\text{Fe}_2\text{O}_3$, $\text{CH}_4 + 2\text{O}_2 \to \text{CO}_2 + 2\text{H}_2\text{O}$, $\text{CaCO}_3 + 2\text{HCl} \to \text{CaCl}_2 + \text{CO}_2 + \text{H}_2\text{O}$.
Calculates acidity/basicity: $\text{pH} = -\log_{10}[\text{H}^+]$, $\text{pOH} = -\log_{10}[\text{OH}^-]$, and $\text{pH} + \text{pOH} = 14$ at 25Β°C.
π¬ 3. Biology Engine Subsystem
Cell biology ontology, human physiology, and structured markdown difference tables:
Cell organelles (Mitochondria "Powerhouse of the cell", Chloroplast, Nucleus, Ribosomes), Photosynthesis ($6\text{CO}_2 + 6\text{H}_2\text{O} \to \text{C}_6\text{H}_{12}\text{O}_6 + 6\text{O}_2$), Transpiration, Osmosis, Human Physiology (Circulatory system, Kidneys/Nephrons, Brain/Neurons, Digestion), Mendel's Genetics, and Ecology (Food chains & Trophic levels).
Generates structured comparison tables for exam questions:
β’ Mitosis vs Meiosis (Equational vs Reductional division)
β’ Xylem vs Phloem (Water unidirectional vs Food bidirectional)
β’ Arteries vs Veins (Oxygenated high pressure vs Deoxygenated valves)
β’ Plant Cell vs Animal Cell (Cell wall, chloroplast vs Centrioles)
β’ Aerobic vs Anaerobic Respiration (36-38 ATP vs 2 ATP / Lactic acid)
β’ DNA vs RNA (Double stranded deoxyribose vs Single stranded ribose/uracil)
Subject Engine REST API Reference
π‘ Dedicated Academic Solve Endpoints
| Method | Endpoint | Description | Payload Example |
|---|---|---|---|
| POST | /api/v1/subject-engine/mathematics/solve |
Solves mathematical questions directly via the 18 specialized math solvers. | {"question": "solve 2x + 5 = 15"} |
| POST | /api/v1/subject-engine/science/solve |
Solves physics, chemistry, and biology academic questions locally. | {"question": "what is formula of water"} |
| POST | /api/v1/subject-engine/solve |
Universal academic solver: auto-classifies question into math or science. | {"question": "calculate kinetic energy if m=2kg, v=3m/s"} |
| GET | /api/v1/subject-engine/concepts |
Returns the ontology concepts catalog filtered by subject or topic. | ?subject=physics&topic=mechanics |
// POST /api/v1/subject-engine/solve
{
"question": "what is the formula of water"
}
// Response (200 OK β Handled locally in 3.4ms)
{
"handled_locally": true,
"subject": "chemistry",
"topic": "chemical_compounds",
"intent": "FORMULA_LOOKUP",
"answer": "HβO",
"formatted_markdown": "### π§ͺ **Water (HβO)** (Chemistry)\n\n#### π **Chemical Information:**\n- **Chemical Formula:** # **`HβO`** (`H2O`)\n- **Chemical Name:** Dihydrogen Monoxide\n- **Molar Mass:** `18.015 g/mol`\n...",
"confidence": 0.99,
"execution_time_ms": 3.42
}
Automated Testing & Quality Assurance (171 / 171 Tests)
π§ͺ Complete 20-File Test Coverage Matrix
| Test File | Tests | Subsystem Focus Area | Result |
|---|---|---|---|
tests/test_website_engine.py | 13 | Web crawler, HTML cleaner, semantic chunker, RapidFuzz knowledge search, role="website". | PASSED |
tests/test_mathematics_engine.py | 19 | 18 Math engines, SymPy calculus, matrices, algebra, quadratic, Pint units. | PASSED |
tests/test_physics_engine.py | 9 | Kinematics, F=ma, energy, electricity, waves, logic gates, optics. | PASSED |
tests/test_chemistry_engine.py | 10 | Periodic table, molar mass, chemical balancer, compounds, pH. | PASSED |
tests/test_biology_engine.py | 5 | Cell biology ontology, difference tables (mitosis/meiosis), genetics. | PASSED |
tests/test_math_pipeline_integration.py | 5 | End-to-end chat pipeline math integration, route="NA", zero Claude. | PASSED |
tests/test_science_pipeline_integration.py | 6 | End-to-end science pipeline chat integration, water formula, route="NA". | PASSED |
tests/test_subject_engine_api.py | 3 | Subject Engine REST endpoints (/mathematics/solve, /science/solve, /concepts). | PASSED |
tests/test_academic_overview.py | 7 | 360Β° Academic snapshot, parallel ERP fetching, all module routes. | PASSED |
tests/test_admin.py | 3 | Institution config CRUD, API registry updates, template overrides. | PASSED |
tests/test_calendar_holiday.py | 18 | School calendar, holidays, reopening dates, date sorting. | PASSED |
tests/test_claude_fallback.py | 6 | Haiku 4.5 integration, MongoDB 6-hour cache, prompt caching headers. | PASSED |
tests/test_homework.py | 9 | Pending homework, subject homework, submission deadlines. | PASSED |
tests/test_notification.py | 9 | Circulars, notices, category filtering, urgent alerts. | PASSED |
tests/test_phase1.py | 11 | Fees, attendance, role permission security checks. | PASSED |
tests/test_profile.py | 11 | Personal profile, admission number, parents info, emergency contacts. | PASSED |
tests/test_routes_and_suggestions.py | 7 | Multi-route array (routes: []), 3 suggestions engine. | PASSED |
tests/test_semantic_matcher.py | 4 | RapidFuzz thresholding, token matching, learned patterns. | PASSED |
tests/test_study_materials.py | 12 | Study resources, syllabus portions, chapter downloads. | PASSED |
tests/test_questions_endpoint.py | 18 | MongoDB sample question catalog, client seeding, CRUD admin endpoints. | PASSED |
Website Crawler, HTML Cleaner, Semantic Chunker & Knowledge DB Subsystem (role: "website")
π Complete Architectural Flow
When an administrator configures school website links (e.g. https://sjbhs.edu.in/, https://sjbhs.edu.in/overview) for an institution (e.g. sjbhs), the crawler fetches the HTML, removes boilerplate (navbars, scripts, footers, cookie banners), splits text into cohesive semantic sections, and indexes them into MongoDB (website_knowledge). When a user asks a question with role: "website", PhinsIQ performs a multi-factor RapidFuzz search across the knowledge base and delivers a verified answer instantly (<10ms, βΉ0 cost, zero Claude fallback, route: "NA").
https://sjbhs.edu.in/, Overview: https://sjbhs.edu.in/overview) via REST API or Admin Studio.httpx.AsyncClient to fetch web pages concurrently with custom User-Agent, redirect following, and connection timeouts.website_knowledge collection with in-memory TTL caching for instant lookup./api/v1/chat with institution_id: "sjbhs" and role: "website".token_set_ratio and keyword matching, generates clean Markdown cards with official source citations, and returns route: "NA".π¦ Package Architecture Breakdown
| Module File | Primary Responsibilities | Key Classes & Functions |
|---|---|---|
app/website_engine/models.py |
Pydantic models for URL entries, crawled pages, semantic sections, search hits, and answers. | WebsiteUrlEntry, CrawlRequest, KnowledgeSection, CrawledPage, WebsiteSearchHit, WebsiteAnswer |
app/website_engine/crawler.py |
Async HTTP crawler with rate limiting, timeouts, and multi-URL concurrency. | WebsiteCrawler.crawl_pages(), WebsiteCrawler.crawl_single_page() |
app/website_engine/cleaner.py |
Boilerplate removal, script/style stripping, and structured block extraction. | HtmlContentCleaner.clean() |
app/website_engine/chunker.py |
Heading-based chunking into coherent sections with auto-keyword extraction. | SemanticChunker.chunk_document() |
app/website_engine/repository.py |
MongoDB website_knowledge collection with pre-seeded data for SJBHS and SAGS. |
WebsiteRepository.save_page(), WebsiteRepository.get_pages(), WebsiteRepository.get_all_sections() |
app/website_engine/searcher.py |
Multi-factor RapidFuzz semantic matcher across titles, text, and keyword tags. | WebsiteKnowledgeSearcher.search() |
app/website_engine/answer_generator.py |
Synthesizes clean markdown cards with official link citations and prompt suggestions. | WebsiteAnswerGenerator.generate_answer() |
app/website_engine/engine.py |
Central coordinator coordinating crawl, index, search, and answer pipelines. | WebsiteEngine.crawl_and_index(), WebsiteEngine.search_and_answer() |
app/api/v1/website.py |
Admin REST endpoints for crawling, page listing, section inspection, and test queries. | POST /admin/website/crawl, GET /admin/website/pages, POST /admin/website/test-search |
π¬ Example Request, Output & Route Behavior
When sending a request with role: "website", the response route is always set to "NA" and routes: ["NA"]:
{
"institution_id": "sjbhs",
"role": "website",
"user_id": "st123",
"message": "tell me about sjbhs overview and history"
}
{
"success": true,
"route": "NA",
"routes": ["NA"],
"response_type": "website_knowledge",
"claude_used": false,
"execution_time_ms": 2.4,
"message": "### π **St. Joseph's Boys' High School (SJBHS) β Overview**\n\nSt. Joseph's Boys' High School (SJBHS) is a premier Jesuit Catholic educational institution located on Museum Road in Bangalore, Karnataka, India. Established in 1858...\n\nπ **Source:** [https://sjbhs.edu.in/overview](https://sjbhs.edu.in/overview)"
}