1. System Overview & Problem Statement
Modern higher-education platforms suffer from critical structural deficiencies: fragmented student data pipelines, severe institutional latency in feedback loops, and a systemic failure to protect learner data sovereignty. Cloud-only architectures routinely expose sensitive academic interactions to third-party telemetry, while off-the-shelf generative models hallucinate domain-specific concepts, violating the foundational rigorous standards required in advanced pedagogical settings.
To resolve these challenges, fellow Subhradip Das engineered Gayatri Demo Main during an intensive 60-day engineering sprint at DBERT (Digital Blinc Education Research and Technology). Gayatri is an institution-grade, secure adaptive learning ecosystem featuring strict Retrieval-Augmented Generation (RAG) grounding and a local-first operational paradigm. The platform models Socratic pedagogical frameworks, dynamically scaling interaction models to evaluate student comprehension while maintaining strict data boundaries. Building this system required production-tier full stack execution—ensuring zero data leakage, sub-second query evaluation, and an immutable audit trail for academic evaluations.
- Production Source Code: https://github.com/buildswithSubhra/Gayatri-Demo-main.git
- Interactive Live Deployment: https://gayatri-demo-main.dbert.in
- DBERT Verified Credential: https://dbert.in/verify/CERT-DBERT-2026-FSD-043
- Pre-Screening Rubric Score: 81/100 (High Merit)
2. Architectural Blueprint & Technical Stack Decisions
Gayatri adopts a decoupled, event-driven micro-monolithic architecture designed for horizontal scalability and low-latency local-first execution. The frontend is built using React and TypeScript, leveraging strict interface definitions and state machines to manage real-time Socratic dialogue streams. The backend rests on a robust FastAPI/Node.js hybrid runtime, interfacing with a localized vector store and a relational PostgreSQL database managed via Prisma ORM.
The following ASCII diagram illustrates the end-to-end data flow across the client interface, API gateway, core domain engines, storage layers, and asynchronous background worker pipelines:
+-------------------------------------------------------------------+
| Client Layer (React / TS) |
+-------------------------------------------------------------------+
|
HTTPS / WSS (JSON Payload / JWT Auth)
v
+-------------------------------------------------------------------+
| API Gateway & Reverse Proxy (NGINX) |
+-------------------------------------------------------------------+
|
Internal REST / gRPC Bus
v
+-------------------------------------------------------------------+
| Core Domain Engine (FastAPI / Node.js) |
| +--------------------+ +--------------------------------+ |
| | Auth & RBAC Engine | | Socratic Pedagogy Orchestrator | |
| +--------------------+ +--------------------------------+ |
+-------------------------------------------------------------------+
| |
v v
+------------------+ +------------------------------+
| Relational DB | | Vector & Document Store |
| (PostgreSQL/Prisma)| | (Chroma / Local Embeddings) |
+------------------+ +------------------------------+
| |
+------------------+-------------------+
|
v
+-------------------------------------------------------------------+
| Asynchronous Background Workers (Celery / Redis) |
+-------------------------------------------------------------------+Key architectural decisions prioritize strict schema validation via Pydantic, atomic transaction rollbacks for student state modifications, and asynchronous vector indexing to prevent blocking I/O operations during active student assessment sessions.
3. Core Implementation & Engineering Highlights
Socratic RAG Pipeline & Guardrails
To prevent model hallucinations in academic contexts, the platform implements a dual-stage retrieval engine. User queries pass through an aggressive sanitization layer before vector similarity search execution. Retrieved context chunks are scored using cross-encoder rerankers, ensuring only high-confidence documents are injected into the LLM context window.
from typing import List, Dict, Any
from pydantic import BaseModel, Field
import structloglogger = structlog.get_logger()
class QueryPayload(BaseModel): student_id: str = Field(..., description="Unique immutable student identifier") session_id: str = Field(..., description="Active session token") raw_query: str = Field(..., min_length=3, max_length=1000)
class SocraticEngine: def __init__(self, vector_store, reranker, confidence_threshold: float = 0.82): self.vector_store = vector_store self.reranker = reranker self.threshold = confidence_threshold
async def evaluate_and_retrieve(self, payload: QueryPayload) -> Dict[str, Any]: try: logger.info("Initiating vector search", student_id=payload.student_id) raw_docs = await self.vector_store.asimilarity_search(payload.raw_query, k=5)
ranked_docs = self.reranker.rank(payload.raw_query, raw_docs) top_matches = [doc for doc in ranked_docs if doc.score >= self.threshold]
if not top_matches: logger.warn("Low RAG grounding confidence detected", query=payload.raw_query) return { "status": "fallback", "response": "Let's break this down further. Can you rephrase your hypothesis based on the core reading?" }
return { "status": "grounded", "context": [doc.content for doc in top_matches] } except Exception as exc: logger.error("Critical failure in Socratic pipeline", error=str(exc)) raise RuntimeError("Internal domain processing error.") from exc ```
Prisma ORM State Management & Transaction Safety
Student assessment progress and telemetry are managed with strict transactional guarantees to prevent race conditions during concurrent updates.
import { PrismaClient } from '@prisma/client';const prisma = new PrismaClient();
export async function recordStudentInteraction( studentId: string, sessionId: string, interactionScore: number ): Promise<void> { try { await prisma.$transaction(async (tx) => { const session = await tx.learningSession.findUniqueOrThrow({ where: { id: sessionId }, });
await tx.interactionLog.create({ data: { studentId, sessionId: session.id, score: interactionScore, timestamp: new Date(), }, });
await tx.studentProgress.upsert({
where: { studentId },
update: { cumulativeScore: { increment: interactionScore }, lastActive: new Date() },
create: { studentId, cumulativeScore: interactionScore, lastActive: new Date() },
});
});
} catch (error) {
console.error(Transaction failed for student ${studentId}:, error);
throw new Error('Failed to persist academic telemetry.');
}
}
```
4. Engineering Hurdles, Edge Cases & Performance Tuning
- Context Window Latency & Token Bloat: Initial benchmarks revealed that loading broad educational syllabi into context inflated request latencies past 3.2 seconds. This was mitigated by implementing a semantic chunking algorithm with sliding token windows and redis caching for frequent syllabus queries, dropping response times below 450ms.
- Race Conditions in Concurrent Assessment Submissions: During high-concurrency simulation stress tests, multiple asynchronous submissions by the same student caused database deadlocks at the Prisma client level. Implementing strict row-level locking (
SELECT ... FOR UPDATE) inside isolated PostgreSQL transaction blocks eliminated concurrency anomalies. - Prompt Injection & Payload Sanitization: Malicious student inputs attempted to override Socratic prompt boundaries. This was resolved by constructing a strict regex-based input normalization layer coupled with systemic prompt-hardening templates that enforce instructional constraints prior to model evaluation.
5. Deployment, Live Verification & Reflections
Gayatri Demo Main is deployed on a production-hardened cloud cluster utilizing automated CI/CD pipelines, containerized via Docker, and orchestrated with strict resource limitations.
Following formal evaluation against the 9-dimension DBERT Engineering Rubric, Subhradip Das secured an 81/100 (High Merit) rating. Evaluators particularly highlighted the system's robust data sovereignty design, fault-tolerant RAG grounding, and clean full-stack architectural separation.
Key Takeaways - Data Sovereignty is Non-Negotiable: Building local-first execution pathways ensures student data integrity while maintaining enterprise scalability. - Defensive Engineering: Anticipating edge cases in AI-human interactions (such as prompt injections and grounding hallucinations) requires multi-layered validation from client input to persistence layers.
Interested in building production AI & Full Stack systems with 1:1 mentorship and verified credentials? Explore the [DBERT AI Fellowship](https://lms.dbert.in).