Metadata-Version: 2.4
Name: procurement-risk-nerve-center
Version: 1.0.0
Summary: A quantitative, multi-agent risk orchestration framework for procurement teams — powered by LangGraph and Google Gemini AI.
Author: Harshit Gogia
License-Expression: MIT
Project-URL: Homepage, https://github.com/hrshtgo/procurement-risk-nerve-center
Project-URL: Repository, https://github.com/hrshtgo/procurement-risk-nerve-center
Project-URL: Issues, https://github.com/hrshtgo/procurement-risk-nerve-center/issues
Keywords: procurement,risk,langgraph,gemini,multi-agent,supply-chain
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Office/Business
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: langgraph>=0.2.0
Requires-Dist: typing-extensions>=4.0
Requires-Dist: python-dotenv>=1.0
Requires-Dist: requests>=2.28
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Dynamic: license-file

# Procurement Risk Nerve Center (PRNC)

![Python](https://img.shields.io/badge/Python-3.10%2B-blue?logo=python&logoColor=white)
![LangGraph](https://img.shields.io/badge/LangGraph-Orchestration-orange)
![Gemini](https://img.shields.io/badge/Google%20Gemini-AI%20Powered-4285F4?logo=google&logoColor=white)
![License](https://img.shields.io/badge/License-MIT-green)

> A quantitative, multi-agent risk orchestration framework that fuses geopolitical intelligence, logistics route modeling, and probabilistic inventory analysis into a single executable pipeline — powered by **LangGraph** and **Google Gemini AI**.

![Architecture Diagram](images/architecture_diagram.png)

---

## Why PRNC?

Global procurement teams juggle hundreds of variables — shipping lane disruptions, trade-policy shifts, safety-stock erosion — often in disconnected spreadsheets.

PRNC replaces that fragmented workflow with **four specialized assessment agents** that pass structured, scored signals through a directed state-graph, culminating in an executive-ready risk brief with quantified severity and tiered mitigation actions.

---

## Two Modes of Operation

| Mode               | Description                                                                                                     | API Key?                                         |
|--------------------|-----------------------------------------------------------------------------------------------------------------|--------------------------------------------------|
| **🤖 Gemini AI**   | All 4 agents use Google Gemini to generate real-time, region-specific risk data for **any region in the world** | Yes ([free](https://aistudio.google.com/apikey)) |
| **📊 Static Data** | Uses pre-built simulated data for South China Sea — no API key needed, great for demos                          | No                                               |

---

## Architecture at a Glance

```text
┌─────────────────┐     ┌────────────────────┐     ┌─────────────────────┐     ┌──────────────────┐
│  Geopolitical   │────▶│  Logistics Route   │────▶│  Inventory Exposure │────▶│  Risk Synthesis  │
│  Assessment     │     │  Evaluation        │     │  Analysis           │     │  & Mitigation    │
└─────────────────┘     └────────────────────┘     └─────────────────────┘     └──────────────────┘
        │                        │                          │                          │
   RiskSignals              RouteAssessments          InventoryExposure         Composite Score
   (sev × conf)             (delay factors)           P(stockout) via CDF      Weighted Geo-Mean
```

**Conditional routing:** when logistics severity is negligible (`< 0.25`), the pipeline skips inventory analysis and jumps directly to synthesis — avoiding unnecessary computation.

---

## Scoring Model

| Component                   | Method                  | Detail                                                        |
|-----------------------------|-------------------------|---------------------------------------------------------------|
| **Signal scoring**          | `severity × confidence` | Each agent emits `RiskSignal` objects with bounded 0–1 values |
| **Composite risk**          | Weighted geometric mean | Dimension weights: Geo 0.35 · Logistics 0.30 · Inventory 0.35 |
| **Stockout probability**    | Normal-CDF demand model | `P(demand > stock) = 1 − Φ((stock − μL) / σ√L)`               |
| **Severity classification** | Threshold mapping       | Critical ≥ 0.80 · High ≥ 0.60 · Medium ≥ 0.35 · Low < 0.35    |

---

## Quick Start

### Prerequisites

- Python 3.10 or later
- `pip` package manager
- (Optional) A free Google Gemini API key — [get one here](https://aistudio.google.com/apikey)

### Install

```bash
git clone https://github.com/hrshtgo/procurement-risk-nerve-center.git
cd procurement-risk-nerve-center
python -m venv .venv

# Activate the virtual environment
# Windows:
.venv\Scripts\activate
# macOS/Linux:
source .venv/bin/activate

pip install -r requirements.txt
```

### Run

```bash
python main.py
```

You'll see an interactive menu:

```
╔══════════════════════════════════════════════════════════════╗
║       PROCUREMENT RISK NERVE CENTER — MAIN MENU              ║
╚══════════════════════════════════════════════════════════════╝

  ─── DATA SOURCE ──────────────────────────────────────────
  How should the agents generate risk data?

    [1] Use Google Gemini AI (free — requires API key)
    [2] Use static/simulated data (no API key needed)
```

- **Option 1 (Gemini AI):** Enter any region (e.g., "Panama Canal", "Taiwan Strait"), then your Gemini API key. All 4 agents will call Gemini to generate real-time risk analysis.
- **Option 2 (Static):** Runs immediately with pre-built data for South China Sea.

```bash
# Force all pipeline stages (disable conditional skip)
python main.py --no-skip
```

---

## Sample Output

```
╔══════════════════════════════════════════════════════════════╗
║        PROCUREMENT RISK NERVE CENTER — EXECUTIVE BRIEF       ║
╚══════════════════════════════════════════════════════════════╝

  Region Under Analysis : South China Sea
  Composite Risk Score  : 0.69 / 1.00
  Severity Classification: High

─── RISK SIGNALS ───────────────────────────────────────────────
  1. [GEOPOLITICAL] Escalating naval exercises have triggered a 34%
     surge in maritime insurance premiums.  (sev=0.88, conf=0.92)
  2. [LOGISTICS] Projected 35d vs nominal 18d (×1.94), rerouted
     via Lombok Strait  (sev=0.63, conf=0.90)
  3. [INVENTORY] Stockout probability 100.0% over 44d lead-time;
     coverage gap of 30 days for 3 SKU(s)  (sev=0.95, conf=1.00)

─── RECOMMENDED ACTIONS ────────────────────────────────────────
  ▸ IMMEDIATE: Pre-book partial air-freight capacity as insurance.
  ▸ SHORT-TERM: Increase safety-stock targets by 40% for impacted SKUs.
  ▸ STRATEGIC: Fast-track supplier qualification in alternate geographies.
  ▸ GOVERNANCE: Brief VP-level stakeholders; schedule weekly risk reviews.
```

---

## Configuration via Environment

| Variable                | Default | Description                                       |
|-------------------------|---------|---------------------------------------------------|
| `PRNC_WEIGHT_GEO`       | `0.35`  | Geopolitical dimension weight                     |
| `PRNC_WEIGHT_LOG`       | `0.30`  | Logistics dimension weight                        |
| `PRNC_WEIGHT_INV`       | `0.35`  | Inventory dimension weight                        |
| `PRNC_REORDER_BUFFER`   | `3`     | Extra buffer days added to reorder point          |
| `PRNC_DEMAND_STD`       | `12.0`  | Standard deviation of daily demand (units)        |
| `PRNC_CONDITIONAL_SKIP` | `1`     | Enable (`1`) or disable (`0`) conditional routing |

---

## Project Layout

```text
procurement-risk-nerve-center/
├── main.py                   # CLI entry point
├── requirements.txt          # Python dependencies
├── .gitignore
├── README.md
├── article.md                # In-depth technical write-up
├── images/                   # Architecture & flow diagrams
├── scripts/
│   └── generate_diagrams.py  # Mermaid diagram renderer
└── prnc/
    ├── __init__.py           # Package metadata
    ├── config.py             # Tunable weights, thresholds, env-loader
    ├── state.py              # PipelineState TypedDict + dataclasses
    ├── graph.py              # LangGraph orchestrator with conditional edges
    ├── utils.py              # Shared lookup utilities
    ├── menu.py               # Interactive CLI menu (Gemini AI / Static)
    ├── prompts.py            # Prompt templates for Gemini AI agents
    ├── scoring/
    │   ├── risk_matrix.py    # Composite risk & 5×5 severity matrix
    │   └── probability.py    # Normal-CDF stockout model
    ├── llm/
    │   ├── base.py           # Abstract LLM client interface
    │   ├── gemini_client.py  # Google Gemini API client with rate-limit handling
    │   └── parser.py         # JSON response parser for LLM outputs
    └── agents/
        ├── geopolitical.py   # Regional tension & trade-policy signals
        ├── logistics.py      # Route disruption & delay-factor projection
        ├── inventory.py      # SKU-level stockout probability modelling
        └── synthesis.py      # Aggregation, scoring, and mitigation tiers
```

---

## How It Works — Step by Step

1. **Geopolitical Assessment** scans for regional risk signals — either generated by Gemini AI for any real-world region, or from a pre-built static database. Produces `RiskSignal` objects with calibrated severity and confidence scores.

2. **Logistics Route Evaluation** maps those signals onto specific shipping corridors, computing delay factors and adjusting projected lead-times proportionally to upstream severity.

3. **Inventory Exposure Analysis** feeds the worst-case lead-time into a **normal-distribution demand model** to calculate `P(stockout)` — the probability that cumulative demand exceeds available stock before replenishment arrives.

4. **Risk Synthesis** aggregates all signals via a **weighted geometric mean**, classifies overall severity, and emits a tiered mitigation plan. In Gemini AI mode, the mitigation plan is generated by the LLM with specific references to the actual routes, SKUs, and risk signals.

---

## Real-World Use Cases

PRNC is designed to slot into real procurement and supply-chain workflows. Here are concrete scenarios where it delivers value:

### 🏭 Manufacturing — Component Sourcing Risk

A consumer electronics OEM sources MCUs and display panels from suppliers in the Taiwan Strait region. PRNC continuously monitors geopolitical tensions, flags rising maritime insurance premiums, and calculates the probability that safety stock will be exhausted before rerouted shipments arrive — giving the procurement team a 2–3 week head start on activating alternate suppliers.

### 🚢 Logistics — Shipping Lane Disruption Response

A global 3PL managing container freight through the Suez Canal or South China Sea uses PRNC to model delay factors across alternate corridors (Cape of Good Hope, Lombok Strait, Panama Canal). When disruption severity crosses the "High" threshold, the system automatically recommends partial air-freight pre-booking and safety-stock top-ups for the most exposed SKUs.

### 🏥 Healthcare — Critical Supply Continuity

A hospital network procuring surgical instruments and pharmaceuticals from single-source suppliers runs PRNC weekly to quantify stockout risk. The normal-CDF demand model highlights items where `P(stockout) > 50%`, triggering reorder-point adjustments and emergency supplier qualification before shortages materialize.

### 🛒 Retail — Seasonal Demand Planning

A retailer preparing for peak season uses PRNC to stress-test their supply chain against geopolitical scenarios (trade sanctions, port strikes, canal blockages). The composite risk score feeds into S&OP meetings, letting category managers prioritize which product lines need buffer inventory vs. which are low-risk.

### 🔋 Energy & EV — Raw Material Procurement

An EV battery manufacturer sourcing lithium and cobalt from politically volatile regions uses PRNC to score supplier-country risk, model shipping delays from African or South American ports, and calculate whether current warehouse stock covers the extended lead-times — all in a single pipeline run.

---

## Extending PRNC

PRNC is built to be modular. Here's how to adapt it to your specific needs:

### Add a New Risk Dimension

Create a new agent module (e.g., `prnc/agents/financial.py`) that follows the same pattern as existing agents:

```python
# prnc/agents/financial.py
def assess_financial_risk(state: PipelineState) -> Dict[str, Any]:
    """Evaluate supplier financial health and currency exposure."""
    # Your logic here — call an API, query a database, or use an LLM
    return {
        "risk_signals": [...],
        "audit_trail": ["[Financial] Assessed 3 supplier credit ratings"],
    }
```

Then register it in `prnc/graph.py`:

```python
graph.add_node("financial", assess_financial_risk)
graph.add_edge("inventory", "financial")
graph.add_edge("financial", "synthesize")
```

And extend the `RiskCategory` enum in `prnc/state.py`:

```python
class RiskCategory(str, Enum):
    GEOPOLITICAL = "geopolitical"
    LOGISTICS = "logistics"
    INVENTORY = "inventory"
    FINANCIAL = "financial"  # new
```

### Add a New LLM Provider

Implement the `LLMClient` interface under `prnc/llm/`:

```python
# prnc/llm/openai_client.py
from .base import LLMClient

class OpenAIClient(LLMClient):
    @property
    def provider_name(self) -> str:
        return "OpenAI"

    def generate(self, prompt: str, system_prompt: str = "") -> str:
        # Call the OpenAI API and return the response text
        ...
```

### Connect Real Data Sources

Replace the static lookup dictionaries in `prnc/agents/` with live API calls:

| Data Source | Integration Point | Example |
|---|---|---|
| **News/intelligence feeds** | `geopolitical.py` | GDELT, Event Registry, or RSS feeds for real-time conflict signals |
| **Shipping APIs** | `logistics.py` | MarineTraffic, Flexport, or Project44 for live vessel tracking and port congestion |
| **ERP / WMS systems** | `inventory.py` | SAP, Oracle, or NetSuite APIs for real inventory positions and demand history |
| **Financial data** | New `financial.py` agent | Dun & Bradstreet, CreditSafe for supplier credit risk scoring |

### Customize Scoring Weights

Tune the risk model without code changes using environment variables:

```bash
# Emphasize geopolitical risk for a volatile region
export PRNC_WEIGHT_GEO=0.50
export PRNC_WEIGHT_LOG=0.25
export PRNC_WEIGHT_INV=0.25

# Lower the "High" severity threshold for more conservative alerts
export PRNC_THRESHOLD_HIGH=0.50
```

### Install as a Package

PRNC includes a `pyproject.toml` for installation as a Python package:

```bash
pip install -e .   # editable/development install
prnc               # run from anywhere
python -m prnc     # alternative invocation
```

---

## 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

MIT — see [LICENSE](LICENSE) for details.
