Skip to content

MasterManoj9/Sentinal_AI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Version Agent Framework Python License

πŸ›‘οΈ Sentinel AI

Compliance Infrastructure for AI Agents

Powered by Prime β€” the compliance gate agent that intercepts every AI query,
detects regulated data in real-time, and routes only to approved models.

Quick Start β€’ Architecture β€’ How It Works β€’ API Reference β€’ Demo Scenarios

## πŸš€ Live Demo


πŸ” Problem Statement

Production AI systems regularly handle sensitive data β€” patient records, financial information, and personally identifiable information. Most AI pipelines send this data directly to third-party models with:

  • ❌ No compliance checks
  • ❌ No audit trail
  • ❌ No memory of past violations
  • ❌ No control over which models access your data

This creates regulatory risk under HIPAA, GDPR, PCI-DSS, and other frameworks.

πŸ’‘ Solution

Sentinel AI places an intelligent compliance gate between your application and AI models. Every query is scanned for regulated data, every decision is logged to an immutable audit trail, and only policy-approved models ever receive your data. Prime β€” the core agent β€” remembers past decisions across sessions using Hindsight, enabling adaptive enforcement that learns from your organization's compliance patterns over time.


πŸ—οΈ Architecture

High-Level System Architecture

flowchart TB
    subgraph Client["πŸ–₯️ Client Application"]
        A["AI Query<br/><i>e.g., Patient records,<br/>Medical questions</i>"]
    end

    subgraph SentinelAI["πŸ›‘οΈ Sentinel AI β€” Prime Compliance Gate"]
        direction TB
        B["πŸ”Ž PHI Detector<br/><i>Regex + LLM<br/>Two-Pass Scan</i>"]
        C{"🚦 Compliance Gate<br/><i>ALLOW / REDACT / BLOCK</i>"}
        D["🧠 Hindsight Memory<br/><i>Cross-Session Recall<br/>Pattern Recognition</i>"]
        E["πŸ”€ Cascade Router<br/><i>Cost-Optimized<br/>Model Selection</i>"]
        F["✏️ Redactor<br/><i>Type-Annotated<br/>PHI Masking</i>"]
        G["πŸ“‹ Audit Logger<br/><i>Append-Only JSONL<br/>Immutable Trail</i>"]
    end

    subgraph Models["βœ… Approved Models"]
        H["Groq<br/><code>openai-gpt-oss-120b</code>"]
        I["Ollama<br/><code>llama3.1</code>"]
    end

    subgraph Blocked["🚫 Blocked Models"]
        J["OpenAI GPT-4"]
        K["Anthropic Claude"]
    end

    A -->|"POST /query"| B
    B --> C
    D <-.->|"Recall & Store"| C
    C -->|"ALLOW"| E
    C -->|"REDACT"| F
    F --> E
    C -->|"BLOCK"| G
    E --> H
    E -.->|"Escalate"| I
    E --> G
    H --> G
    C -.-x J
    C -.-x K

    style SentinelAI fill:#0a0f1a,stroke:#00d4ff,stroke-width:2px,color:#e0e0e0
    style Client fill:#1a1a2e,stroke:#ff6b35,stroke-width:2px,color:#e0e0e0
    style Models fill:#0d2818,stroke:#00e676,stroke-width:2px,color:#e0e0e0
    style Blocked fill:#2d0a0a,stroke:#ff4444,stroke-width:2px,color:#e0e0e0
Loading

Prime Agent β€” Internal Pipeline

sequenceDiagram
    participant Client
    participant Prime as πŸ›‘οΈ Prime Agent
    participant Detector as πŸ”Ž PHI Detector
    participant Memory as 🧠 Hindsight
    participant Gate as 🚦 Gate
    participant Router as πŸ”€ Router
    participant Audit as πŸ“‹ Audit Log

    Client->>Prime: POST /query { query, client_id }
    
    Note over Prime: Step 1 β€” Log Query Received
    Prime->>Audit: log_event("QUERY_RECEIVED")
    
    Note over Prime: Step 2 β€” Detect PHI
    Prime->>Detector: detect_phi(query)
    Detector-->>Prime: { entities, confidence, method }
    
    Note over Prime: Step 3 β€” Recall Memory
    Prime->>Memory: recall_rules(client_id)
    Memory-->>Prime: past_decisions[]
    
    Note over Prime: Step 4 β€” Evaluate Policy
    Prime->>Gate: evaluate(detection, policy, recall)
    Gate-->>Prime: { decision: ALLOW|REDACT|BLOCK }
    
    Note over Prime: Step 5 β€” Route or Block
    alt BLOCK
        Prime->>Audit: log_event("DECISION_MADE", BLOCK)
    else REDACT
        Prime->>Router: route(redacted_query, approved_models)
        Router-->>Prime: { response, model_used, cost }
    else ALLOW
        Prime->>Router: route(query, approved_models)
        Router-->>Prime: { response, model_used, cost }
    end
    
    Note over Prime: Step 6 β€” Persist Memory
    Prime->>Memory: store_decision(client_id, decision)
    Prime->>Audit: log_event("DECISION_MADE")
    
    Prime-->>Client: { decision, response, audit_id, ... }
Loading

PHI Detection β€” Two-Pass Engine

flowchart LR
    subgraph Input
        Q["Raw Query Text"]
    end

    subgraph Pass1["Pass 1 β€” Regex Engine"]
        R1["SSN Pattern<br/><code>XXX-XX-XXXX</code>"]
        R2["Phone Pattern<br/><code>(XXX) XXX-XXXX</code>"]
        R3["Email Pattern<br/><code>user@domain.com</code>"]
        R4["DOB Pattern<br/><code>MM/DD/YYYY</code>"]
        R5["Medical Records<br/><code>MRN#XXXXX</code>"]
        R6["Contextual Keywords<br/><code>Patient, Dr., Diagnosis</code>"]
    end

    subgraph Pass2["Pass 2 β€” LLM Verification"]
        L["cascadeflow<br/>Contextual PHI<br/>Analysis"]
    end

    subgraph Output
        O["PHI Entity List<br/><i>type, value, position,<br/>confidence, method</i>"]
    end

    Q --> R1 & R2 & R3 & R4 & R5 & R6
    R1 & R2 & R3 & R4 & R5 & R6 --> L
    L --> O

    style Pass1 fill:#1a1a2e,stroke:#00d4ff,stroke-width:1px,color:#e0e0e0
    style Pass2 fill:#1a1a2e,stroke:#ff6b35,stroke-width:1px,color:#e0e0e0
Loading

Gate Decision Logic

flowchart TD
    A["Incoming Query"] --> B{"Requested model<br/>in blocked list?"}
    B -->|"Yes"| BLOCK1["🚫 BLOCK<br/><i>Non-compliant model</i>"]
    B -->|"No"| C{"PHI detected?"}
    C -->|"No"| ALLOW["βœ… ALLOW<br/><i>Route to approved model</i>"]
    C -->|"Yes"| D{"Contains high-sensitivity<br/>PHI? (SSN, MRN, etc.)"}
    D -->|"Yes"| BLOCK2["🚫 BLOCK<br/><i>High-sensitivity data</i>"]
    D -->|"No"| E{"Client has prior<br/>BLOCK history?"}
    E -->|"Yes + High Confidence"| BLOCK3["🚫 BLOCK<br/><i>Repeat offender escalation</i>"]
    E -->|"No"| REDACT["✏️ REDACT<br/><i>Mask PHI β†’ Route</i>"]

    style BLOCK1 fill:#4a0000,stroke:#ff4444,color:#ffffff
    style BLOCK2 fill:#4a0000,stroke:#ff4444,color:#ffffff
    style BLOCK3 fill:#4a0000,stroke:#ff4444,color:#ffffff
    style ALLOW fill:#003d00,stroke:#00e676,color:#ffffff
    style REDACT fill:#3d3000,stroke:#ffab00,color:#ffffff
Loading

πŸš€ Quick Start

Prerequisites

Requirement Version
Python β‰₯ 3.11
pip Latest
Git Latest

1. Clone the Repository

git clone https://github.com/YOUR_USERNAME/sentinel-ai.git
cd sentinel-ai

2. Install Dependencies

pip install -r requirements.txt

3. Configure Environment

cp .env.example .env

Edit .env with your API keys:

# Required β€” LLM Provider
GROQ_API_KEY=your_groq_api_key_here

# Optional β€” Cross-Session Memory
HINDSIGHT_API_KEY=your_hindsight_api_key_here
HINDSIGHT_BASE_URL=https://api.hindsight.vectorize.io

# Optional β€” Local Fallback Model
OLLAMA_BASE_URL=http://localhost:11434/v1

Note: Sentinel AI works without any API keys β€” it gracefully degrades to simulated responses for LLM routing and in-memory storage for Hindsight. This is perfect for development and testing.

4. Run the Server

uvicorn sentinel_ai.main:app --reload --port 8000

Or with Docker:

docker-compose up

5. Open the Dashboard

Visit http://localhost:8000 in your browser to access the interactive Prime Dashboard.

Resource URL
πŸ–₯️ Dashboard UI http://localhost:8000
❀️ Health Check http://localhost:8000/health
🎬 Demo Scenarios http://localhost:8000/demo

βš™οΈ How It Works

Key Integrations

Integration Purpose Fallback
Hindsight Persistent cross-session memory for compliance decisions In-memory store (no cross-session persistence)
cascadeflow Intelligent model routing with automatic escalation Simulated responses with routing decision explanation
Groq Ultra-fast inference for approved LLM models Offline mode with compliance-only operation

Hindsight Memory β€” How Prime Remembers

flowchart LR
    subgraph Cycle["Memory Lifecycle"]
        direction LR
        S["πŸ”’ Store<br/><i>After every decision,<br/>persist query hash,<br/>client ID, outcome</i>"]
        R["πŸ” Recall<br/><i>Before evaluation,<br/>fetch top-5 similar<br/>past decisions</i>"]
        RF["πŸ§ͺ Reflect<br/><i>Analyze trends,<br/>block rates, violation<br/>types over time</i>"]
    end

    S --> R --> RF --> S

    style Cycle fill:#0a0f1a,stroke:#00d4ff,stroke-width:1px,color:#e0e0e0
Loading
  1. Store β€” After every compliance decision, Prime stores the query hash, decision type, client ID, and outcome metadata in Hindsight's vector store.
  2. Recall β€” Before evaluating a new query, Prime recalls the top-5 most relevant past decisions for the same client, enabling escalation for repeat offenders and pattern recognition.
  3. Reflect β€” The reflect() method analyzes accumulated decisions to surface trends β€” block rates, common violation types, and compliance improvements over time.

cascadeflow Routing β€” Cost-Optimized Model Selection

  1. Policy Enforcement β€” Only models listed in approved_models are available. Blocked models are never called.
  2. Cost Optimization β€” Queries route to the cheapest approved model first (groq/openai-gpt-oss-120b).
  3. Automatic Escalation β€” If the primary model returns an empty or low-quality response, cascadeflow escalates to the fallback model (ollama/llama3.1).
  4. Redaction Pipeline β€” For REDACT decisions, PHI is masked with typed placeholders ([REDACTED-SSN], [REDACTED-DIAGNOSIS]) before any model sees the data.

🎯 Demo Scenarios

Sentinel AI ships with three built-in scenarios that exercise the Prime compliance gate across different risk levels.

Run via CLI

python -m sentinel_ai.scenarios

Run via API

curl http://localhost:8000/demo

Scenario 1: 🚫 Block PHI β€” SSN + Diagnosis + Name

Input:

Patient John Smith (SSN: 123-45-6789) was diagnosed with Type 2 Diabetes
on 03/15/2024. His treating physician Dr. Sarah Johnson prescribed
Metformin 500mg twice daily.
Field Value
PHI Detected βœ… Yes (10 entities)
Decision 🚫 BLOCK
Reason Query contains high-sensitivity PHI (SSN)
Model Used none

Scenario 2: ✏️ Redact Medical β€” Diagnosis + Doctor Name

Input:

Dr. Emily Chen noted that the patient presents with symptoms consistent
with Major Depressive Disorder. The patient has been experiencing fatigue,
loss of appetite, and insomnia for the past three months.
Field Value
PHI Detected βœ… Yes (3 entities)
Decision ✏️ REDACT
Reason PHI eligible for redaction; mask strategy applied
Model Used groq/openai-gpt-oss-120b

Scenario 3: βš”οΈ Attack β€” Non-Compliant Model Request

Input:

What are the common side effects of Lisinopril?

With requested_model: "openai/gpt-4" (blocked model)

Field Value
Decision 🚫 BLOCK
Reason Requested model 'openai/gpt-4' is not approved under HIPAA
Blocked Model openai/gpt-4

πŸ“‘ API Reference

Core Endpoints

Method Endpoint Description
POST /query Process a query through the Prime compliance gate
POST /chat Send a message to the Support FAQ agent
GET /demo Run all 3 demo scenarios
GET /health System health check
GET / Interactive Prime Dashboard UI

Audit Endpoints

Method Endpoint Description
GET /audit/recent?limit=20 Get recent audit log entries
GET /audit/client/{client_id} Get audit entries for a specific client
GET /audit/stats Get aggregate audit statistics

Example: Process a Query

curl -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "my-app-001",
    "query": "What are the side effects of Metformin?",
    "requested_model": "groq/openai-gpt-oss-120b"
  }'

Response:

{
  "decision": "ALLOW",
  "reason": "No protected health information detected in the query.",
  "response": "Metformin side effects include...",
  "model_used": "groq/openai-gpt-oss-120b",
  "cost": 0.001,
  "latency_ms": 245.67,
  "audit_id": "f5038df1-3a08-4f9b-9988-f95cf0bb0fde",
  "phi_detected": false,
  "entity_count": 0,
  "detection_method": "regex",
  "redacted": false,
  "escalated": false
}

πŸ“‹ Audit Trail

Every compliance decision is logged to an append-only JSONL file (audit.log). Entries are never overwritten or deleted.

Audit Entry Format

{
  "audit_id": "f5038df1-3a08-4f9b-9988-f95cf0bb0fde",
  "timestamp": "2025-01-15T10:30:00.150000+00:00",
  "event": "DECISION_MADE",
  "agent": "Prime",
  "project": "Sentinel AI",
  "client_id": "hospital-emr-001",
  "query_hash": "98ac1f09b938...",
  "decision": "BLOCK",
  "reason": "Query contains high-sensitivity PHI (ssn).",
  "model_used": "none",
  "cost": 0.0,
  "latency_ms": 7.84,
  "entity_count": 10,
  "redacted": false
}

Audit Locations

Output Details
File audit.log in project root (configurable via AUDIT_LOG_PATH)
stdout All entries printed to stdout for live monitoring
API Query via /audit/recent, /audit/client/{id}, /audit/stats
Sample See examples/sample_audit_log.jsonl

πŸ“ Project Structure

