A quantitative, multi-agent risk orchestration framework for procurement teams — powered by LangGraph and Google Gemini AI.
Project description
Procurement Risk Nerve Center (PRNC)
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.
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) |
| 📊 Static Data | Uses pre-built simulated data for South China Sea — no API key needed, great for demos | No |
Architecture at a Glance
┌─────────────────┐ ┌────────────────────┐ ┌─────────────────────┐ ┌──────────────────┐
│ 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
pippackage manager- (Optional) A free Google Gemini API key — get one here
Install
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
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.
# 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
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
-
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
RiskSignalobjects with calibrated severity and confidence scores. -
Logistics Route Evaluation maps those signals onto specific shipping corridors, computing delay factors and adjusting projected lead-times proportionally to upstream severity.
-
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. -
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:
# 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:
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:
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/:
# 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:
# 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:
pip install -e . # editable/development install
prnc # run from anywhere
python -m prnc # alternative invocation
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/my-feature) - Commit your changes (
git commit -m 'Add my feature') - Push to the branch (
git push origin feature/my-feature) - Open a Pull Request
License
MIT — see LICENSE for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file procurement_risk_nerve_center-1.0.0.tar.gz.
File metadata
- Download URL: procurement_risk_nerve_center-1.0.0.tar.gz
- Upload date:
- Size: 32.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1827817f76ba85f0361a083f9c89b297424d661f76ddcb5ed67474415c684783
|
|
| MD5 |
e7b630decbd7aaee9f39390330ad66cb
|
|
| BLAKE2b-256 |
8b490567dcf106708fda78b010b0a59f289a813f8def6766f2f7507081b05e30
|
File details
Details for the file procurement_risk_nerve_center-1.0.0-py3-none-any.whl.
File metadata
- Download URL: procurement_risk_nerve_center-1.0.0-py3-none-any.whl
- Upload date:
- Size: 34.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.14.4
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
67cc5b3bd284e7b1aba5e307c4aec7df10ae95ee17f7d6c0540e02774f17a201
|
|
| MD5 |
58cd5af0ac00b9f074c7531dead7e51b
|
|
| BLAKE2b-256 |
63a99711cad9091b63d19228a3505d46a8485beea9f07ea754a0df523776375d
|