Skip to content

About

Provides Islamic prayer postural adjustment advice using a source-based RAG architecture grounded in biomechanics and verified Islamic sources.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

85 Commits

Folders and files

Repository files navigation

sdk docker
title SujudSense
emoji πŸ•‹
colorFrom gray
colorTo blue
pinned false

SujudSense

til

SujudSense is an AI-powered coaching assistant designed to help Muslims safely adapt their prayer postures (like Ruku and Sujud) when dealing with physical injuries, joint pain, or mobility limitations.

When modifying prayer movements, worshippers face a unique challenge: they must balance physical safety (sports biomechanics) with canonical validity (Islamic jurisprudence or Fiqh). Standard AI chatbots are dangerous for thisβ€”they frequently hallucinate medical diagnoses or invent religious exceptions that do not exist.

SujudSense solves this by restricting the AI to a strict, verified knowledge base. It will not guess, and it will not act like a doctor. If a user asks a valid question, it provides safe, ergonomically sound postural adjustments backed by established Fiqh. If a user asks an off-topic or purely medical question, the system's safety firewalls instantly block the request.


πŸš€ High-Level Overview

Modifying prayer positions due to injury requires a highly delicate balance between joint ergonomics and canonical alignment. Standard LLMs frequently hallucinate unsafe medical adjustments or invalid jurisprudential exceptions.

SujudSense solves this by enforcing a strictly bounded knowledge environment. Operating under a closed-world assumption, the system pairs high-speed vector retrieval with programmatic guardrails to act as a reliable, safety-first assistant. It is engineered defensively to mitigate common production RAG failures: token bleeding, conversational context loss, and prompt injection attacks.

Key Engineering Highlights

  • Decoupled Service-Layer Pattern: Business logic (engine.py) is completely separated from the presentation layer (app.py), allowing seamless porting to alternative interfaces (e.g., FastAPI) without rewriting core RAG logic.
  • Conversational Memory Condensing: Implements a pre-processing LLM chain to rewrite ambiguous follow-up questions using session history, ensuring semantic search and firewalls never lose context.
  • Cost-Defensive Firewalls: Intercepts off-topic queries locally using structured output Intent Classification and L2 embedding distance checks. Unrelated inputs are rejected immediately, protecting cloud endpoints from infinite generation loops and off-topic billings.
  • Non-Blocking Asynchronous I/O: Every stage of the data pipeline utilizes native Python asyncio (ainvoke, asimilarity_search_with_score) to prevent database and LLM queries from blocking the server's single-threaded event loop under concurrent user loads.

πŸ› οΈ Technology Stack

  • Orchestration & UI: LangChain Ecosystem, Chainlit (Asynchronous WebSockets)
  • Vector Compute & Database: ChromaDB (Persistent Disk Storage Layout)
  • Local Embeddings: Hugging Face sentence-transformers/all-MiniLM-L6-v2 (CPU-Optimized)
  • Cloud Inference: Groq API Cloud Engine
    • Routing, Memory, & Synthesis: llama-3.3-70b-versatile
  • Telemetry & Analytics: Google Analytics (GA4 client injection via public/analytics.js)
  • Observability: Centralized Native Python Logging (logging module wrapper)

πŸ“ System Architecture

The workflow follows a deterministic, sequential security and retrieval pipeline. To prevent LLM hallucinations and medical misdirection, the system relies on strict intent classification and programmatic loops before returning any response to the user.

Flowchart

SujudSense Logical Flowchart

  1. Data Preparation: Reference documents are split into smaller chunks, embedded, and stored securely in a vector database.
  2. Initial Safety Check: When a user submits a query, the system first checks for off-topic or jailbreak phrases. If any are found, the request is refused.
  3. Query Rewrite: The system uses the ongoing chat history to rewrite the user's input into a single, standalone question.
  4. Relevance Check: It verifies if the standalone question matches the topics stored in the database. If it is off-topic, the request is refused.
  5. Intent Classification: The system evaluates the core intent of the question. To proceed, the question must contain both an Islamic prayer intent and a medical intent.
  6. Document Retrieval: If the question passes all filters, the system searches the database and retrieves the top 3 most relevant document chunks.
  7. Context Creation: The system combines the user's question, the retrieved documents, and the system prompt to build the context.
  8. Answer Generation: The combined context is sent to the LLM API to generate a response.
  9. Completeness Check: The system verifies if the generated answer is complete. If it is cut off, it makes an additional call to the LLM API to finish the response before returning the final answer to the user.

Infrastructure & Deployment

The system is containerized and deployed on the cloud to ensure reliable access and fast processing.

SujudSense Infrastructure Diagram

  1. Code Hosting: The AI Engineer pushes the application source code to the GitHub repository.
  2. Cloud Deployment: The application is deployed as a Docker container into Hugging Face Spaces.
  3. Model Download: The embedding model pulls the required files directly from Hugging Face Models.
  4. Database Storage: The embedding model processes the reference documents and stores them in ChromaDB.
  5. User Access: The user interacts with the application through the Chainlit UI (with usage tracked by Google Analytics).
  6. Data Retrieval: The LangChain Engine searches ChromaDB and retrieves the information needed to answer the user's question.
  7. Answer Generation: The LangChain Engine sends the retrieved information and the user's question to the Groq API to generate the response.
  8. UI Delivery: The LangChain Engine sends the final generated answer back to the Chainlit UI to be displayed to the user.
  9. Web Analytics: The web traffic data is captured and monitored using Google Analytics platform.

πŸ§ͺ Testing & Evaluation

SujudSense includes a comprehensive evaluation suite designed to verify safety, correctness, and conversational robustness before any deployment.

Test Structure

Test Category File Coverage
End-to-end integration tests/test_evaluation.py Full pipeline: firewalls β†’ memory condensing β†’ RAG generation β†’ output guards
Per-stage diagnostics tests/test_set.json 50+ cases across 4 pipeline stages: hardcoded block, capability triggers, vector firewall, intent classification
Safety-critical verification tests/test_evaluation.py Fail-closed behavior, jailbreak resistance, medical notice enforcement

Key Test Cases

  • Jailbreak resistance: Confirms prompts like "ignore previous instructions" are blocked before reaching the LLM
  • Fail-closed safety: Verifies that if the intent classifier fails (API error, malformed output), the system refuses rather than generating blindly
  • Conversational memory: Proves that ambiguous follow-ups ("What should I do for Sujud?") retain prior medical context ("I had knee surgery") through the condenser chain
  • Boundary enforcement: Confirms prayer-only queries ("What does Ruku mean?") and medical-only queries are correctly refused

Run the Suite

export GROQ_API_KEY="your-key"
python -m pytest tests/test_evaluation.py -v

πŸ›‘οΈ Safety and Response Rules

SujudSense applies explicit programmatic safety rules before and after LLM generation:

  • Intent-Based Filtering: Uses a structured-output LLM pass to classify the user's intent. If a query does not contain both a prayer-related context AND a medical/mobility context, it is safely rejected.
  • Off-Topic/Jailbreak Blocking: Queries containing blacklisted patterns (e.g., python script, hack, ignore previous instructions) are intercepted programmatically before reaching the reasoning chains.
  • Capability Queries: Questions like what can you do? or how can you help? bypass the LLM and return a hardcoded, safe scope description to save API compute costs.
  • Completeness Enforcement: Output payloads are systematically formatted with structural headings (Anatomical Cue and Fiqh Validation). Generation lengths are explicitly capped at 512 tokens.
  • Medical Safety Notice: When the response suggests physical prayer adjustments, the system explicitly appends a medical caution advising consultation with a healthcare professional for severe or worsening pain.

Safety rules are enforced programmatically in safety.py and verified by the test suite described in Testing & Evaluation.


πŸ—οΈ Architecture Note

The knowledge base (data/biomechanics.txt, data/fiqh.txt) uses synthetic reference documents for demonstration. The pipeline is source-agnostic by design β€” production deployment would swap in verified biomechanical literature and madhhab-specific Fiqh rulings without changing the RAG or safety architecture.

πŸ“‚ Repository Structure

β”œβ”€β”€ app.py                    # Presentation Layer: Manages WebSocket sessions and UI rendering
β”œβ”€β”€ engine.py                 # Service Layer: Handles conversational state, RAG orchestration, and firewalls
β”œβ”€β”€ config.py                 # Configuration Layer: Environment variable resolution and type-safe defaults
β”œβ”€β”€ safety.py                 # Security Layer: Hardcoded policies, intent schema, and blocklists
β”œβ”€β”€ logger.py                 # Telemetry Layer: Centralized, environment-toggled application logger
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ test_evaluation.py    # End-to-end integration and per-stage diagnostic tests
β”‚   └── test_set.json         # Structured test cases across all pipeline stages
β”œβ”€β”€ chainlit.md               # Application entry view and user welcome screen
β”œβ”€β”€ public/
β”‚   └── analytics.js          # Client-side Google Analytics (GA4) injection script
β”œβ”€β”€ .chainlit/
β”‚   └── config.toml           # Chainlit UI setup linking custom JS assets
β”œβ”€β”€ data/                     # Ground-Truth Knowledge Base (Immutable Source Text)
β”‚   β”œβ”€β”€ biomechanics.txt      # Structured orthopedic and athletic movement constraints
β”‚   └── fiqh.txt              # Canonical jurisprudential modification rulings
└── pyproject.toml            # Deterministic project metadata and dependencies

βš™οΈ Configuration & Environment Variables

The system architecture relies entirely on twelve-factor configuration practices. All system limits, paths, and behaviors are set using environment defaults:

Variable Default Value Purpose
LOG_LEVEL INFO Toggles telemetry output verbosity (DEBUG or INFO)
FIREWALL_THRESHOLD 1.4 Calibrated semantic distance cap for off-topic query rejection
FAST_LLM_MODEL llama-3.1-8b-instant Model used for low-latency routing and context condensing
FAST_LLM_MODEL_MAX_TOKENS 256 Token limit for fast LLM operations (classification, rewriting)
HEAVY_LLM_MODEL llama-3.3-70b-versatile Model used for final RAG synthesis and reasoning
HEAVY_LLM_TEMPERATURE 0.1 Low temperature for highly deterministic generation
HEAVY_LLM_MAX_TOKENS 512 Output response limit protecting against token drain
RETRIEVAL_K 3 Number of context documents passed to the compilation prompt
CHROMA_PERSIST_DIR ./chroma_db Disk directory mapping for the persistent storage layer

⚑ Setup & Execution

1. Environment Initialization

Ensure Python 3.12+ is active. Set your cloud inference token via your terminal profile or environment manager:

export GROQ_API_KEY="your-production-api-key-here"
export LOG_LEVEL="INFO"

2. Install Project Core Dependencies

pip install chainlit chromadb langchain langchain-classic langchain-community langchain-groq langchain-huggingface sentence-transformers

3. Launching the App

Run the local serving loop with the hot-reload watch flag active:

chainlit run app.py -w

4. Codebase Telemetry & Performance Auditing

To inspect the internal database inventory, execute diagnostic runs, or audit individual vector search distances on the fly, pass the runtime debug switch prior to boot:

export LOG_LEVEL=DEBUG
chainlit run app.py

πŸš€ Hugging Face Spaces Deployment

This project is fully containerized and can be deployed natively as a Hugging Face Space using the Docker SDK.

  1. Create a new Space on Hugging Face using the Docker SDK type (Choose the Blank template).
  2. Add the Space repository as a git remote in your local repo:
    git remote add hf [https://huggingface.co/spaces/](https://huggingface.co/spaces/)<your-username>/sujudsense
  3. Push your current branch to the HF remote:
    git push hf main
  4. Configure required secrets in the Space settings UI:
    • GROQ_API_KEY

About

Provides Islamic prayer postural adjustment advice using a source-based RAG architecture grounded in biomechanics and verified Islamic sources.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages