Skip to main content

aipaygen-buyer

Python Buyer SDK for AiPayGen x402 micropayment APIs. Automatically handles 402 Payment Required responses with signed USDC payments on Base Mainnet.

Install

pip install aipaygen-buyer

Quick Start

from aipaygen_buyer import AiPayGenBuyer

client = AiPayGenBuyer(
    private_key="0xYOUR_PRIVATE_KEY",  # or set AIPAYGEN_PRIVATE_KEY env var
    max_price=0.05,      # max $0.05 per call
    daily_budget=5.0,    # max $5/day
)

# Call any AiPayGen API — 402s are handled automatically
result = client.call("/ask", prompt="What is the x402 protocol?")
print(result.data)
print(f"Paid: {result.paid}")

# Check spending
print(f"Budget remaining: ${client.budget_remaining:.2f}")
print(f"Total spent: ${client.stats.total_spent_usdc:.4f}")

Features

  • Auto-402 handling — Detects 402 responses, signs EIP-3009 payments, retries with X-Payment header
  • Policy engine — Per-call price limits, daily/monthly budgets, vendor allowlists/blocklists
  • Transaction tracking — Every payment logged with receipts, timestamps, and tx hashes
  • Async support — AsyncAiPayGenBuyer with identical API using httpx.AsyncClient
  • Discovery — Browse API catalog and x402 protocol metadata

Policy Engine

from aipaygen_buyer import AiPayGenBuyer, SpendingPolicy

policy = SpendingPolicy(
    max_price_per_call=0.02,     # reject calls over $0.02
    daily_budget=2.0,            # $2/day cap
    monthly_budget=50.0,         # $50/month cap
    vendor_allowlist={           # only pay these wallets
        "0x366D488a48de1B2773F3a21F1A6972715056Cb30",
    },
    endpoint_allowlist={"/ask", "/summarize", "/translate"},
)

client = AiPayGenBuyer(private_key="0x...", policy=policy)

Async Usage

import asyncio
from aipaygen_buyer import AsyncAiPayGenBuyer

async def main():
    async with AsyncAiPayGenBuyer(private_key="0x...") as client:
        result = await client.call("/ask", prompt="Hello")
        print(result.data)

asyncio.run(main())

API Key Mode

If you have a prepaid API key, you can skip x402 payments entirely:

client = AiPayGenBuyer(api_key="apk_YOUR_KEY")
result = client.call("/ask", prompt="No crypto needed")

Receipts & Tracking

client = AiPayGenBuyer(private_key="0x...")

client.call("/ask", prompt="First call")
client.call("/summarize", text="Some long text...")

for receipt in client.receipts:
    print(f"{receipt.endpoint}: ${receipt.price_usdc} at {receipt.timestamp}")

stats = client.stats
print(f"Calls today: {stats.calls_today}")
print(f"Spent today: ${stats.spent_today_usdc:.4f}")

Discovery

client = AiPayGenBuyer()

# x402 protocol metadata
info = client.discover()
print(info["chains"])  # Base, Solana

# Browse API catalog
catalog = client.catalog(search="translate", category="ai")

Environment Variables

Variable Description
AIPAYGEN_PRIVATE_KEY Ethereum private key for signing payments
AIPAYGEN_API_KEY Prepaid API key (alternative to x402)

How It Works

  1. SDK makes an API request to AiPayGen
  2. If the endpoint returns 402 Payment Required with x402 headers:
    • X-Price-USDC: Price for the call
    • X-Pay-To: Vendor wallet address
    • X-Network: Chain (eip155:8453 = Base Mainnet)
    • X-Facilitator-URL: Payment processor
  3. SDK checks the payment against your spending policy
  4. If approved, signs an EIP-3009 TransferWithAuthorization for USDC
  5. Retries the request with the signed X-Payment header
  6. Server verifies payment via the facilitator and returns the response
  7. Receipt is logged for tracking

License

MIT

Metadata

Release files for aipaygen-buyer 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aipaygen-buyer 0.1.0
File Size Uploaded Provenance
aipaygen_buyer-0.1.0.tar.gz 10.5 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for aipaygen-buyer 0.1.0
File Interpreter ABI Platform
aipaygen_buyer-0.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 21.1 kB

Release files / aipaygen_buyer-0.1.0.tar.gz

Download URL aipaygen_buyer-0.1.0.tar.gz
Size 10.5 kB
Tags Source
SHA-256 checksum
How to use checksums
ef77f9214905fa64c5401b1ba20d6dc845e94d7a08f8493a9e37c3d3a3c58ae8
BLAKE2b-256 checksum
How to use checksums
e27dd61b37d4aed6c5e20192e1cf736f7c7168da77ab36973b513b1e64b4da5b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.2

Release files / aipaygen_buyer-0.1.0-py3-none-any.whl

Download URL aipaygen_buyer-0.1.0-py3-none-any.whl
Size 10.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fd57fe6be952d2fec01e9dbd8e70ae2777f48c8c51401d9251de0540180c7aba
BLAKE2b-256 checksum
How to use checksums
edc10ac64a16b86039183dbd20efbf67f72c00001efc36859da987423bc56f29
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.11.2

Security for aipaygen-buyer 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page