CoolFace
Modelpublic

mohdbelal010/SecureAI-Gaurd

sourceHugging Faceapache-2.0updated 6mo agoView on Hugging Face
0likes
Model Card

๐Ÿ›ก๏ธ SecureAI-Guard: Stateful POMDP for Autonomous Digital Defense

![OpenEnv](https://openenv.ai) ![HuggingFace Spaces](https://huggingface.co/spaces) ![License: MIT](LICENSE)

Overview

SecureAI-Guard is a production-grade reinforcement learning environment that simulates an autonomous personal security assistant protecting users across SMS, Email, and Web channels. Agents must make real-time decisions to block phishing, malware, social engineering, and spam while preserving user trust and avoiding alert fatigue.

This environment is fully compliant with the OpenEnv specification and is designed for both RL training and zero-shot LLM inference evaluation.


๐ŸŽฏ Key Features

FeatureDescription
Stateful POMDPHidden state (user trust, system fatigue) affects observations and termination
Adversarial DriftL3 adversary adapts its attack tactics mid-episode based on agent behaviour
Dense RewardsMulti-component reward shaped across every step โ€” no sparse end-of-episode signals
DeterministicFully reproducible with seed control
OpenEnv CompliantFull reset(), step(), state() API + valid openenv.yaml
HF IntegrationOptional DistilBERT risk scorer with keyword fallback
DPO FlywheelPreference pairs logged every step for LLM alignment
SOC DashboardReal-time Gradio monitoring interface

๐Ÿ—๏ธ Project Structure

SecureAI-Guard/
โ”œโ”€โ”€ app.py                   # FastAPI environment server (port 7860)
โ”œโ”€โ”€ ui.py                    # Gradio SOC dashboard (port 7861)
โ”œโ”€โ”€ inference.py             # โญ Required baseline inference script
โ”œโ”€โ”€ dqn_baseline.py          # Dueling DQN training script
โ”œโ”€โ”€ openenv.yaml             # OpenEnv manifest
โ”œโ”€โ”€ requirements.txt
โ”œโ”€โ”€ Dockerfile
โ”œโ”€โ”€ schema/
โ”‚   โ””โ”€โ”€ models.py            # Pydantic v2 typed models
โ”œโ”€โ”€ env/
โ”‚   โ”œโ”€โ”€ core.py              # Threat generation + reward logic
โ”‚   โ””โ”€โ”€ engine.py            # reset() / step() / state() engine
โ”œโ”€โ”€ tasks/
โ”‚   โ””โ”€โ”€ registry.py          # Three tasks (L1, L2, L3)
โ”œโ”€โ”€ graders/
โ”‚   โ””โ”€โ”€ security_grader.py   # Deterministic grader โ†’ score โˆˆ [0.0, 1.0]
โ””โ”€โ”€ utils/
    โ””โ”€โ”€ hf_integration.py    # HuggingFace risk scorer + fallback

๐Ÿš€ Quick Start

Prerequisites

bash
python -m venv venv
source venv/bin/activate   # Windows: venv\Scripts\activate
pip install -r requirements.txt

1. Start the Environment Server

bash
python app.py
# FastAPI running at http://localhost:7860

2. Run the Baseline Inference Script

bash
export API_BASE_URL=http://localhost:7860
export MODEL_NAME=gpt-3.5-turbo          # any OpenAI-compatible model
export OPENAI_API_KEY=sk-...             # optional; uses rule-based fallback if absent
export HF_TOKEN=hf_...                   # optional
python inference.py

3. Launch the SOC Dashboard (optional)

bash
python ui.py
# Gradio dashboard at http://localhost:7861

4. Train the DQN Agent (optional)

bash
python dqn_baseline.py --episodes 500 --task basic_security

๐Ÿ“ก API Reference

All endpoints accept and return JSON. The server runs on port 7860.

POST /reset

Reset the environment and return the first observation.

Request:

json
{
  "task_id": "basic_security",
  "seed": 42
}

Response:

json
{
  "observation": { ... },
  "state": { ... },
  "task_id": "basic_security"
}

POST /step

Execute one action and advance the environment.

Request:

json
{
  "action": {
    "decision": "block",
    "confidence": 0.92,
    "reasoning": "High-risk phishing link detected from unknown sender."
  }
}

Response:

json
{
  "observation": { ... },
  "reward": {
    "value": 0.48,
    "components": {
      "security": 1.0,
      "user_friction": 0.0,
      "delay": 0.0,
      "reasoning_quality": 0.6,
      "total": 0.56
    },
    "explanation": "security=1.00, friction=0.00, delay=0.00, reasoning=0.60"
  },
  "done": false,
  "info": { "threat_type": "phishing", "step": 3 },
  "state": { ... }
}

GET /state

Return the current environment state without advancing.

GET /tasks

List all available tasks.

GET /health

Health check โ€” returns {"status": "healthy"}.


๐ŸŽญ Observation Space

FieldTypeRangeDescription
event_idstringโ€”Unique UUID per event
channelenumsms, email, webMessage delivery channel
senderstringโ€”Sender identifier
contentstringโ€”Raw message text
timestampfloatunix tsArrival time
hf_risk_scorefloat[0.0, 1.0]HuggingFace classifier risk signal
user_trustfloat[0.0, 100.0]Running user trust level
system_fatiguefloat[0.0, 100.0]Alert fatigue accumulator
threat_historylistโ€”Last 5 events for context
metadataobjectโ€”Step, difficulty, event type

๐ŸŽฎ Action Space

FieldTypeDescription
decisionenumallow / block / warn / investigate
confidencefloat [0โ€“1]Agent's confidence in its decision
reasoningstringHuman-readable explanation (required, non-empty)

๐Ÿ† Task Descriptions

L1 โ€” Basic Security Screening (basic_security)

  • โ€”Max steps: 50 | Success threshold: 0.80
  • โ€”Phishing and spam only. No adversarial drift.
  • โ€”Ideal entry point. Clear-cut threats with high reward signal.

L2 โ€” Trust Management Challenge (trust_management)

  • โ€”Max steps: 75 | Success threshold: 0.75
  • โ€”All threat types active. False positives incur 1.5ร— trust penalty.
  • โ€”Agents must learn to tolerate ambiguity without over-blocking.

L3 โ€” Advanced Adversary Challenge (adversarial_drift)

  • โ€”Max steps: 100 | Success threshold: 0.70
  • โ€”Adaptive attacker: after step 20, switches tactics based on agent blocking rate.
  • โ€”Agents that over-block phishing will face a surge of social-engineering instead.

๐Ÿ’ฐ Reward Design

Formula

R_step = (0.5ยทsecurity + 0.3ยทuser_friction + 0.1ยทdelay + 0.1ยทreasoning) ร— (0.7 + 0.3ยทconfidence)

Components

ComponentRangeCalculation
security[โˆ’1.0, +1.0]+1.0 correct block; โˆ’1.0 missed threat; +0.5 safe allow; โˆ’0.8 false positive
user_friction[โˆ’0.5, 0.0]โˆ’0.2 per warning; โˆ’0.1 per investigate; โˆ’0.5 for false-positive block
delay[โˆ’0.1, 0.0]โˆ’0.1 for investigate actions
reasoning_quality[0.0, 1.0]Keyword match against threat-specific vocabulary

Why Dense?

Every step yields a non-zero reward signal, enabling stable gradient estimates for both RL and LLM policy optimisation. Partial credit is given via the confidence scaling factor โ€” an uncertain correct answer scores higher than a certain wrong one.


๐Ÿ“Š Grading

The SecurityGrader produces a deterministic score in [0.0, 1.0]:

score = 0.40 ร— security_efficiency
      + 0.30 ร— user_retention
      + 0.20 ร— precision
      + 0.10 ร— reasoning_quality
MetricFormula
security_efficiencyblockedthreats / totalthreats
user_retentionfinalusertrust / 100
precision1 โˆ’ falsepositiverate
reasoning_qualityavg(reasoning component across episode)

Letter Grades

ScoreGrade
โ‰ฅ 0.90A+
โ‰ฅ 0.80A
โ‰ฅ 0.70B
โ‰ฅ 0.60C
โ‰ฅ 0.50D
< 0.50F

๐Ÿ”š Episode Termination

An episode ends when any of the following conditions is met:

  1. 1.`user_trust โ‰ค 0` โ€” User has uninstalled the assistant due to too many false positives.
  2. 2.`system_fatigue โ‰ฅ 100` โ€” User ignores all alerts (warn overload).
  3. 3.`step_count โ‰ฅ max_steps` โ€” Episode length limit reached.

๐Ÿ“‹ Inference Script

inference.py is the required OpenEnv baseline script. It:

  • โ€”Reads API_BASE_URL, MODEL_NAME, and HF_TOKEN from environment variables
  • โ€”Uses the OpenAI client for LLM inference (with deterministic keyword fallback when no API key is set)
  • โ€”Runs all three tasks sequentially
  • โ€”Produces reproducible results with SEED_BASE control
  • โ€”Logs in the required format:
[START] task=basic_security episode=1 seed=43 model=gpt-3.5-turbo api=http://localhost:7860
[STEP]  step=1 decision=block confidence=0.92 reward=0.4830 trust=101.0 fatigue=0.0 threat=phishing
[STEP]  step=2 decision=allow confidence=0.88 reward=0.3150 trust=101.2 fatigue=0.0 threat=safe
...
[END]   task=basic_security episode=1 steps=50 total_reward=18.4200 score=0.7841 grade=B

๐Ÿณ Docker / HuggingFace Spaces Deployment

Build and run locally

bash
docker build -t secureai-guard .
docker run -p 7860:7860 secureai-guard

HuggingFace Spaces

  1. 1.Create a new Space (Docker SDK)
  2. 2.Push this repository
  3. 3.The Dockerfile exposes port 7860 โ€” HF Spaces will map it automatically
  4. 4.Set optional secrets: HF_TOKEN, OPENAI_API_KEY

Resource requirements

  • โ€”CPU: 2 vCPU (no GPU required; HF model loading is optional)
  • โ€”RAM: 4โ€“8 GB (8 GB recommended with transformers loaded)
  • โ€”Startup time: ~15 seconds

๐Ÿง  HuggingFace Integration

utils/hf_integration.py loads a text-classification pipeline for real-time risk scoring.

  • โ€”Default model: distilbert-base-uncased-finetuned-sst-2-english
  • โ€”Override: Set HF_RISK_MODEL environment variable
  • โ€”Fallback: If the model is unavailable, a deterministic keyword scorer activates automatically โ€” the environment works fully offline

๐Ÿ”„ DPO Data Flywheel

Every step logs a PreferencePair:

  • โ€”chosen_action: the action taken this step
  • โ€”rejected_actions: the previous step's action
  • โ€”reward_delta: improvement in reward

Retrieve via GET /preference_data. This data can be used directly for Direct Preference Optimisation (DPO) fine-tuning of LLM agents.


๐Ÿ“ˆ Baseline Results

Rule-based agent (keyword heuristics, no LLM):

TaskAvg ScoreAvg RewardGrade
basic_security0.7414.2B
trust_management0.6111.8C
adversarial_drift0.529.1D

DQN agent (500 episodes training):

TaskAvg ScoreAvg RewardGrade
basic_security0.8318.9A
trust_management0.7616.3B
adversarial_drift0.7114.7B

โš™๏ธ Environment Variables

VariableDefaultDescription
API_BASE_URLhttp://localhost:7860Environment server URL
MODEL_NAMEgpt-3.5-turboLLM model name
HF_TOKENโ€”HuggingFace token
OPENAI_API_KEYโ€”OpenAI API key
OPENAI_BASE_URLhttps://api.openai.com/v1OpenAI-compatible base URL
HF_RISK_MODELdistilbert-base-uncased-finetuned-sst-2-englishRisk scorer model
EPISODES_PER_TASK1Episodes per task in inference.py
SEED_BASE42Base seed for reproducibility

๐Ÿ“ License

MIT License โ€” see LICENSE for details.


๐Ÿค Contributing

  1. 1.Fork the repository
  2. 2.Create a feature branch (git checkout -b feature/my-feature)
  3. 3.Commit your changes
  4. 4.Submit a pull request

SecureAI-Guard: Where Reinforcement Learning Meets Cybersecurity Excellence ๐Ÿ›ก๏ธ