Skip to content

hashim-i222478/StressEarlyWarningAgent

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Stress Early Warning Agent (SEWA)

A multi-agent stress monitoring and analytics system powered by LangGraph reasoning, ChromaDB memory, and temporal trend analysis.

πŸ“‹ Project Overview

SEWA is an AI-driven Early Warning System that analyzes daily health metrics to predict stress levels and provide personalized recommendations. The system tracks stress patterns over time, identifies peak stress periods, and offers intelligent insights based on temporal trends.

Key Features

βœ… Multi-Node LangGraph Reasoning - Non-sequential, conditional branching for intelligent stress analysis
βœ… Temporal Trend Analysis - Track stress increases/decreases over days/weeks
βœ… Peak Time Detection - Identify morning vs evening, weekday vs weekend stress patterns
βœ… Historical Comparisons - Compare current stress to baseline ("20% higher than last week")
βœ… Risk Scoring Breakdown - Visualize metric contribution with interactive pie charts
βœ… Long-Term Memory (LTM) - ChromaDB-backed persistent memory with 98% similarity caching
βœ… Professional UI - Responsive dashboard with animations and real-time visualizations
βœ… Reasoning Trace Output - Transparent agent decision-making with step-by-step explanations

Architecture

Frontend (HTML/CSS/Chart.js)
        ↓
Flask REST API
        ↓
LangGraph Multi-Node Agent
        β”œβ”€ validate_input
        β”œβ”€ search_ltm (ChromaDB)
        β”œβ”€ analyze_metrics_via_agent (reasoning)
        β”œβ”€ save_to_ltm
        └─ format_result
        ↓
Temporal Analyzer (Trend Detection)
        β”œβ”€ Daily averages
        β”œβ”€ Peak times (hourly/daily)
        β”œβ”€ Historical comparisons
        └─ Temporal recommendations

πŸš€ Quick Start

Prerequisites

  • Python 3.8+
  • Windows/Mac/Linux

Installation & Setup

Windows PowerShell:

# Clone the repository
git clone <repo-url>
cd SEWA

# Create virtual environment
python -m venv .venv
.\.venv\Scripts\Activate.ps1

# Install dependencies
pip install -r requirements.txt

# Run the application
python run.py

macOS/Linux:

# Clone and setup
git clone <repo-url>
cd SEWA
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt

# Start server
python run.py

Access the Application

Open your browser and navigate to:

http://localhost:5000

You'll see the interactive dashboard where you can:

  1. Enter your daily health metrics (work hours, sleep hours, heart rate)
  2. View your stress risk level and detailed breakdown
  3. Check temporal trends and patterns
  4. Get personalized recommendations

πŸ“Š Stress Scoring System

The agent calculates stress on a 0-100 scale using four metrics:

Metric Points Calculation
Work Hours 0-20 Based on daily workload (8h = 3pts, >14h = 20pts)
Sleep Hours 0-30 Sleep deprivation impact (<4h = 30pts, 7-9h = 0pts)
Heart Rate 0-20 Resting HR elevation (60-90 = 0pts, >110 = 20pts)
Synergy 0-25 Combined effects (overwork + poor sleep + elevated HR)
Total 0-100 Sum with max cap at 100

Risk Classification

  • 🟒 LOW (0-29): Healthy stress levels, maintain current habits
  • 🟑 MODERATE (30-59): Monitor closely, improve sleep/breaks
  • πŸ”΄ HIGH (60-100): Significant stress, prioritize rest and support

πŸ“‘ API Endpoints

Main Analysis Endpoint

POST /process_task
Content-Type: application/json

{
  "task": {
    "work": 9.5,
    "sleep": 6.5,
    "heart_rate": 85
  }
}

Response (Success):

{
  "message_id": "uuid-string",
  "sender": "StressWorkerAgent",
  "type": "completion_report",
  "status": "SUCCESS",
  "results": {
    "risk_level": "moderate",
    "stress_score": 43,
    "advice": "🟑 MODERATE STRESS: Monitor closely. Improve sleep and take breaks.",
    "source": "agent_reasoning",
    "breakdown": {
      "work": { "value": 12, "percent": 28 },
      "sleep": { "value": 15, "percent": 35 },
      "hr": { "value": 10, "percent": 23 },
      "synergy": { "value": 6, "percent": 14 }
    }
  },
  "cached": false,
  "reasoning_trace": [
    "βœ“ Validation: Input parameters valid",
    "β†’ LTM Search: Searching memory for similar patterns...",
    "βœ— No matches in LTM - executing fresh analysis",
    "=== AGENT REASONING START ===",
    "[Reasoning Step 1] Evaluate work hours...",
    "  Decision: 9.5h > 9h = ABOVE NORMAL (stress +12)",
    "...",
    "βœ“ Analysis complete"
  ]
}

Temporal Analysis Endpoints

Get Comprehensive Temporal Analysis

GET /temporal/analysis?days_back=7

Response:

{
  "trend": {
    "status": "ok",
    "trend": "increasing",
    "emoji": "πŸ“ˆ",
    "percent_change": 15,
    "message": "Your stress is increasing by 15%",
    "first_period_avg": 35,
    "second_period_avg": 40,
    "days": 7
  },
  "daily_average": {
    "status": "ok",
    "total_entries": 8,
    "daily_stats": {
      "2025-11-20": { "avg_stress": 32, "avg_work": 8.5, "avg_sleep": 7, "avg_hr": 72 },
      "2025-11-21": { "avg_stress": 38, "avg_work": 9.2, "avg_sleep": 6.5, "avg_hr": 78 }
    },
    "dates": ["2025-11-20", "2025-11-21"]
  },
  "peak_times": {
    "status": "ok",
    "hourly": {
      "peak_hour": 18,
      "peak_score": 65,
      "peak_category": "Evening",
      "lowest_hour": 8,
      "all_hours": { "8": 25, "9": 28, ..., "18": 65 }
    },
    "daily": {
      "peak_day": "Wednesday",
      "peak_score": 52,
      "all_days": { "Monday": 35, "Tuesday": 38, "Wednesday": 52 }
    },
    "weekday_vs_weekend": {
      "weekday_avg": 42,
      "weekend_avg": 28,
      "difference": 14,
      "higher": "weekday"
    }
  },
  "historical_comparison": {
    "status": "higher",
    "current_score": 48,
    "historical_avg": 38,
    "percent_difference": 26,
    "message": "Your current stress (48) is 26% above your average (38)",
    "total_entries_tracked": 23
  },
  "recommendations": [
    {
      "type": "timing",
      "icon": "⏰",
      "title": "Peak Stress in Evening",
      "advice": "Your stress peaks around 18:00. Consider scheduling breaks or relaxation activities during this time."
    },
    {
      "type": "schedule",
      "icon": "πŸ“…",
      "title": "Higher Stress on Weekdays",
      "advice": "Weekdays average 14 points higher stress. Plan more rest on these days."
    },
    {
      "type": "trend",
      "icon": "πŸ“ˆ",
      "title": "Stress is Rising",
      "advice": "Your stress is increasing by 15%. Consider stress management techniques now before it escalates."
    }
  ]
}

Get Stress Trend

GET /temporal/trend?days_back=7

Response:

{
  "status": "ok",
  "trend": "increasing",
  "emoji": "πŸ“ˆ",
  "percent_change": 15,
  "message": "Your stress is increasing by 15%",
  "first_period_avg": 35,
  "second_period_avg": 40,
  "days": 7
}

Get Peak Stress Times

GET /temporal/peak-times

Response:

{
  "status": "ok",
  "hourly": {
    "peak_hour": 18,
    "peak_score": 65,
    "peak_category": "Evening",
    "lowest_hour": 8,
    "lowest_score": 25,
    "all_hours": { "8": 25, "9": 28, "10": 30, ..., "23": 45 }
  },
  "daily": {
    "peak_day": "Wednesday",
    "peak_score": 52,
    "lowest_day": "Saturday",
    "lowest_score": 18,
    "all_days": {
      "Monday": 35,
      "Tuesday": 38,
      "Wednesday": 52,
      "Thursday": 42,
      "Friday": 48,
      "Saturday": 18,
      "Sunday": 22
    }
  },
  "weekday_vs_weekend": {
    "weekday_avg": 42,
    "weekend_avg": 28,
    "difference": 14,
    "higher": "weekday"
  }
}

Get Historical Comparison

GET /temporal/comparison

Response:

{
  "status": "significantly_higher",
  "current_score": 65,
  "historical_avg": 38,
  "percent_difference": 71,
  "message": "⚠️ Your current stress (65) is 71% higher than your average (38)",
  "total_entries_tracked": 42,
  "latest_timestamp": "2025-11-24T21:30:00.123456"
}

Get Daily Averages

GET /temporal/daily?days_back=7

Response:

{
  "status": "ok",
  "days": 7,
  "total_entries": 12,
  "daily_stats": {
    "2025-11-20": {
      "avg_stress": 32,
      "avg_work": 8.5,
      "avg_sleep": 7.2,
      "avg_hr": 72,
      "entries_count": 2,
      "peak_stress": 38,
      "risk_levels": ["low", "low"]
    },
    "2025-11-21": {
      "avg_stress": 45,
      "avg_work": 9.8,
      "avg_sleep": 6.1,
      "avg_hr": 82,
      "entries_count": 2,
      "peak_stress": 52,
      "risk_levels": ["moderate", "moderate"]
    }
  },
  "dates": ["2025-11-20", "2025-11-21", "2025-11-22"]
}

Get Temporal Recommendations

GET /temporal/recommendations

Response:

[
  {
    "type": "timing",
    "icon": "⏰",
    "title": "Peak Stress in Evening",
    "advice": "Your stress peaks around 18:00. Consider scheduling breaks or relaxation activities during this time."
  },
  {
    "type": "schedule",
    "icon": "πŸ“…",
    "title": "Higher Stress on Weekdays",
    "advice": "Weekdays average 14 points higher stress. Plan more rest on these days."
  },
  {
    "type": "trend",
    "icon": "πŸ“ˆ",
    "title": "Stress is Rising",
    "advice": "Your stress is increasing by 15%. Consider stress management techniques now before it escalates."
  },
  {
    "type": "comparison",
    "icon": "⚠️",
    "title": "Currently Above Average",
    "advice": "Your stress is 26% higher than usual. Take time to recover and practice self-care."
  }
]

Health & System Endpoints

GET /health

Returns agent status, version, memory stats, and features.

GET /registry

Returns full agent capability metadata for multi-agent orchestration.

GET /memory

Dumps all ChromaDB long-term memories.

POST /memory/clear

Clears all saved memories.

GET /memory/stats

Returns count of stored memories.

GET /responses/tail?n=10

Returns last N archived responses.

πŸ“ Project Structure

SEWA/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ __init__.py              # Flask app factory
β”‚   β”œβ”€β”€ routes.py                # All API endpoints
β”‚   β”œβ”€β”€ langgraph_integration.py # Multi-node reasoning engine
β”‚   β”œβ”€β”€ temporal_analysis.py     # Temporal trend analysis
β”‚   β”œβ”€β”€ ltm.py                   # ChromaDB memory backend
β”‚   └── archive.py               # Response archiving
β”œβ”€β”€ templates/
β”‚   └── index.html               # Interactive dashboard UI
β”œβ”€β”€ static/
β”‚   └── css/
β”‚       └── styles.css           # Professional styling & animations
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ chroma_db/               # ChromaDB persistent store
β”‚   β”œβ”€β”€ temporal_data.jsonl      # Temporal analysis data
β”‚   β”œβ”€β”€ responses.jsonl          # Archived API responses
β”‚   └── ltm.json                 # Legacy LTM format
β”œβ”€β”€ tests/
β”‚   └── integration_test.py      # Test suite
β”œβ”€β”€ run.py                       # Server launcher
β”œβ”€β”€ requirements.txt             # Dependencies
└── README.md                    # This file

πŸ”§ Configuration

Environment Variables (Optional)

# Set API host and port
setx FLASK_HOST "127.0.0.1"
setx FLASK_PORT "5000"

# Enable debug mode (development only)
setx FLASK_ENV "development"

Data Persistence

  • LTM Memory: data/chroma_db/ (ChromaDB)
  • Temporal Data: data/temporal_data.jsonl (JSONL format)
  • Response Archive: data/responses.jsonl (JSONL format)

πŸ§ͺ Testing

Run the integration test suite:

# Windows PowerShell
python -m unittest tests.integration_test -v

# macOS/Linux
python3 -m unittest tests.integration_test -v

πŸ“Š Example Workflow

1. Submit Health Data

$body = @{
  task = @{
    work = 9.5
    sleep = 6.5
    heart_rate = 85
  }
} | ConvertTo-Json

$response = Invoke-WebRequest -Uri "http://localhost:5000/process_task" `
  -Method POST -ContentType "application/json" -Body $body

$response.Content | ConvertFrom-Json

2. Check Temporal Trends

$trends = Invoke-WebRequest -Uri "http://localhost:5000/temporal/analysis?days_back=7"
$trends.Content | ConvertFrom-Json | ConvertTo-Json -Depth 10

3. View Recommendations

$recs = Invoke-WebRequest -Uri "http://localhost:5000/temporal/recommendations"
$recs.Content | ConvertFrom-Json

🎯 Stress Metric Details

Work Hours Scoring

  • 0-8 hours: 0-3 pts (healthy)
  • 8-10 hours: 3-12 pts (elevated)
  • 10-12 hours: 12-18 pts (high load)
  • 12-14 hours: 18-20 pts (excessive)
  • >14 hours: 20 pts (dangerous)

Sleep Hours Scoring

  • <4 hours: 30 pts (severe deprivation)
  • 4-5 hours: 20-25 pts (significant loss)
  • 5-6 hours: 15-20 pts (moderate loss)
  • 6-7 hours: 10-15 pts (slight loss)
  • 7-9 hours: 0 pts (optimal)
  • >9 hours: 5 pts (oversleep)

Heart Rate Scoring

  • <60 bpm: 0 pts (low/athletic)
  • 60-90 bpm: 0 pts (normal)
  • 90-100 bpm: 10 pts (slightly elevated)
  • 100-110 bpm: 15 pts (elevated)
  • >110 bpm: 20 pts (very elevated)

Synergy Bonuses

  • Overwork + Sleep Deprivation: +15 pts
  • Elevated HR + High Work: +10 pts
  • Sleep Loss + Elevated HR: +5 pts

πŸ” Security Considerations

  • No External LLM Dependency: All reasoning done locally with LangGraph
  • Metric-Based Matching: Uses Euclidean distance (not semantic similarity)
  • Data Privacy: All data stored locally in data/ directory
  • Rate Limiting: Implement in production deployment

πŸ“ˆ Performance Notes

  • Temporal Analysis: O(n) where n = number of historical entries
  • LTM Lookup: O(1) average with 98% similarity threshold
  • Reasoning Graph: ~50-100ms per analysis
  • UI Response: <500ms typical

🚒 Deployment

Production Setup

# Install production WSGI server
pip install gunicorn

# Run with Gunicorn (4 workers)
gunicorn --workers 4 --bind 0.0.0.0:5000 app:create_app()

Docker (Optional)

FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "run.py"]

πŸ“ License

This project is provided as-is for educational and research purposes.

🀝 Support

For issues, questions, or suggestions:

  1. Check existing documentation above
  2. Review /temporal/analysis endpoint response for diagnostic data
  3. Inspect /responses/tail for recent responses
  4. Check server logs for detailed error traces

About

A multi-agent stress monitoring and analytics system powered by LangGraph reasoning, ChromaDB memory, and temporal trend analysis.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors