| sdk | docker |
|---|---|
| title | SujudSense |
| emoji | π |
| colorFrom | gray |
| colorTo | blue |
| pinned | false |
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.
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.
- 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.
- 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
- Routing, Memory, & Synthesis:
- Telemetry & Analytics: Google Analytics (GA4 client injection via
public/analytics.js) - Observability: Centralized Native Python Logging (
loggingmodule wrapper)
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.
- Data Preparation: Reference documents are split into smaller chunks, embedded, and stored securely in a vector database.
- 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.
- Query Rewrite: The system uses the ongoing chat history to rewrite the user's input into a single, standalone question.
- Relevance Check: It verifies if the standalone question matches the topics stored in the database. If it is off-topic, the request is refused.
- 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.
- Document Retrieval: If the question passes all filters, the system searches the database and retrieves the top 3 most relevant document chunks.
- Context Creation: The system combines the user's question, the retrieved documents, and the system prompt to build the context.
- Answer Generation: The combined context is sent to the LLM API to generate a response.
- 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.
The system is containerized and deployed on the cloud to ensure reliable access and fast processing.
- Code Hosting: The AI Engineer pushes the application source code to the GitHub repository.
- Cloud Deployment: The application is deployed as a Docker container into Hugging Face Spaces.
- Model Download: The embedding model pulls the required files directly from Hugging Face Models.
- Database Storage: The embedding model processes the reference documents and stores them in ChromaDB.
- User Access: The user interacts with the application through the Chainlit UI (with usage tracked by Google Analytics).
- Data Retrieval: The LangChain Engine searches ChromaDB and retrieves the information needed to answer the user's question.
- Answer Generation: The LangChain Engine sends the retrieved information and the user's question to the Groq API to generate the response.
- UI Delivery: The LangChain Engine sends the final generated answer back to the Chainlit UI to be displayed to the user.
- Web Analytics: The web traffic data is captured and monitored using Google Analytics platform.
SujudSense includes a comprehensive evaluation suite designed to verify safety, correctness, and conversational robustness before any deployment.
| 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 |
- 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
export GROQ_API_KEY="your-key"
python -m pytest tests/test_evaluation.py -vSujudSense 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?orhow 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 CueandFiqh Validation). Generation lengths are explicitly capped at512tokens. - 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.
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.
βββ 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
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 |
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"pip install chainlit chromadb langchain langchain-classic langchain-community langchain-groq langchain-huggingface sentence-transformersRun the local serving loop with the hot-reload watch flag active:
chainlit run app.py -wTo 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.pyThis project is fully containerized and can be deployed natively as a Hugging Face Space using the Docker SDK.
- Create a new Space on Hugging Face using the Docker SDK type (Choose the Blank template).
- 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
- Push your current branch to the HF remote:
git push hf main
- Configure required secrets in the Space settings UI:
GROQ_API_KEY


