asterpay-openai-agents 1.0.0
AsterPay tools for OpenAI Agents SDK - Enable AI agents to make x402 payments
Requires Python: >=3.10
Keywords: agents, ai, asterpay, crypto, openai, payments, usdc, x402

# AsterPay OpenAI Agents SDK

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

[![PyPI](https://img.shields.io/pypi/v/asterpay-openai-agents)](https://pypi.org/project/asterpay-openai-agents/)
[![Python](https://img.shields.io/pypi/pyversions/asterpay-openai-agents)](https://pypi.org/project/asterpay-openai-agents/)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

## Overview

`asterpay-openai-agents` provides payment tools for the [OpenAI Agents SDK](https://github.com/openai/openai-agents-python), 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

```bash
pip install asterpay-openai-agents
```

## Quick Start

```python
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.

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

### `check_spending`

View spending against configured limits.

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

### `paid_fetch`

Fetch URLs that may require payment (HTTP 402).

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

### `get_transactions`

Get recent payment history.

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

### `make_payment`

Make direct USDC payments.

```python
# 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:

```python
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](https://x402.org) 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:

```python
# 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"`)

```python
# 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

```python
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`

```python
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`

```python
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

- **Website**: [asterpay.io](https://asterpay.io)
- **Demo**: [demo.asterpay.io](https://demo.asterpay.io)
- **Docs**: [asterpay.io/docs](https://asterpay.io/docs)
- **x402 Protocol**: [x402.org](https://x402.org)

## License

MIT License - see [LICENSE](LICENSE) for details.