Agentic GraphRAG for Pharmaceutical Resilience
Status: π 5-Day Gen AI Intensive Course with Google Capstone Submission
Track: Enterprise / Business
Deployment: Video Demo
- The Business Problem
- The Solution
- Course Concepts Applied
- Architecture
- Agent Workflow
- Development Journey
- Installation & Usage
- Testing & Validation
- Project Structure
Pharma supply chains are fragile. Yet, the current landscape of tools leaves critical gaps in Time-to-Insight:
- Legacy SCRM (e.g., Resilinc) relies on manual mapping and qualitative scorecards, often detecting risks days after they occur.
- Logistics Tools (e.g., Everstream) track shipments well but lack the manufacturing context to calculate the financial impact of a raw material shortage.
- Planning Systems (e.g., SAP IBP or Kinaxis RapidResponse) are powerful systems of record but are "blind" to unstructured data (news, social media) until a human manually inputs the disruption.
While Generative AI offers a potential bridge, standard RAG chatbots fail to address this unmet need in the enterprise because they are:
- "Frozen in Time" - Training data cutoff means they miss real-time events
- "Deterministic" - They cannot verify if a fire reported on Twitter is real
- "Unaware" - They cannot pinpoint a factory's exact location relative to a hurricane
Resilio is a Cognitive Supply Chain Engine. It moves beyond "Chat with PDF" to perform Level 3 Agentic Reasoning by combining:
- Unstructured Intelligence (News extraction via Gemini 2.5 Flash)
- Geospatial Verification (NASA Satellite Data)
- Structured Reasoning (NetworkX Graph Traversal)
- Probabilistic Math (Monte Carlo Risk Simulation)
This project demonstrates the application of 5 Key Concepts from the AI Agents Intensive:
| Course Concept | Implementation in Resilio |
|---|---|
| 1. Multi-Agent Systems | Sequential Architecture: We orchestrated 5 specialized agents (Sentinel β Detective β Quantifier β Strategist β Auditor) using LangGraph. |
| 2. Tool Use (Function Calling) | Hybrid Tooling: We integrated custom Python tools (Graph Traversal, Monte Carlo Math) alongside external APIs (Tavily, NASA EONET) to ground the LLM in reality. |
| 3. Agent Evaluation | The Auditor Node: We implemented an "LLM-as-a-Judge" node that scores the faithfulness (0-5) of the strategy before presenting it to the user. |
| 4. State Management | TypedDict Schema: We used a structured AgentState to persist complex context (Entity IDs, Risk Distributions, Verification Logs) across the workflow steps. |
| 5. Reasoning Loops | Self-Correction: If the Auditor rejects a plan (Safety Check Fail), the workflow utilizes a Conditional Edge to loop back to the Sentinel for re-extraction. |
To solve the enterprise hallucination problem, we wrap every LLM generation in deterministic code layers:
The Sentinel Agent uses Google Gemini 2.5 Flash to extract events, but validates them immediately:
- Tavily Search: Confirms the event exists in reputable news sources
- NASA EONET: Checks satellite data for thermal anomalies (Fires) or storm tracks (Hurricanes) at the specific coordinates
The extracted entity string is forced to match a valid node ID in our NetworkX Knowledge Graph. If the entity is not in our supply chain, the alert is dropped.
Instead of asking the LLM to guess financial impact, the Quantifier Agent runs 1,000 Monte Carlo simulations in Python. It calculates the "Time-to-Survive" (Inventory Gap) to output a P5-P95 confidence interval for revenue loss.
Sentinel (Detect) β Detective (Trace) β Quantifier (Calculate) β Strategist (Decide) β Auditor (Verify)
-
π‘ Sentinel Agent - Detect & Verify
- Scans news input for supply chain disruptions
- Uses Gemini 2.5 Flash with Tavily (web search) and NASA EONET (geospatial verification)
- Maps events to entities in the knowledge graph using fuzzy matching and keyword mapping
- Tracks API usage (Gemini tokens and Tavily searches)
-
π΅οΈ Detective Agent - Trace Impact
- Traverses the knowledge graph using Breadth-First Search (BFS)
- Finds impacted products downstream
- Detects hidden dependencies (e.g., Saline β CAR-T)
-
π Quantifier Agent - Calculate Risk
- Runs Monte Carlo simulation (1000 iterations)
- Calculates financial risk ranges (P5, Expected, P95)
- Computes inventory gap days
-
π― Strategist Agent - Recommend Action
- Analyzes risk magnitude and event type
- Generates context-specific recommended actions
-
βοΈ Auditor Agent - Validate & Approve
- Validates entity grounding (hallucination check)
- Verifies math integrity
- Approves or blocks results for presentation
Our journey to building Resilio followed three phases of discovery, addressing critical enterprise adoption barriers:
Early prototypes using simple RAG would hallucinate suppliers or fail to distinguish between a "Fire near a factory" and "Fire at a factory."
Pivot: We moved from semantic search to Deterministic Entity Grounding. We stress-tested the system with ambiguous inputs (e.g., "Storm near Mock Town") and enforced a Python-based fuzzy match against our graph. This reduced false positives to near-zero, ensuring the "Control Tower" only lights up for verified network hits.
We found that LLMs are unreliable at arithmetic, often inventing financial losses. In an enterprise setting, a wrong number is worse than no number.
Pivot: We stripped the math capabilities out of the LLM and into a Python Tool. We implemented a Monte Carlo Simulation (1,000 replications) to model demand volatility and recovery uncertainty. This allows us to present a Confidence Interval (P5-P95) rather than a guess, aligning with how Risk Managers actually assess exposure.
Supply chain leaders told us they wouldn't trust a "Black Box" recommendation like "Buy more inventory."
Pivot: We focused on Explainable AI (XAI) via the Dashboard. By adding features like hover-over Lead Times on the graph edges and a visible "Auditor Validation Log," we exposed the agent's reasoning chain. Users can now trace the logic: Event Detected β Satellite Verified β Path Traced β Math Calculated β Action Recommended.
1. Clone the repository:
git clone https://github.com/codingnoodle/resilio.git
cd resilio2. Install dependencies:
pip install -r requirements.txt3. Set API Keys:
Create a .env file in the project root (or use env.template as a reference):
cp env.template .env
# Edit .env and add your API keysOr set environment variables (Linux/Mac):
export GOOGLE_API_KEY="your_key"
export TAVILY_API_KEY="your_key"4. (Optional) Configure Event Types & Locations:
Edit config.yaml to customize:
- Event types and disruption parameters
- Location-to-entity mappings
- Location-specific event descriptions
- Inventory overrides
5. Run the Control Tower:
streamlit run ui/dashboard.pyOpen http://localhost:8501 in your browser.
Deploy Resilio as a microservice on Google Cloud Run.
Build Container:
docker build -t resilio-app .Run Container:
docker run -p 8080:8080 \
-e GOOGLE_API_KEY="your_key" \
-e TAVILY_API_KEY="your_key" \
-e PORT=8080 \
resilio-appDeploy to Google Cloud Run:
gcloud run deploy resilio \
--source . \
--platform managed \
--region us-central1 \
--allow-unauthenticated \
--set-env-vars GOOGLE_API_KEY="your-key",TAVILY_API_KEY="your-key"Resilio uses automatic .env file loading (via python-dotenv). Create a .env file in the project root:
GOOGLE_API_KEY=your_google_api_key_here
TAVILY_API_KEY=your_tavily_api_key_here
USE_REAL_LLM=true # Optional: auto-detected if GOOGLE_API_KEY is setAll event types, locations, disruption parameters, and inventory overrides are now configurable via config.yaml:
- Event Types: Define keywords, disruption days (mean, sigma), and descriptions
- Location Mappings: Map location keywords to knowledge graph entities
- Event Descriptions: Location-specific event descriptions
- Inventory Overrides: Override inventory weeks for specific entities
See config.yaml for the full configuration schema.
The system automatically detects if API keys are missing and runs in deterministic mock mode (no API calls required). You can also explicitly set USE_REAL_LLM=false in your .env file.
Valid inputs in Zero-Dependency Mode:
- Locations: North Carolina, Rocky Mount, North Cove, New Jersey, Mock Town, Mumbai, Rotterdam
- Partners: PharmaCorp A, B, C, D, EU Logistics
- Disruptions: Fire, Tornado, Hurricane, Strike, Floods, Logistics
When GOOGLE_API_KEY is set, the system automatically enables real LLM mode. The system will use:
- Google Gemini 2.5 Flash for entity/event extraction
- Tavily Search for web verification (if
TAVILY_API_KEYis set) - NASA EONET for geospatial verification (always available, no key required)
The dashboard displays real-time API usage:
- Gemini API: Prompt tokens, completion tokens, and total tokens
- Tavily API: Number of search queries executed
This helps monitor API costs and usage patterns.
Resilio includes a comprehensive test suite (src/testing.py) that validates the core reliability mechanisms. These tests are critical for enterprise adoption because they ensure the system won't hallucinate entities or produce incorrect financial calculations.
In a production supply chain system, false positives are costly (unnecessary alerts) and false negatives are dangerous (missed disruptions). The test suite validates:
- Entity Grounding - Ensures location keywords (e.g., "Mumbai", "NJ") correctly map to the right supplier nodes in the knowledge graph
- Location-Priority Logic - Verifies that specific locations are prioritized over generic event types (e.g., "NJ fire" maps to New Jersey, not Mumbai)
- Probabilistic Math Integrity - Confirms that Monte Carlo simulations produce valid ranges (P95 > P50 > P5)
- Hallucination Prevention - Rejects unknown entities (e.g., "Explosion at Wonka Factory") to prevent false alerts
- Scenario Coverage - Validates complex scenarios like Internal BioTherapy Logistics disruptions
- Multi-Event Detection - Ensures the same location can correctly detect different event types (fire, hurricane, tornado)
python src/testing.pyExpected Output: All 6 tests should pass in ~2 seconds, confirming system integrity.
resilio/
βββ src/
β βββ resilio_core.py # The "Brain" - Graph, Agents, Monte Carlo engine
β βββ testing.py # Unit tests for risk math and grounding logic
βββ ui/
β βββ dashboard.py # The Streamlit "Control Tower" interface
β βββ workflow_diagram.svg # Multi-agent workflow diagram
β βββ workflow_diagram.png # Workflow diagram (PNG version)
βββ config.yaml # Centralized configuration (events, locations, disruption params)
βββ env.template # Template for .env file with required environment variables
βββ Dockerfile # Container configuration
βββ requirements.txt # Python dependencies
βββ README.md # This file
βββ RISK_CALCULATION_EXPLAINED.md # Detailed risk calculation methodology
src/resilio_core.py- Main application logic, agents, knowledge graph, LLM integrationui/dashboard.py- Streamlit UI with visualizations and API usage trackingsrc/testing.py- Unit tests for reliability and API key handlingconfig.yaml- Centralized configuration for event types, locations, and disruption parametersenv.template- Template showing required environment variables
| Type | Name | Role |
|---|---|---|
| Location | Mock Town, NJ (USA) | Internal Mfg Facility |
| Location | North Cove, NC (USA) | Partner B Facility |
| Location | Rocky Mount, NC (USA) | Partner C Facility |
| Location | Mumbai, India | Partner D Facility |
| Location | Rotterdam, EU | Logistics Hub |
| Entity | PharmaCorp A | Internal Mfg |
| Entity | PharmaCorp B (Tier 1) | IV Fluid Supplier |
| Entity | PharmaCorp C (Tier 1) | Sterile Injectable Supplier |
| Entity | PharmaCorp D (Tier 2) | Raw Material Supplier |
| Entity | EU Logistics | European Logistics Partner |
| Product | Product X BioTherapy | Finished BioTherapy (CAR-T proxy) |
| Product | Product Y Sterile | Sterile Injectable Component |
| Product | Product Z Commodity | Critical Commodity Component |
| Ingredient | BioTherapy Raw | Precursor Material |
- Supply Chain Data: Synthetic ontology modeled after the FDA Drug Safety Communication: Rocky Mount Tornado Damage (FDA Drug Safety Communication)
- Satellite Data: NASA Earth Observatory Natural Event Tracker (EONET) API
- Search: Tavily AI for agent-optimized web search
- LLM: Google Gemini 2.5 Flash via LangChain
MIT License
For questions or issues, please open an issue on GitHub.

