Autonomous B2B/B2C Procurement, Dynamic Margin-Safe Bundles & Verifiable Razorpay Test Mode Settlement powered natively by Google Gemini 2.0 and PostgreSQL pgvector.
As AI agents increasingly make autonomous purchasing decisions on behalf of consumers and enterprises (via emerging standards like Google AP2 / NPCI Universal Agent Protocol (UAP) / x402), traditional static e-commerce checkout flows fail:
- Missed Revenue & Cart Abandonment: Static price points lose price-sensitive buyers and fail to dynamically upsell high-margin complementary inventory.
- Zero Financial Negotiation Capability: Enterprise procurement requires multi-turn bargaining and volume tier discounting.
- Financial Hallucination Risk: Unconstrained LLMs cannot be trusted to execute financial transactions or calculate discount totals without strict mathematical boundaries.
The Agentic Commerce & AI Growth Engine introduces an "AI Proposes, Python Disposes" architecture:
- Autonomous Revenue Intelligence: Native Google Gemini 2.0 reasons over buyer intent, negotiates multi-turn enterprise deals, and calculates context-aware product bundles.
- Strict Mathematical Policy Guardrails: Deterministic Python validation enforces merchant floor prices (
min_negotiable_price_paisa), hard discount caps (25%), transaction velocity limits (₹20,000 ceiling), and HMAC-SHA256 cryptographic quote signing before payment generation. - Razorpay Test Settlement Rails: Seamless conversion of AI quote proposals into native Razorpay Orders, Payment Links, and Webhook-driven settlement updates.
- Universal Agent Protocol (UAP/AP2) Gateway: Standardized machine-readable manifests (
/.well-known/agent-catalog.json) and API endpoints allowing external autonomous AI buyer agents to discover, negotiate, and checkout programmatically.
flowchart TD
subgraph External_AI_World["External World & Autonomous AI Buyers"]
BuyerAgent["Autonomous AI Buyer Agent\n(AP2 / UAP / x402)"]
HumanBuyer["Human Shopper / UI\n(Streamlit Cockpit)"]
end
subgraph Gateway_Layer["Standardized Inbound Gateway"]
UAP["UAP / AP2 Gateway (FastAPI)\n/.well-known/agent-catalog.json\n/api/v1/uap/negotiate\n/api/v1/uap/checkout\n(src/api/gateway.py)"]
end
subgraph LangGraph_Orchestrator["LangGraph Master State Machine (src/agents/orchestrator.py)"]
Router["Dynamic Flow Router\n(Gemini 2.0 Flash)"]
Discovery["Catalog Discovery Node\n(pgvector HNSW Cosine Search)"]
UpsellNode["Dynamic Bundler Node\n(UpsellAgent)"]
NegNode["B2B Negotiator Node\n(NegotiationAgent)"]
QuoteNode["Initial Quote Node"]
end
subgraph Guardrail_Layer["Policy Gatekeeper (Deterministic Python)"]
Guardrail["GuardrailAgent (src/agents/guardrail.py)\n- Floor Price Clamp (min_negotiable_price_paisa)\n- Max Discount Cap (25% hard cap)\n- INR 20,000 Velocity Cap -> HITL\n- HMAC-SHA256 Merchant Signing"]
end
subgraph Execution_Settlement["Razorpay Test Settlement Layer"]
RZPClient["RazorpayTestClient\n(src/clients/razorpay.py)"]
RZPAPI["Razorpay Payment Rails (Test Mode)\n- Orders API\n- Payment Links API"]
Webhook["Razorpay Webhook Handler\n(order.paid -> SETTLED)\n(src/api/webhook.py)"]
end
subgraph Storage_Layer["Data & Telemetry Engine"]
PG["PostgreSQL 16 + pgvector (HNSW Index)\n(Dual-Engine SQLite fallback)\n(src/db/database.py)"]
Audit["Immutable Audit Logger\n(src/telemetry/audit.py)"]
end
BuyerAgent -->|HTTP POST| UAP
HumanBuyer -->|Web UI| Router
UAP --> Router
Router --> Discovery
Discovery --> PG
Discovery --> QuoteNode
Discovery --> UpsellNode
Discovery --> NegNode
QuoteNode --> Guardrail
UpsellNode --> Guardrail
NegNode --> Guardrail
Guardrail -->|Approved / Clamped| RZPClient
Guardrail -->|Rejected > INR 20k| HumanBuyer
RZPClient --> RZPAPI
RZPAPI -.->|Webhook Event| Webhook
Webhook --> PG
Discovery -.-> Audit
Guardrail -.-> Audit
RZPClient -.-> Audit
Webhook -.-> Audit
To guarantee complete financial security and prevent prompt-injection exploits:
| Security Layer | Invariant Enforcement | Action on Breach |
|---|---|---|
| Price Floor Guard | unit_price_paisa >= min_negotiable_price_paisa |
Clamped immediately to merchant floor (CLAMPED) |
| Max Discount Cap | discount_pct <= sku.max_discount_percentage (max 25%) |
Clamped to permissible discount ceiling (CLAMPED) |
| Transaction Ceiling | total_price_paisa <= ₹20,000 (2,000,000 paisa) |
Blocked from auto-execution; routed to HITL Drawer (REJECTED) |
| Inventory Guard | requested_qty <= live_inventory_count |
Rejects order; AI offers stockout remediation |
| Prompt Injection Defense | Regex + semantic sanitization against price-override jailbreaks | Stripped and marked REJECTED in audit trace |
| Cryptographic Signatures | HMAC-SHA256(quote_id + sku_id + price + ttl, SECRET) |
Prevents external tampering of AI quotes |
razorpay_agents/
├── main.py # Master entry point CLI (flags: --demo, --server, --ui, --all, --seed, --failures)
├── demo_walkthrough.py # One-click multi-service demo orchestrator (UAP Gateway + Streamlit UI)
├── start.sh / start.bat # One-click platform startup scripts
├── docker-compose.yml # PostgreSQL 16 + pgvector container configuration
├── init.sql # Database schema & HNSW cosine index definition
├── pyproject.toml # Project dependencies and tool configuration
├── src/ # Modular production source tree
│ ├── config.py # Central Pydantic Settings & prompt injection security rules
│ ├── main.py # Master CLI execution flow and interactive scenarios
│ ├── core/
│ │ └── schemas.py # Pydantic v2 schemas & HMAC cryptographic quote signing
│ ├── utils/
│ │ ├── crypto.py # Consolidated HMAC-SHA256 & timing-safe comparisons
│ │ ├── formatting.py # Currency converters (Paisa <-> INR) & ISO helpers
│ │ └── logging.py # Structured logging configuration
│ ├── clients/
│ │ ├── gemini.py # Google Gemini 2.0 Flash & text-embedding-004 SDK client
│ │ └── razorpay.py # Razorpay Test Mode client with retry & deterministic mocks
│ ├── db/
│ │ ├── database.py # Dual-engine DB driver (PostgreSQL pgvector / SQLite FTS5 fallback)
│ │ └── seed.py # Catalog SKU seed data with 768-D dense embeddings
│ ├── agents/
│ │ ├── state.py # TypedDict global state containers for LangGraph
│ │ ├── catalog.py # Catalog Discovery Agent (Intent parsing + semantic search)
│ │ ├── guardrail.py # Deterministic policy gatekeeper & financial validator
│ │ ├── negotiation.py # Multi-turn B2B procurement negotiator
│ │ ├── upsell.py # Dynamic margin-safe bundler & cart recovery agent
│ │ └── orchestrator.py # LangGraph state machine master orchestrator
│ ├── telemetry/
│ │ └── audit.py # Immutable telemetry logger and transaction trace inspector
│ ├── api/
│ │ ├── gateway.py # Universal Agent Protocol (UAP) & AP2 FastAPI Gateway
│ │ └── webhook.py # Razorpay Webhook receiver with signature verification
│ └── ui/
│ └── app.py # Streamlit Visual Merchant & AI Buyer Cockpit
└── tests/ # Comprehensive test suite (53 automated tests)
- Python 3.11+ (managed via
uvorpip) - (Optional) Docker for PostgreSQL + pgvector (system automatically falls back to SQLite if Docker is not running)
Copy .env.example to .env and provide your API keys:
cp .env.example .env# Google Gemini API Key
GEMINI_API_KEY=AIzaSy...
# Razorpay Test Mode Credentials (Optional - auto-mocks if unset)
RAZORPAY_KEY_ID=rzp_test_...
RAZORPAY_KEY_SECRET=...
RAZORPAY_WEBHOOK_SECRET=test_webhook_secret_hmac_2026
# Merchant Security Secret
MERCHANT_HMAC_SECRET=agentic_commerce_default_secret_key_2026docker compose up -dRun the automated startup script:
Linux / Mac:
chmod +x start.sh
./start.shWindows:
start.batOr launch via uv:
# Launch UAP Gateway (FastAPI) + Streamlit Cockpit in parallel:
uv run python demo_walkthrough.py
# Or run the unified master entry point:
uv run python main.py --allThe unified main.py entry point supports multiple execution modes:
# Run 5-Scenario Interactive Headless CLI Demo:
uv run python main.py --demo
# Start the UAP / AP2 Gateway Server (FastAPI):
uv run python main.py --server
# Launch the Streamlit Merchant & AI Buyer Cockpit:
uv run python main.py --ui
# Run Failure Injection & Self-Healing Scenarios:
uv run python main.py --failures
# Seed the Catalog with Dense 768-D Vector Embeddings:
uv run python main.py --seed
# Launch Gateway Server + Streamlit UI simultaneously:
uv run python main.py --all| Service | Port | Endpoint URL | Description |
|---|---|---|---|
| Streamlit Cockpit | 8501 |
http://localhost:8501 |
Visual Buyer Simulator, Seller Control Plane & Audit Inspector |
| UAP Machine Manifest | 8000 |
http://localhost:8000/.well-known/agent-catalog.json |
JSON-LD Feed & Capability Manifest for External AI Agents |
| UAP Negotiation API | 8000 |
http://localhost:8000/api/v1/uap/negotiate |
Machine-to-Machine Intent & Negotiation Endpoint |
| UAP Checkout API | 8000 |
http://localhost:8000/api/v1/uap/checkout |
Pre-signed Razorpay Order Generation |
| Razorpay Webhooks | 8000 |
http://localhost:8000/webhook/razorpay |
Asynchronous Payment Settlement Synchronization |
Run all 53 unit, integration, protocol, and end-to-end failure injection tests:
uv run pytest -vRun the 5-scenario headless CLI demo:
uv run python main.py --demo