Skip to main content

AsterPay tools for OpenAI Agents SDK - Enable AI agents to make x402 payments

Project description

AsterPay OpenAI Agents SDK

Give your AI agents the ability to pay for services using the x402 protocol.

PyPI Python License

Overview

asterpay-openai-agents provides payment tools for the OpenAI Agents SDK, enabling AI agents to:

  • Check wallet balance - Know available funds
  • Make payments - Direct USDC transfers
  • Access paid APIs - Automatic x402 payment handling
  • Track spending - Enforce limits and view history

Installation

pip install asterpay-openai-agents

Quick Start

import os
from agents import Agent, Runner
from asterpay_agents import get_asterpay_tools, AsterPayWallet

# Create wallet with spending limits
wallet = AsterPayWallet(
    private_key=os.environ["AGENT_PRIVATE_KEY"],
    network="base",
    name="Research Agent",
    daily_limit=10.0,      # Max $10/day
    monthly_limit=100.0,   # Max $100/month
)

# Create agent with payment tools
agent = Agent(
    name="Research Assistant",
    instructions="""You are a research assistant that can access paid APIs.
    Before making purchases, always check the balance and spending limits.
    Only pay for resources that directly help the user's request.""",
    model="gpt-4o",
    tools=get_asterpay_tools(wallet),
)

# Run the agent
async def main():
    result = await Runner.run(
        agent,
        messages=[{
            "role": "user",
            "content": "Find the latest AI research papers on transformer architectures"
        }]
    )
    print(result.final_output)

import asyncio
asyncio.run(main())

Available Tools

check_balance

Check the current USDC balance of the agent's wallet.

# Agent can call: check_balance()
# Returns: {"balance": "$25.50", "wallet_address": "0x...", "network": "base"}

check_spending

View spending against configured limits.

# Agent can call: check_spending()
# Returns spending for hourly, daily, weekly, monthly periods

paid_fetch

Fetch URLs that may require payment (HTTP 402).

# Agent can call: paid_fetch("https://api.premium-data.com/articles/123")
# Automatically handles x402 payments if needed

get_transactions

Get recent payment history.

# Agent can call: get_transactions(limit=10)
# Returns list of recent payments with amounts, recipients, timestamps

make_payment

Make direct USDC payments.

# Agent can call: make_payment("0x...", 5.00, "Thanks for the service!")
# Sends $5 USDC to the specified address

Spending Limits

Protect your wallet with configurable limits:

wallet = AsterPayWallet(
    private_key=key,
    network="base",
    per_transaction_limit=2.0,  # Max $2 per transaction
    hourly_limit=5.0,           # Max $5 per hour
    daily_limit=25.0,           # Max $25 per day
    weekly_limit=100.0,         # Max $100 per week
    monthly_limit=300.0,        # Max $300 per month
)

Networks

Supported networks:

Network Chain ID Notes
base 8453 Recommended - Low fees
base-sepolia 84532 Testnet
polygon 137 Alternative L2
arbitrum 42161 Alternative L2
ethereum 1 Mainnet (higher fees)

x402 Protocol

The x402 protocol enables machine-to-machine payments via HTTP:

  1. Agent requests a resource
  2. Server returns HTTP 402 with payment details
  3. Agent pays via stablecoin
  4. Server returns the resource

AsterPay handles this automatically:

# This automatically pays if the API requires it
response = await paid_fetch("https://api.paid-service.com/data")

if response["payment_made"]:
    print(f"Paid: {response['payment_amount']}")
print(response["data"])

Security Best Practices

  1. Use environment variables for private keys
  2. Set spending limits appropriate to your use case
  3. Monitor transactions regularly
  4. Use testnet for development (network="base-sepolia")
# Good: Load from environment
wallet = AsterPayWallet(
    private_key=os.environ["AGENT_KEY"],
    daily_limit=10.0,
)

# Bad: Hardcoded key (never do this!)
wallet = AsterPayWallet(private_key="0x123...")

Full Example: Research Agent

import os
from agents import Agent, Runner
from asterpay_agents import get_asterpay_tools, AsterPayWallet

# Configure wallet
wallet = AsterPayWallet(
    private_key=os.environ["AGENT_KEY"],
    network="base",
    name="Research Bot",
    daily_limit=20.0,
    per_transaction_limit=1.0,
)

# Create agent
agent = Agent(
    name="Research Agent",
    instructions="""You are a research assistant with access to paid APIs.

    RULES:
    1. Always check balance before making purchases
    2. Only pay for directly relevant resources
    3. Summarize findings clearly
    4. Report any payment failures
    
    You have access to payment tools:
    - check_balance: View available funds
    - check_spending: View spending against limits
    - paid_fetch: Access paid APIs (auto-pays)
    - get_transactions: View payment history
    """,
    model="gpt-4o",
    tools=get_asterpay_tools(wallet, max_auto_pay=0.50),
)

# Run
async def research(query: str):
    result = await Runner.run(
        agent,
        messages=[{"role": "user", "content": query}]
    )
    return result.final_output

# Usage
import asyncio
answer = asyncio.run(research("What are the latest breakthroughs in quantum computing?"))
print(answer)

API Reference

AsterPayWallet

AsterPayWallet(
    private_key: str,           # Ethereum private key
    network: str = "base",      # Network to use
    name: str = "AI Agent",     # Wallet name
    per_transaction_limit: float = None,
    hourly_limit: float = None,
    daily_limit: float = None,
    weekly_limit: float = None,
    monthly_limit: float = None,
)

get_asterpay_tools

get_asterpay_tools(
    wallet: AsterPayWallet,     # Configured wallet
    auto_pay: bool = True,      # Auto-pay x402 challenges
    max_auto_pay: float = 1.0,  # Max auto-pay amount
) -> List[Callable]

Links

License

MIT License - see LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

asterpay_openai_agents-1.0.0.tar.gz (15.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

asterpay_openai_agents-1.0.0-py3-none-any.whl (15.3 kB view details)

Uploaded Python 3

File details

Details for the file asterpay_openai_agents-1.0.0.tar.gz.

File metadata

  • Download URL: asterpay_openai_agents-1.0.0.tar.gz
  • Upload date:
  • Size: 15.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.0

File hashes

Hashes for asterpay_openai_agents-1.0.0.tar.gz
Algorithm Hash digest
SHA256 55864d09d9cadd2c4e254be66f1971ae06ef01a0883e956c23346527b75ddd2e
MD5 4cdae1dc89082cc0a7517cd8bd94a572
BLAKE2b-256 f7e49ecb6af393c74856dd2e5085c56123af46edd47ebf29faa47517c45abd4a

See more details on using hashes here.

File details

Details for the file asterpay_openai_agents-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for asterpay_openai_agents-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a25f2ce4b97b081c7ee7ab9188f610fc7d0c5df426ffd678adf8b9e85c6c793c
MD5 a1475d1ff1324314869d0cf78b0e7acd
BLAKE2b-256 0c212e3151f72aaa0b95d2559e5d6cba8ff8ded4366f8515c8e43d87369a2ac8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page