Jasika Logo Jasika AI Portal

Jasika AI Model Architecture & System Features

Welcome to the comprehensive technical documentation for the Jasika AI Platform. Jasika AI is an advanced, multi-modal artificial intelligence engine developed by Maa Saraswati Mentors (MSM Class) and MSMEdu. Built specifically for educational excellence, the Jasika AI Model natively powers text completions, cognitive reasoning, document analysis, vision processing, and image generations.

Operating as a low-latency, edge-native neural engine, Jasika AI processes client requests close to the geographical location of the requesting browser, eliminating cold starts and delivering real-time responses. This document details the Jasika AI Model execution pipeline, cognitive reasoning stages, vision processing, and atomic database persistence.

1. System Overview & Jasika Model Pipeline

The Jasika AI architecture is structured around high-concurrency execution, zero-knowledge security, and multi-modal synthesis. All user queries pass through the multi-stage Jasika AI Engine:

Figure 1.1: Jasika AI Model Multi-Modal Pipeline
graph TD A[Client Request / Web Portal] --> B[Edge Routing & HTTPS Gateway Layer] B --> C[OIDC Authentication & Web Crypto Security Layer] C --> D[Business Logic & Plan Limits Enforcement Layer] D --> E[Jasika Multi-Modal AI Engine] E --> F[Atomic Storage Layer / Cloudflare KV Database]

1.1 Core Pipeline Walkthrough

The Jasika AI Engine operates modularly, separating user authentication and quota controls from multi-modal AI synthesis:

  • Presentation & Portal Layer: Renders visual assets, documentation panels, the plans comparative dashboard, and the ChatGPT-inspired real-time messaging interface. Communicates via REST APIs and server-sent events (SSE).
  • Context Adapter & Gateway Layer: Intercepts requests at the edge node, extracting visitor timezone, region, and local clock references to dynamically adapt the prompt context for the Jasika Model.
  • Authentication & Security Layer: Enforces OIDC JWT session validation and encrypts secure server keys in-memory using Web Crypto AES-GCM 256-bit encryption.
  • Business Logic & Quota Engine: Checks daily quota states from KV storage, tracking text completions and image generation metrics per user tier.
  • Jasika Multi-Modal Core: Executes text synthesis, cognitive reasoning extraction (streaming <think> blocks), document text extraction, vision analysis, and neural image generation with 60% opacity watermarks.

1.2 System Execution Lifecycle

Every HTTP request follows a strict lifecycle. When a request hits the system, the edge worker initializes an execution context and routes it through global CORS middleware. For version 2 (/api/v2/) API endpoints, the worker extracts the Authorization: Bearer <token> header and validates the identity token. Once verified, identity parameters (roles, daily quotas, client ID) are bound to the request object. The worker then invokes the Jasika AI Model handler, streams the response to the user's browser, and updates KV conversation state atomically.

2. Edge Router & Gateway Pipeline

The gateway serves as the single entry point for all API calls and frontend routes. When a request hits the edge worker, it enters the global routing loop within `index.js`. The edge routing engine evaluates the request URL path and HTTP verb to forward to appropriate subsystems. Crucially, versioning is strictly enforced between `/api/v1/` and `/api/v2/` routes, protecting legacy applications while supporting modern OIDC flows.

This edge routing pipeline is completely stateless. It relies on the environment variables defined within `wrangler.toml` and bound resources (such as KV storage namespaces) to interact with external targets. By avoiding persistent TCP connections and container state, the system is resilient to centralized backend crashes, scaling automatically to handle millions of simultaneous queries.

2.1 Detailed Gateway Pipeline Processing

The router carries out incoming sanitization and headers injection before delegating execution. The following actions occur in sequence:

  1. CORS Resolution: Verifies the request origin against allowed hostnames. Injects CORS headers to support browser fetch capabilities.
  2. Environment Validation: Checks that all required server-side bindings (KV storage, API credentials, and signing secrets) are available before processing requests. If any are missing, a descriptive error is returned immediately.
  3. Static Asset Serving: Matches known static asset paths and serves them directly from memory-embedded bundles, avoiding any external file round-trips.

2.2 Gateway Architecture Overview

The gateway entrypoint acts as the central coordinator for all inbound traffic. It imports subsystems dynamically and maintains a minimal memory footprint — enabling extremely fast cold starts. The routing engine pattern evaluates URL paths and HTTP methods to forward each request to the appropriate handler: static assets, versioned API endpoints, authentication flows, or HTML page templates.

"By executing fully within Cloudflare Workers edge nodes, request latency is minimized. Response headers are injected directly at the edge, reducing typical time-to-first-byte (TTFB) metrics by up to 70%."

3. OIDC SSO Pipeline

Jasika AI delegates OIDC OAuth2 single sign-on credentials to the MSM Class authentication platform at `https://msmclass.in`. The integration follows the strict Authorization Code Grant Flow with PKCE/State validation. When the user initiates a sign-in, the gateway creates a cryptographically random state parameter, stores it to verify against callbacks, and redirects the browser to the authorization endpoint.

By outsourcing authentication to the central MSM Class platform, Jasika AI remains light and avoids managing raw user credentials, credentials databases, or password resets. Security mapping is carried out in transit during OIDC token exchanges, ensuring real-time roles sync between platforms.

Figure 3.1: SSO Authorization Code Flow Diagram
sequenceDiagram participant User as User Browser participant Worker as Jasika AI Worker participant Provider as MSM Class Auth Server User->>Worker: GET /api/v2/auth/login Worker-->>User: 302 Redirect (Authorize URL + Client ID + State) User->>Provider: Consent & Authenticate Provider-->>User: 302 Redirect to /callback?code=...&state=... User->>Worker: GET /api/v2/auth/callback Worker->Provider: Token Exchange Provider-->>Worker: 200 OK (User Identity Token) Worker->>Worker: Validate Identity & Map Plan Tier Worker-->>User: Render Success page & Save LocalStorage

3.1 User Plan Assignment

Upon successful authentication, the platform automatically assigns each user to a plan tier based on their profile. The platform administrator can configure and create any number of custom plan tiers from the Admin Dashboard. Plan assignments and individual usage quotas can be overridden per user at any time, providing flexible access control without requiring user re-authentication.

  • Platform Administrators: Receive elevated access including the Admin Dashboard, with configurable or unlimited daily quotas.
  • All Other Users: Default to the platform's base free plan. Admins may upgrade any user to any custom plan configured in the system.

3.2 Session Token Lifecycle

After a successful token exchange, the platform issues a short-lived, signed session token bound to the authenticated user's identity. This token carries plan tier information and is used to authorize subsequent API calls. Tokens are issued with a configurable expiry window and automatically expire, requiring users to re-authenticate. No sensitive credentials are stored in the browser or accessible from client-side code.

4. Plan Quota Engine & KV Storage

Usage quotas are checked on every API call. The plan quota engine splits checks into text completions and image generation quotas, storing them under distinct keys to prevent locking database tables. The quota check uses a rolling date format, `usage:[type]:[client_id]:[yyyy-mm-dd]`, ensuring daily limits auto-reset at midnight UTC.

This design handles thousands of concurrent increments. The limits check resolves instantly, preventing DB congestion. The admin panel can override these counts for a particular client identifier, adding dynamic allowances without altering default tier configurations.

Figure 4.1: Rate Limiting & Quota Validation Flow
flowchart TD A[Client Request] --> B{Valid JWT?} B -- No --> C[401 Unauthorized] B -- Yes --> D{Is Admin?} D -- Yes --> E[Bypass Limits] D -- No --> F[Get Mapped Plan Tier] F --> G[Query KV for Daily Limit Configs] G --> H[Read Current Usage usage:text & usage:image] H --> I{Usage >= Limit?} I -- Yes --> J[429 Too Many Requests] I -- No --> K[Allow Execution] K --> L[Update Usage Counter +1 in KV]

4.1 Key Storage Structures

All configurations are saved within Cloudflare Key-Value (KV) storage, offering high availability. Key namespaces are structured as follows:

  • plan:config:[plan_name]: Stores the daily default quotas set by the admin (e.g. `{"text_limit": 50, "image_limit": 5}`).
  • user:plan:[client_id]: Stores user-specific plan overrides configured by an admin. If present, it takes precedence over the default plan tier quotas.
  • usage:[type]:[client_id]:[date]: Real-time counter of current operations carried out today.

4.2 Quota Enforcement Design

On each API request, the quota engine performs a fast read-check against the relevant usage key, compares the value against the plan's configured limit, and atomically increments the counter on success. The check-and-increment pipeline is designed for high concurrency and resolves in single-digit milliseconds, ensuring no significant latency is added to API responses. If the daily quota is exhausted, the gateway returns a 429 Too Many Requests response with clear retry guidance.

5. Document Processor & Jasika Stream Engine

To support interactive student-tutor learning, Jasika AI includes a document processing engine that parses multi-part form-data inputs. It extracts text contents from uploaded files, formats them with system rules, and passes them to the Jasika Model context pipeline. It also provides a streaming Server-Sent Events (SSE) engine that delivers real-time response tokens and reasoning deltas.

The Jasika parser processes file streams chunk by chunk without reading entire files into memory at once, supporting document uploads up to 20MB at edge speeds.

5.1 Document Splicing Pipeline

When a user attaches a document (PDF, CSV, JSON, or TXT) alongside a prompt, the Jasika Document Handler parses the multi-part request, extracts raw content, and formats it for the Jasika AI Model:

[System Context]
Attached Document (${file_name}):
----------------------------------------
${extracted_file_text}
----------------------------------------
User Question: ${user_prompt}
This context is fed into the Jasika Model, enabling context-aware Q&A over study materials, board exams, and curriculum guides.

6. Cryptography & Web Crypto Security

Jasika AI employs a zero-knowledge approach to secret management — no access credentials or API keys are stored in plain text in any database, session store, or log file. All sensitive values are encrypted server-side using industry-standard AES-GCM symmetric encryption before being embedded in a session token.

This architecture ensures that even if any storage layer is compromised, no usable credentials can be extracted. All decryption occurs exclusively in-memory during active request processing and is never written to disk or forwarded downstream.

6.1 Zero-Knowledge Secret Management

The platform uses industry-standard symmetric encryption to protect access credentials in transit. Server-side API keys are never stored in plain text in any database or session store. Instead, they are encrypted at the point of authentication using a key derived from the server's signing secret, and the encrypted payload is embedded in the session token issued to the user.

Each encryption operation uses a fresh, randomly generated initialization vector (IV), ensuring that no two encryption outputs are identical — even for the same input. This prevents pattern analysis and replay attacks.

The encryption scheme employs AES-GCM with 256-bit keys, providing both confidentiality and integrity guarantees. All cryptographic operations are performed in-memory using the Web Crypto API — a native, audited implementation available in all modern browser and edge runtime environments.

6.2 Runtime Decryption Model

Encrypted credentials are only decrypted in-memory during active request processing. The decrypted value is used exclusively for the duration of that request and is never persisted, logged, or forwarded. If the session token is compromised, the attacker cannot recover the underlying credentials without also having access to the server's signing secret — which is never exposed to clients or included in any response.

7. Jasika Cognitive Engine, KaTeX Math & Neural Image Generation

Jasika AI V2 introduces advanced cognitive reasoning extraction, OpenAI ChatGPT-grade Markdown rendering, native LaTeX typesetting with KaTeX, and Jasika Neural Image Generation with automatic watermarking.

7.1 Jasika Cognitive Reasoning (<think>)

When solving complex mathematical, scientific, or logical problems, the Jasika AI Model streams reasoning deltas in real time enclosed within <think>...</think> tags. The frontend dynamically renders these into a collapsible 💭 Thought for a moment header block while persisting the complete reasoning history into Cloudflare KV conversation memory.

Figure 7.1: Jasika AI Reasoning & History Persistence Pipeline
flowchart TD A[Jasika Model SSE Stream] --> B{Contains Reasoning?} B -- Yes --> C[Extract Reasoning Delta to <think> Block] B -- No --> D[Append Visible Content] C --> E[Update Collapsible 💭 Thought Panel] D --> F[Render GFM Markdown & KaTeX] E --> G[Stream Completed] F --> G G --> H[Combine <think> Reasoning + Answer] H --> I[Atomic Save to Cloudflare KV History Store]

7.2 Jasika Neural Image Generation & Watermarking

The Jasika AI Model generates visual artwork, diagrams, and SVGs based on user prompts. All generated images feature an integrated 60% opacity watermark (Jasika AI · ai.msmclass.in) displayed in the bottom-right corner of the UI container and baked into downloaded PNG files via HTML5 Canvas rendering.

7.3 GFM Markdown Tables & KaTeX Math Suite

Responses format complex data using GitHub Flavored Markdown (GFM) tables, blockquotes, horizontal rules, and language-tagged code blocks (with 1-click copy buttons and message action toolbars). Standalone equations ($$...$$) and inline formulas ($...$) are typeset dynamically via KaTeX.

7.4 Atomic KV Batch History Deletion

To eliminate race conditions when deleting multiple chat sessions, Jasika AI routes bulk deletions through /api/v2/chat/history/batch-delete. The backend executes a single-pass mutation over the user's index key (chat:index:${clientId}) and deletes associated conversation keys atomically in a single network round-trip.

8. API Specifications (OpenAPI Spec)

The gateway serves documentation endpoints under `/docs` and the OpenAPI YAML definition directly. Clients can use the following version 2 (V2) routes:

paths:
  /api/v2/auth/login:
    get:
      summary: Redirect to MSM Class SSO Page.
  /api/v2/auth/callback:
    get:
      summary: Exchange code and issue Jasika JWT.
  /api/v2/user/limits:
    get:
      summary: Fetch visitor plan tiers and active KV quotas usage today.
  /api/v2/admin/plans:
    post:
      summary: Create client limit overrides (Admin only).
  /api/v2/admin/plan-configs:
    post:
      summary: Modify baseline default plans quotas configuration (Admin only).
  /api/v2/admin/logs:
    get:
      summary: Retrieve system access logs (Admin only).