-
Notifications
You must be signed in to change notification settings - Fork 102
feat: Python Self-Healing Supply Chain Demo (Interactive + Gemini 3) #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 15 commits
d0494de
14b738f
d90aad3
09bdc2a
79f01e0
4c31805
945b378
622ede1
6886486
ade31f5
4082301
3bfbfb6
9eded53
a126dca
2d29498
42d15b1
61b58ec
a0880e0
5ca6b5f
ffa0de5
235d9fb
940e9e5
f356615
45ec3bf
e62748e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| # feat: Python Self-Healing Supply Chain Demo (Interactive + Gemini 3) | ||
|
|
||
| ## 📝 Summary | ||
| This PR adds a comprehensive Python sample demonstrating an **Autonomous Supply Chain Agent** capable of "Self-Healing" when a primary supplier fails. It leverages the **Google Agent Development Kit (ADK)** and the latest **Gemini 3 Flash** model to orchestrate a recovery workflow using **UCP** (Commerce) and **AP2** (Governance) protocols. | ||
|
|
||
| ## ✨ Key Features | ||
| * **Interactive Simulation**: Includes a CLI-based `InventoryManager` where users simulate sales. The Autonomous Restock triggers automatically when inventory drops below a critical threshold. | ||
| * **Dynamic Discovery (UCP)**: The agent dynamically resolves backup suppliers via `/.well-known/ucp` instead of hardcoded endpoints, demonstrating true network autonomy. | ||
| * **Negotiation Capability (UCP)**: Handles multi-step checkout flows, including providing Shipping Address and Discount Codes (`PARTNER_20`) to finalize Tax and Totals. | ||
| * **Governance & Trust (AP2)**: | ||
| * Implements **Detached JWS** signatures for verifiable user intent. | ||
| * Enforces a **Variance-Based Spending Policy** (15% threshold). | ||
| * **Human-in-the-Loop**: High-variance transactions pause for manual admin sign-off. | ||
| * **Modern Stack**: Built with `google-genai` (Gemini 3 Flash Preview) and standard `pydantic` models for UCP/AP2 schemas. | ||
|
|
||
| ## 🏗️ Architecture | ||
| * **`buyer_agent.py`**: The ADK Agent utilizing a "Brain + Tools" pattern. | ||
| * **`supplier_server.py`**: A lightweight Mock UCP Server (FastAPI) that handles Discovery, Checkout Negotiation, and Mandate Verification. | ||
| * **`mock_db.py`**: Simulates a Product Catalog and Corporate Spending Policy. | ||
|
|
||
| ## 🧪 How to Test | ||
| 1. **Start the Supplier Server**: | ||
| ```bash | ||
| python supplier_server.py | ||
| ``` | ||
| 2. **Run the Buyer Agent**: | ||
| ```bash | ||
| python buyer_agent.py | ||
| ``` | ||
| 3. **Interactive Loop**: | ||
| * Enter sales (e.g., `90` units) to drop inventory below 20. | ||
| * Observe the Agent detect the Primary Supplier failure (503). | ||
| * Watch the Agent discover the Backup Supplier and request approval for the price variance. | ||
| * Approve the purchase to see the Inventory restock. | ||
|
|
||
| ## ✅ Checklist | ||
| - [x] Code adheres to UCP & AP2 Architectural Best Practices. | ||
| - [x] Includes detailed `README.md` with production architecture diagrams. | ||
| - [x] Secrets managed via `.env.local` (excluded from git). | ||
| - [x] Dependencies listed in `requirements.txt`. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| # Python | ||
| __pycache__/ | ||
| *.py[cod] | ||
| *$py.class | ||
|
|
||
| # Virtual Environment | ||
| .venv/ | ||
| venv/ | ||
| env/ | ||
|
|
||
| # Environment Variables (Secrets) | ||
| .env | ||
| .env.local | ||
|
|
||
| # IDE | ||
| .vscode/ | ||
| .idea/ | ||
|
|
||
| # OS | ||
| .DS_Store | ||
|
|
||
| demo_audit.log | ||
| ucp_samples_fork/ |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| # Self-Healing Supply Chain Demo (UCP & AP2) | ||
|
|
||
| This project demonstrates an **Autonomous Supply Chain Agent** capable of "Self-Healing" when a primary supplier fails. It leverages two key next-generation protocols: | ||
|
|
||
| * **Google ADK (Agent Development Kit)**: For orchestrating the autonomous agent, managing state, and integrating with Gemini 3 Flash. | ||
| * **UCP (Universal Commerce Protocol)**: For dynamic supplier discovery, checking inventory, and negotiating standardized checkout sessions. | ||
| * **AP2 (Agent Payments Protocol)**: For secure, policy-driven transaction governance and "Agentic Payments". | ||
|
|
||
| ## 🚀 Scenario | ||
|
|
||
| 1. **Start State**: The demo begins in an **Interactive Mode** with 100 units of inventory. You simulate sales manually. | ||
| 2. **Trigger**: When inventory drops below the critical threshold (20 units), the **Autonomous Agent** wakes up to restock. | ||
| 3. **Discovery (UCP)**: The Agent detects the primary supplier is down (503) and dynamically discovers "Supplier B" via `/.well-known/ucp`. | ||
| 4. **Negotiation (UCP)**: | ||
| * **Initial Intent**: Agent requests 100 units. | ||
| * **Counter-Offer**: Server returns "Incomplete" status (needs Address). | ||
| * **Refinement**: Agent provides Shipping Address + Discount Code (`PARTNER_20`). | ||
| * **Final Offer**: Server calculates Tax + Shipping - Discount and returns a **Binding Total**. | ||
| 5. **Governance (AP2)**: The Agent compares the *Final* price against the standard. | ||
| * **Variance**: High variance detected (>15%). | ||
| * **Policy Check**: The Corporate Spending Policy (`mock_db.py`) pauses for **Human Sign-off**. | ||
| 6. **Execution**: Once approved, the Agent signs a verifiable **AP2 Payment Mandate** for the *exact* final amount and completes the order. | ||
|
|
||
| ## 🛠️ Setup & Installation | ||
|
|
||
| ### Prerequisites | ||
| * Python 3.12+ | ||
| * Google GenAI API Key | ||
|
|
||
| ### 1. Environment Configuration | ||
| Create a `.env.local` file in the root directory: | ||
|
||
| ```bash | ||
| GOOGLE_API_KEY=your_api_key_here | ||
| ``` | ||
|
|
||
| ### 2. Install Dependencies | ||
| ```bash | ||
| pip install fastapi uvicorn requests python-dotenv | ||
|
||
| # Note: google-adk, ucp-sdk, ap2-sdk are currently mocked or included in this demo structure. | ||
|
||
| ``` | ||
|
|
||
| ## 🏃♂️ How to Run | ||
|
|
||
| You will need **two separate terminal windows**. | ||
|
|
||
| ### Terminal 1: The Backup Supplier (Server) | ||
| Start the mock supplier server. This represents "Supplier B". | ||
| ```bash | ||
| python supplier_server.py | ||
| ``` | ||
| *Output: `🏭 [SUPPLIER] Server Online at http://0.0.0.0:8000`* | ||
|
|
||
| ### Terminal 2: The Buyer Agent (Client) | ||
| Run the agent. | ||
| ```bash | ||
| python buyer_agent.py | ||
| ``` | ||
|
|
||
| * **Interactive Loop**: The agent will display current inventory (e.g., `100`). | ||
|
|
||
| #### Scenario A: Normal Operation (Safe Zone) | ||
| If Inventory is **> 20 units**: | ||
| 1. Enter a number (e.g., `50`) to simulate sales. | ||
| 2. The Agent will simply update the inventory count. | ||
| 3. *Result:* "Inventory updated to 50." (No autonomous action taken). | ||
|
|
||
| #### Scenario B: The Crisis (Critical Zone) | ||
| If Inventory drops **<= 20 units** (e.g., enter `85` when you have 100): | ||
| 1. **Autonomous Trigger**: The "Self-Healing" protocol activates immediately. | ||
| 2. **Visual Feedback**: You will see the Agent: | ||
| * Detect Primary Supplier Failure. | ||
| * Discover Backup Supplier (Port 8000). | ||
| * **Negotiate Price**: Adding Shipping/Tax and applying Discounts. | ||
| 3. **Governance Check**: The Agent detects the price variance is too high. | ||
| 4. **Your Input**: You will be prompted to Approve/Deny the transaction. | ||
| * *Input:* Press `Enter` to Approve. | ||
| 5. **Success**: The Agent signs the AP2 Mandate, restocks inventory, and the loop continues. | ||
|
|
||
| ## 🧠 Agent Architecture (Google ADK) | ||
|
|
||
| The Buyer Agent is built using the **Google Agent Development Kit (ADK)**, utilizing a modular "Brain + Tools" pattern: | ||
|
|
||
| * **Model**: Uses `gemini-3-flash-preview` for high-speed reasoning and decision making. | ||
| * **Tools**: Encapsulates specific capabilities as Python functions (`discover_backup_suppliers`, `execute_ucp_transaction`). | ||
| * **Runner**: The ADK `Runner` handles the event loop, routing user inputs (sales data) or system triggers (low inventory) to the model, which then decides which Tool to call. | ||
| * **State**: Uses `InMemorySessionService` to maintain context across the multi-step recovery flow. | ||
|
|
||
| ## � Best Practices Alignment | ||
|
|
||
| This demo adheres to the official **Google Developers UCP & AP2 Architecture**: | ||
|
|
||
| 1. **Dynamic Discovery**: Endpoints are never hardcoded. The Agent resolves capabilities dynamically via `/.well-known/ucp`. | ||
| 2. **Service-Based Architecture**: Separation of concerns between UCP (Commerce) and AP2 (Trust). | ||
| 3. **Verifiable Intent**: Utilizes cryptographic **AP2 Mandates** (Detached JWS) to anchor every transaction to a signed user intent. | ||
| 4. **Standardized Schemas**: Uses official `ucp-sdk` Pydantic models generated from the canonical JSON Schemas. | ||
|
|
||
| ## �🏭 Production Architecture | ||
|
|
||
| In a real-world enterprise environment, this architecture scales from local scripts to distributed cloud services. | ||
|
|
||
| ```mermaid | ||
| graph TD | ||
| subgraph Buyer_Enterprise ["Enterprise Environment (Buyer)"] | ||
| Agent["Supply Chain Agent (Cloud Run)"] | ||
| Orch["Orchestrator (Temporal)"] | ||
| PolicyDB["Policy Engine (OPA)"] | ||
|
|
||
| subgraph Human ["Human-in-the-Loop"] | ||
| Approver(("Supply Chain Manager")) | ||
| Dashboard["Operations Dashboard"] | ||
| end | ||
| end | ||
|
|
||
| subgraph External ["External Ecosystem"] | ||
| Registry["UCP Registry"] | ||
| SupplierA["Supplier A (Primary - DOWN)"] | ||
| SupplierB["Supplier B (Backup - FOUND)"] | ||
| end | ||
|
|
||
| Agent -->|1. Monitor| SupplierA | ||
| Agent -->|2. Discover| Registry | ||
| Registry -->|3. Resolve| SupplierB | ||
| Agent -->|4. Negotiate| SupplierB | ||
|
|
||
| Agent -->|5. Policy Check| PolicyDB | ||
| PolicyDB -- Fail --> Orch | ||
| Orch -->|6. Request Approval| Dashboard | ||
| Approver -->|7. Approve| Dashboard | ||
| Dashboard -->|8. Sign Mandate| Agent | ||
|
|
||
| Agent -->|9. Execute Payment| SupplierB | ||
| ``` | ||
|
|
||
| ### Key Differences in Production | ||
| 1. **Decentralized Discovery**: Instead of a hardcoded `mock_db.py`, the Agent queries a **UCP Registry** or DID Resolver to find verified suppliers dynamically. | ||
| 2. **Cryptographic Trust**: AP2 Mandates are signed with real enterprise Keys (KMS/Vault), providing non-repudiable proof of intent. | ||
| 3. **Governance Dashboard**: The `input()` prompt is replaced by a secure **Operations Dashboard** or Slack/Mobile push notification for one-click approval. | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
undo this