Skip to content

Chanu716/ResilientAI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

32 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

ResilientAI πŸš€

Autonomous Supply Intelligence for MSMEs β€” Global events β†’ Local decisions, instantly.

ResilientAI is a Decision Intelligence platform that converts global supply chain disruptions into real-time, actionable recommendations for small and micro businesses (MSMEs). If the Strait of Hormuz closes today, a kirana owner in Pune shouldn't have to wait 3 weeks to see prices spike β€” ResilientAI predicts the cost impact immediately and surfaces the single best action to take.

"If Bloomberg Terminal is for Wall Street, ResilientAI is for Main Street."


πŸ“‹ Table of Contents

  1. The Problem
  2. Core Features
  3. Technology Stack
  4. Repository Structure
  5. API Endpoints
  6. Quick Start Guide
  7. Environment Variables
  8. Running Tests
  9. Typical Demo Flow
  10. Deployment
  11. Roadmap
  12. License

🧩 The Problem

63 million MSMEs in India operate with zero access to real-time supply intelligence. When global disruptions occur β€” geopolitical conflicts, energy crises, commodity shocks β€” the impact cascades rapidly from global trade routes to local shelves, but small business owners find out weeks too late.

What MSMEs Have Today What ResilientAI Provides
WhatsApp rumours Verified, AI-qualified risk alerts
Reactive pricing Predictive, data-driven recommendations
Gut-instinct decisions Quantum-optimized trade-off analysis
No foresight tools Global β†’ local impact mapping in seconds

Example chain: Strait of Hormuz closure β†’ LPG price +20% β†’ Transport cost +12% β†’ Product margin -8% β†’ Recommended action delivered in < 5 minutes.


✨ Core Features

🌍 1. Risk Detection Agent

  • Autonomously scans global news feeds and geopolitical datasets via NewsAPI.
  • Performs NLP keyword extraction and named entity recognition using spaCy.
  • Classifies events as LOW, MEDIUM, or HIGH risk with a confidence score.
  • Tags affected commodity classes (LPG, fuel, FMCG, pharma, agri).
  • Powered by a LangChain ReAct agent with optional OpenAI / Gemini backends.

πŸ“‰ 2. Impact Prediction Engine

  • Maps global risk events directly to quantified local business cost impacts (in β‚Ή and %).
  • Models cascading factor effects through causal chains (e.g., LPG drop β†’ transport rise β†’ margin compression).
  • Computes city-level impact comparisons across logistics hubs.
  • Outputs predictions with a confidence interval for transparency.

🧠 3. Quantum-Inspired Optimization Engine

  • Evaluates competing multi-variable trade-off strategies using Qiskit QAOA.
  • Considers price delta, inventory delta, supplier switching costs, and demand elasticity.
  • Objective: maximise expected 7-day profit per decision.
  • Automatic NumPy classical fallback if Qiskit runtime exceeds 10 seconds.
  • Returns a ranked list of actions with human-readable rationale.

πŸ—ΊοΈ 4. 3D City Comparison Intelligence

  • Fully interactive MapLibre GL 3D globe visualization in the Next.js dashboard.
  • Compare city-specific resilience metrics, vulnerability scores, and logistics hub exposure in real time.

πŸŽ™οΈ 5. Voice-Activated Intelligence

  • Ask supply chain questions in plain language or Hindi (e.g., "Gas price badhega kya?").
  • SpeechRecognition for STT + gTTS for audio response synthesis.
  • Integrated with language detection and impact engine queries.

πŸ“² 6. WhatsApp Alert Integration

  • Proactive push alerts via Meta WhatsApp Business API.
  • Sends risk alerts and recommended actions directly to MSME owners' phones.
  • Webhook-based two-way messaging support.

πŸ“Š 7. Profit Simulation Sandbox

  • Simulate "what-if" scenarios: price increase, inventory stock-up, supplier switch.
  • Visualises projected revenue, profit, and margin for each strategy.

πŸ“ˆ 8. Forecast & Report Generation

  • Price forecaster for key commodity categories.
  • Exportable report generation per disruption event.

πŸ—οΈ Technology Stack

Layer Technology
Frontend Next.js 16 Β· React 19 Β· TypeScript Β· Tailwind CSS v4 Β· shadcn/ui
Geospatial MapLibre GL 5 (3D globe)
Charts Recharts
Backend API FastAPI Β· Python 3.11 Β· Uvicorn
AI Agent LangChain (ReAct) Β· OpenAI Β· Google Gemini Β· Nebius AI
NLP spaCy (en_core_web_sm) Β· langdetect
Optimization Qiskit 1.0 (QAOA) Β· Qiskit Aer Β· NumPy (classical fallback)
Voice SpeechRecognition Β· gTTS Β· PyAudio
Database Supabase (PostgreSQL)
Messaging Meta WhatsApp Business API
Data Sources NewsAPI Β· Custom commodity CSV baselines
Deployment Vercel

πŸ“ Repository Structure

ResilientAI/
β”œβ”€β”€ .env.example            # Environment variable template
β”œβ”€β”€ vercel.json             # Vercel deployment configuration
β”œβ”€β”€ requirements.txt        # Python dependencies
β”œβ”€β”€ pytest.ini              # Pytest configuration
β”‚
β”œβ”€β”€ agents/                 # AI Risk Detection & News Intelligence
β”‚   β”œβ”€β”€ news_fetcher.py     # NewsAPI integration & headline polling
β”‚   β”œβ”€β”€ nlp_classifier.py   # spaCy NLP keyword extraction & classification
β”‚   └── risk_agent.py       # LangChain ReAct agent for risk scoring
β”‚
β”œβ”€β”€ api/                    # FastAPI Backend
β”‚   β”œβ”€β”€ main.py             # App entry point & middleware configuration
β”‚   β”œβ”€β”€ models.py           # Pydantic request/response data models
β”‚   └── routes/             # API route handlers
β”‚       β”œβ”€β”€ alerts.py       # GET  /api/v1/alerts
β”‚       β”œβ”€β”€ impact.py       # POST /api/v1/impact
β”‚       β”œβ”€β”€ recommend.py    # POST /api/v1/recommend
β”‚       β”œβ”€β”€ simulate.py     # POST /api/v1/simulate
β”‚       β”œβ”€β”€ voice.py        # POST /api/v1/voice
β”‚       β”œβ”€β”€ decisions.py    # GET/POST /api/v1/decisions
β”‚       β”œβ”€β”€ cities.py       # GET  /api/v1/cities
β”‚       β”œβ”€β”€ forecast.py     # GET  /api/v1/forecast
β”‚       β”œβ”€β”€ whatsapp.py     # POST /api/v1/whatsapp (webhook)
β”‚       └── report.py       # GET  /api/v1/report
β”‚
β”œβ”€β”€ engines/                # Core Intelligence Engines
β”‚   β”œβ”€β”€ impact_engine.py    # Global risk β†’ local cost impact calculator
β”‚   β”œβ”€β”€ optimizer.py        # Qiskit QAOA optimizer + NumPy fallback
β”‚   β”œβ”€β”€ risk_scorer.py      # Risk level scoring logic
β”‚   β”œβ”€β”€ city_impact.py      # City-level comparative impact engine
β”‚   β”œβ”€β”€ price_forecaster.py # Commodity price forecasting
β”‚   β”œβ”€β”€ supplier_engine.py  # Alternative supplier recommendations
β”‚   β”œβ”€β”€ report_generator.py # PDF/JSON report generation
β”‚   β”œβ”€β”€ user_store.py       # User business profile management
β”‚   └── database.py         # Supabase database client
β”‚
β”œβ”€β”€ data/                   # Seed Data & Baselines
β”‚   β”œβ”€β”€ commodity_baselines.csv  # Baseline prices for key commodities
β”‚   β”œβ”€β”€ impact_rules.json        # Causal chain rules for impact calculation
β”‚   β”œβ”€β”€ seed_events.json         # Pre-seeded disruption events for demo mode
β”‚   └── suppliers.json           # Supplier directory dataset
β”‚
β”œβ”€β”€ frontend/               # Next.js Web Dashboard
β”‚   β”œβ”€β”€ app/                # Next.js App Router pages
β”‚   β”œβ”€β”€ components/         # Reusable React components
β”‚   β”œβ”€β”€ lib/                # Shared utilities and API client
β”‚   β”œβ”€β”€ middleware.ts        # Next.js middleware (auth, routing)
β”‚   └── public/             # Static assets
β”‚
β”œβ”€β”€ tests/                  # Pytest Test Suite
β”‚   β”œβ”€β”€ test_impact_engine.py    # Impact engine unit tests
β”‚   β”œβ”€β”€ test_optimizer.py        # Qiskit optimizer unit tests
β”‚   β”œβ”€β”€ test_risk_agent.py       # Risk detection agent tests
β”‚   └── test_meta_whatsapp.py    # WhatsApp webhook integration tests
β”‚
└── voice/                  # Voice Processing Module
    └── whatsapp.py         # STT / TTS pipeline & voice query handler

πŸ”Œ API Endpoints

Base URL: http://localhost:8000/api/v1
Interactive docs: http://localhost:8000/docs

Method Endpoint Description
GET /alerts Returns current active risk alerts
POST /impact Calculate business impact from a risk event
POST /recommend Get quantum-optimized decision recommendation
POST /simulate Run profit simulation for a proposed action
POST /voice Submit a voice/text query and get audio + text response
GET/POST /decisions Log and retrieve accepted decisions
GET /cities City-level resilience and impact comparison data
GET /forecast Commodity price forecast for selected categories
POST /whatsapp Meta WhatsApp webhook for push alerts
GET /report Generate disruption impact report
Example: POST /impact

Request:

{ "event_id": "evt_001", "business_type": "kirana" }

Response:

{
  "LPG_price_change": 0.20,
  "transport_cost_change": 0.12,
  "product_margin_change": -0.08,
  "demand_change": -0.05,
  "confidence_interval": 0.03
}
Example: POST /recommend

Request:

{ "impact_id": "imp_001" }

Response:

{
  "action": "Stock 10 extra units + raise price by β‚Ή2",
  "reason": "Minimizes expected loss, maximizes 7-day profit",
  "profit_impact_inr": 1200,
  "generated_by": "quantum",
  "alternatives": [
    { "action": "Price increase only", "profit_impact": "+β‚Ή600" },
    { "action": "Switch supplier", "profit_impact": "+β‚Ή400", "risk": "HIGH" }
  ]
}
Example: POST /voice

Request:

{ "query": "Gas price badhega kya?", "lang": "hi" }

Response:

{
  "text": "Haan, LPG price 20% badhega. 10 unit extra stock karo.",
  "audio_base64": "<base64_mp3>"
}

πŸš€ Quick Start Guide

Prerequisites


1. Clone the Repository

git clone https://github.com/Charmiseera/ResilientAI.git
cd ResilientAI

2. Set Up the Python Backend

# Create and activate virtual environment
python -m venv .venv

# macOS / Linux
source .venv/bin/activate
# Windows
.venv\Scripts\activate

# Install Python dependencies
pip install -r requirements.txt

# Download the spaCy NLP model
python -m spacy download en_core_web_sm

3. Configure Environment Variables

cp .env.example .env
# Edit .env and fill in your API keys (see section below)

Demo Mode: Set USE_SEED_DATA=true and DEMO_MODE=true in .env to run fully on pre-seeded data without any external API keys.

4. Start the Backend API

uvicorn api.main:app --reload --port 8000
  • API base: http://localhost:8000
  • Interactive docs (Swagger UI): http://localhost:8000/docs

5. Start the Frontend Dashboard

cd frontend
npm install
npm run dev
  • Dashboard: http://localhost:3000

πŸ”‘ Environment Variables

Copy .env.example to .env and populate the following:

Variable Required Description
USE_SEED_DATA No true = use mock seeded data (safe for demo)
DEMO_MODE No true = run in full demo mode
DEMO_SCENARIO No Default scenario (e.g. hormuz_disruption)
GEMINI_API_KEY For AI Google AI Studio
NEBIUS_API_KEY For AI Nebius AI
NEWS_API_KEY For live news newsapi.org (free tier)
SUPABASE_URL For DB Your Supabase project URL
SUPABASE_KEY For DB Supabase anon or service role key
NEXT_PUBLIC_SUPABASE_URL Frontend Same as SUPABASE_URL
NEXT_PUBLIC_SUPABASE_ANON_KEY Frontend Supabase anon key
IBM_QUANTUM_TOKEN For Qiskit quantum.ibm.com (free)
QUANTUM_TIMEOUT_SECONDS No Fallback timeout (default: 10)
WHATSAPP_TOKEN For WhatsApp Meta Business API token
WHATSAPP_PHONE_NUMBER_ID For WhatsApp Meta phone number ID
WHATSAPP_BUSINESS_ACCOUNT_ID For WhatsApp Meta business account ID
NEXT_PUBLIC_GOOGLE_MAPS_KEY Frontend map Google Maps API key
NEXT_PUBLIC_API_URL Frontend Backend URL (default: http://localhost:8000/api/v1)

πŸ§ͺ Running Tests

# Run the full test suite
pytest

# Run a specific test file
pytest tests/test_impact_engine.py -v
pytest tests/test_optimizer.py -v
pytest tests/test_risk_agent.py -v
pytest tests/test_meta_whatsapp.py -v

🎯 Typical Demo Flow

  1. Open http://localhost:3000 in your browser.
  2. In the Intelligence Panel, select a simulated global event (e.g., Hormuz Disruption).
  3. The Risk Detection Agent scores the event: Risk: HIGH | Confidence: 92%.
  4. The Impact Engine calculates: LPG +20% Β· Transport +12% Β· Margin -8%.
  5. The Quantum Optimizer recommends: "Stock 10 extra units + raise price by β‚Ή2 β†’ Est. +β‚Ή1,200/week".
  6. Switch to the City Comparisons tab for the interactive 3D MapLibre globe showing affected regions.
  7. Use the Voice panel to ask: "Gas price badhega kya?" and hear an audio response.
  8. Use the Simulation panel to model alternative pricing or inventory strategies.

☁️ Deployment

ResilientAI is a full-stack application with a Python backend and a Next.js frontend. For the best performance and reliability:

  • Backend (API): Deployed on Render (Web Service).
  • Frontend (Dashboard): Deployed on Vercel (Next.js).

1. Deploy Backend (Render)

  1. Connect Repository: Create a new Web Service on Render and connect it to your GitHub repository.
  2. Blueprint (Recommended): Render will automatically detect the render.yaml file and configure the service.
  3. Manual Configuration (If not using Blueprint):
    • Runtime: Python
    • Build Command: pip install -r requirements.txt && python -m spacy download en_core_web_sm
    • Start Command: gunicorn -k uvicorn.workers.UvicornWorker app:app
  4. Environment Variables: Add all required keys from .env.example in the Render dashboard.
  5. Health Check: Your API will be live at https://your-backend.onrender.com. Verify by visiting https://your-backend.onrender.com/health.

2. Deploy Frontend (Vercel)

  1. Import Project: In Vercel, create a new project and select the frontend directory as the Root Directory.
  2. Environment Variables:
    • Set NEXT_PUBLIC_API_URL to your Render backend URL (e.g., https://your-backend.onrender.com/api/v1).
    • Add Supabase and other frontend-specific keys.
  3. Deploy: Vercel will build and deploy the Next.js app natively.

Tip: Ensure NEXT_PUBLIC_API_URL ends with /api/v1 to match the backend routes.


πŸ—ΊοΈ Roadmap

MVP (Now)          v1.5 (Month 3)       v2.0 (Month 6)       v3.0 (Year 2)
────────────────   ─────────────────    ─────────────────    ─────────────────
Kirana stores      + Pharma stores      + Agri / logistics   Global expansion
Next.js dashboard  + WhatsApp alerts    + Native mobile app  Multi-country data
Qiskit simulator   + Real-time pricing  + Real quantum HW    Enterprise SaaS
3 core decisions   + Supplier directory + Predictive trends  Platform API

Sector Expansion Path:

  • Now: Kirana / general retail
  • Month 3: Pharmaceutical distributors
  • Month 6: Restaurants, food & beverage
  • Year 2: Agri-logistics, manufacturing MSMEs

πŸ›‘οΈ License

Built for real-world impact. See ResilientAI_PRD.md for the full Product Requirements Document.

About

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors