Skip to content
Open
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
d0494de
Add Python Self-Healing Supply Chain Sample (UCP/AP2)
heiko-hotz Jan 13, 2026
14b738f
Update: Interactive Mode, Gemini 3, and Best Practices
heiko-hotz Jan 13, 2026
d90aad3
Update: Upgrade to Gemini 3 Flash Preview (README)
heiko-hotz Jan 13, 2026
09bdc2a
docs: Update README with detailed negotiation flow and usage scenarios
heiko-hotz Jan 20, 2026
79f01e0
refactor: Revert mandate token verification (demo clarity)
heiko-hotz Jan 20, 2026
4c31805
feat: Sync Negotiation Loop and full file parity
heiko-hotz Jan 20, 2026
945b378
fix(ucp): resolve pydantic v2 validation and import errors
heiko-hotz Jan 20, 2026
622ede1
docs: sync final README and PR description
heiko-hotz Jan 20, 2026
6886486
Merge branch 'Universal-Commerce-Protocol:main' into feature/self-hea…
heiko-hotz Jan 20, 2026
ade31f5
Sync self-healing-supply-chain sample with latest project usage and c…
heiko-hotz Feb 4, 2026
4082301
Uncomment and pin adk/ucp/ap2 dependencies
heiko-hotz Feb 4, 2026
3bfbfb6
Bump google-genai to 1.57.0
heiko-hotz Feb 4, 2026
9eded53
Update dependencies to match existing .venv versions
heiko-hotz Feb 4, 2026
a126dca
Update ap2 dependency to standard git URL
heiko-hotz Feb 4, 2026
2d29498
Add a2a-sdk dependency
heiko-hotz Feb 4, 2026
42d15b1
feat(supply-chain-demo): add safety mechanism and start script
heiko-hotz Feb 5, 2026
61b58ec
refactor: address PR review feedback
heiko-hotz Feb 5, 2026
a0880e0
docs: add emoji to Best Practices Alignment heading
heiko-hotz Feb 5, 2026
5ca6b5f
docs: document ADK authentication options (Gemini vs Vertex)
heiko-hotz Feb 5, 2026
ffa0de5
docs: minor fix to cloud location in README
heiko-hotz Feb 5, 2026
235d9fb
Merge upstream main, restoring root README.md to address PR feedback
heiko-hotz Feb 5, 2026
940e9e5
docs: add demo video to self-healing supply chain README
heiko-hotz Feb 6, 2026
f356615
docs: fix video embed url to use absolute github raw path
heiko-hotz Feb 6, 2026
45ec3bf
docs: use markdown image syntax for video embed
heiko-hotz Feb 6, 2026
e62748e
docs: replace local video with youtube embed
heiko-hotz Feb 6, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 0 additions & 55 deletions README.md
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

undo this

This file was deleted.

40 changes: 40 additions & 0 deletions pr_description.md
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove before merging

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`.
23 changes: 23 additions & 0 deletions python/self-healing-supply-chain/.gitignore
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/
137 changes: 137 additions & 0 deletions python/self-healing-supply-chain/README.md
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:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clarify this is not the actual root, but the base directory for this sample

```bash
GOOGLE_API_KEY=your_api_key_here
```

### 2. Install Dependencies
```bash
pip install fastapi uvicorn requests python-dotenv
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add instructions to create a venv before installing dependencies

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add a2a-sdk

# Note: google-adk, ucp-sdk, ap2-sdk are currently mocked or included in this demo structure.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you explain this? I actually need to install these dependencies to be able to run the demo

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also, please add versions in the dependencies. consider adding requirements.txt instead

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

actually, saw there's a requirements.txt. just update this instruction then.

```

## 🏃‍♂️ 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.
Loading