sentinel-ai/
β”œβ”€β”€ πŸ“„ README.md                     ← You are here
β”œβ”€β”€ πŸ“„ pyproject.toml                ← Package config, dependencies, metadata
β”œβ”€β”€ πŸ“„ requirements.txt             ← Pinned dependency versions
β”œβ”€β”€ πŸ“„ Dockerfile                   ← Multi-stage production container
β”œβ”€β”€ πŸ“„ docker-compose.yml           ← One-command deployment
β”œβ”€β”€ πŸ“„ .env.example                 ← Environment variable template
β”œβ”€β”€ πŸ“„ .gitignore                   ← Git exclusion rules
β”‚
β”œβ”€β”€ πŸ“‚ sentinel_ai/                  ← Core Python package
β”‚   β”œβ”€β”€ __init__.py                  ← Package metadata (version, agent name)
β”‚   β”œβ”€β”€ main.py                      ← FastAPI application & all REST endpoints
β”‚   β”œβ”€β”€ prime.py                     ← Prime agent β€” orchestrates full pipeline
β”‚   β”œβ”€β”€ detector.py                  ← PHI/PII detection (regex + LLM two-pass)
β”‚   β”œβ”€β”€ gate.py                      ← Compliance decision engine (ALLOW/REDACT/BLOCK)
β”‚   β”œβ”€β”€ router.py                    ← Model routing via cascadeflow
β”‚   β”œβ”€β”€ memory.py                    ← Hindsight memory integration + fallback store
β”‚   β”œβ”€β”€ audit.py                     ← Append-only JSONL audit logger
β”‚   β”œβ”€β”€ redact.py                    ← PHI redaction with typed placeholders
β”‚   β”œβ”€β”€ scenarios.py                 ← Built-in demo scenarios (3 test cases)
β”‚   └── config.py                    ← Configuration loader (env + policy file)
β”‚
β”œβ”€β”€ πŸ“‚ policies/                     ← Compliance policy definitions
β”‚   └── hipaa.json                   ← HIPAA policy (PHI types, approved models, thresholds)
β”‚
β”œβ”€β”€ πŸ“‚ static/                       ← Frontend assets
β”‚   └── index.html                   ← Interactive Prime Dashboard (single-page app)
β”‚
β”œβ”€β”€ πŸ“‚ tests/                        ← Test suite (pytest)
β”‚   β”œβ”€β”€ test_detector.py             ← PHI detection tests
β”‚   β”œβ”€β”€ test_gate.py                 ← Gate decision logic tests
β”‚   β”œβ”€β”€ test_router.py               ← Model routing tests
β”‚   └── test_e2e.py                  ← End-to-end integration tests
β”‚
└── πŸ“‚ examples/                     ← Sample data for reference
    β”œβ”€β”€ sample_audit_log.jsonl       ← Example audit log entries
    β”œβ”€β”€ sample_query_allowed.json    ← Example allowed query payload
    └── sample_query_blocked.json    ← Example blocked query payload

πŸ§ͺ Testing

Run the full test suite:

pytest -v

Run specific test modules:

# PHI detection tests
pytest tests/test_detector.py -v

# Gate decision logic tests
pytest tests/test_gate.py -v

# Model routing tests
pytest tests/test_router.py -v

# End-to-end integration tests
pytest tests/test_e2e.py -v

🐳 Docker Deployment

Build and Run

docker-compose up --build

Container Features

  • Multi-stage build for minimal image size
  • Non-root user (sentinel) for security
  • Health checks every 30 seconds
  • Volume mounts for audit.log persistence and policy files
  • Environment injection via .env file

Environment Variables

Variable Default Description
GROQ_API_KEY β€” Groq API key for LLM inference
HINDSIGHT_API_KEY β€” Hindsight API key for cross-session memory
HINDSIGHT_BASE_URL https://api.hindsight.vectorize.io Hindsight server URL
HINDSIGHT_BANK_ID client_id Memory bank identifier
HINDSIGHT_ENABLED true Enable/disable Hindsight integration
OLLAMA_BASE_URL http://localhost:11434/v1 Ollama server URL for fallback model
POLICY_FILE policies/hipaa.json Path to compliance policy file
AUDIT_LOG_PATH audit.log Path to the audit log file
LOG_LEVEL INFO Logging verbosity
HOST 0.0.0.0 Server bind address
PORT 8000 Server port

πŸ—ΊοΈ Roadmap

  • Multi-framework support β€” Add GDPR, SOC 2, and PCI-DSS policy templates
  • Webhook alerts β€” Notify security teams on BLOCK decisions
  • Client-specific policies β€” Per-client policy overrides
  • Model quality scoring β€” Track and compare model response quality
  • Batch processing β€” Support for bulk query compliance checking
  • Advanced PHI detection β€” Fine-tuned NER model for medical entities
  • Rate limiting β€” Per-client query rate limits with compliance tiers
  • RBAC β€” Role-based access control for API endpoints

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/my-feature
  3. Commit your changes: git commit -m "Add my feature"
  4. Push to the branch: git push origin feature/my-feature
  5. Open a Pull Request

πŸ“œ License

This project is licensed under the MIT License. See LICENSE for details.


Sentinel AI β€” Because compliance shouldn't be an afterthought.
Powered by Prime, the compliance gate agent.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors