Skip to content

About

Autonomous agentic commerce platform on Razorpay test-mode APIs — featuring Gemini-powered discovery, margin-safe dynamic negotiation, bounded financial guardrails, and full audit trails.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

⚡ Agentic Commerce & AI Growth Engine

Autonomous B2B/B2C Procurement, Dynamic Margin-Safe Bundles & Verifiable Razorpay Test Mode Settlement powered natively by Google Gemini 2.0 and PostgreSQL pgvector.


🚀 Executive Summary

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:

  1. Missed Revenue & Cart Abandonment: Static price points lose price-sensitive buyers and fail to dynamically upsell high-margin complementary inventory.
  2. Zero Financial Negotiation Capability: Enterprise procurement requires multi-turn bargaining and volume tier discounting.
  3. Financial Hallucination Risk: Unconstrained LLMs cannot be trusted to execute financial transactions or calculate discount totals without strict mathematical boundaries.

The Solution

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.

🏛️ System Architecture

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
Loading

🛡️ "AI Proposes, Python Disposes" Safety & Security Invariant

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

📦 Project Layout

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)

⚡ Quickstart Guide (< 2 Minutes)

1. Prerequisites

  • Python 3.11+ (managed via uv or pip)
  • (Optional) Docker for PostgreSQL + pgvector (system automatically falls back to SQLite if Docker is not running)

2. Environment Configuration

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_2026

3. (Optional) Start PostgreSQL + pgvector Docker Container

docker compose up -d

4. Launch the Platform (One-Click)

Run the automated startup script:

Linux / Mac:

chmod +x start.sh
./start.sh

Windows:

start.bat

Or 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 --all

🖥️ Master CLI Commands

The 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

🌐 Live Service URLs

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

🧪 Comprehensive Verification Suite

Run all 53 unit, integration, protocol, and end-to-end failure injection tests:

uv run pytest -v

Run the 5-scenario headless CLI demo:

uv run python main.py --demo

About

Autonomous agentic commerce platform on Razorpay test-mode APIs — featuring Gemini-powered discovery, margin-safe dynamic negotiation, bounded financial guardrails, and full audit trails.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages