Metadata-Version: 2.4
Name: crewai-x402
Version: 0.1.0
Summary: x402 payment protocol integration for CrewAI - enable AI agents to pay for APIs with USDC
Project-URL: Homepage, https://agentrails.io
Project-URL: Documentation, https://agentrails.io/docs
Project-URL: Repository, https://github.com/kmatthewsio/crewai-x402
Project-URL: Issues, https://github.com/kmatthewsio/crewai-x402/issues
Author-email: AgentRails <dev@agentrails.io>
License-Expression: MIT
License-File: LICENSE
Keywords: ai-agents,api-monetization,crewai,crypto,payments,usdc,x402
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: crewai>=0.10.0
Requires-Dist: eth-account>=0.10.0
Requires-Dist: eth-typing>=3.0.0
Requires-Dist: httpx>=0.25.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: dev
Requires-Dist: mypy>=1.0.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
Requires-Dist: pytest-httpx>=0.22.0; extra == 'dev'
Requires-Dist: pytest>=7.0.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Description-Content-Type: text/markdown

# crewai-x402

[![PyPI version](https://badge.fury.io/py/crewai-x402.svg)](https://pypi.org/project/crewai-x402/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**Enable CrewAI agents to pay for APIs with USDC using the x402 protocol.**

crewai-x402 integrates the [x402 payment protocol](https://x402.org) with CrewAI, allowing your AI agent crews to autonomously access paid APIs without managing API keys or subscriptions.

## What is x402?

x402 is the HTTP-native payment protocol that finally implements the `402 Payment Required` status code. Instead of API keys and monthly subscriptions, software pays software—per request, in USDC, with cryptographic proof.

**How it works:**
1. Agent requests a resource
2. Server returns `402 Payment Required` with price info
3. Agent signs a USDC payment authorization (EIP-3009)
4. Agent retries with payment proof
5. Server settles on-chain, returns data

All in a single HTTP round-trip.

## Installation

```bash
pip install crewai-x402
```

## Quick Start

```python
import os
from crewai import Agent, Crew, Task
from crewai_x402 import X402Wallet, X402Tool

# 1. Create a wallet with a USDC budget
wallet = X402Wallet(
    private_key=os.environ["WALLET_PRIVATE_KEY"],
    network="base-mainnet",
    budget_usd=10.00
)

# 2. Create the payment tool
payment_tool = X402Tool(wallet=wallet)

# 3. Add to your agent
researcher = Agent(
    role="Research Analyst",
    goal="Find accurate data using any available source",
    backstory="You have access to both free and paid APIs.",
    tools=[payment_tool],
)

# 4. Agent can now pay for premium data
task = Task(
    description="Get premium market data from https://api.example.com/premium",
    agent=researcher,
)

crew = Crew(agents=[researcher], tasks=[task])
result = crew.kickoff()
```

## Features

### Automatic Payment Handling
The `X402Tool` automatically detects 402 responses and handles payment negotiation:

```python
tool = X402Tool(
    wallet=wallet,
    auto_pay=True,  # Automatically pay when within budget
    timeout=30.0,   # Request timeout in seconds
)
```

### Budget Control
Set spending limits at the wallet level:

```python
wallet = X402Wallet(
    private_key=key,
    network="base-mainnet",
    budget_usd=5.00  # Crew can't spend more than $5
)

# Check remaining budget
print(f"Remaining: ${wallet.remaining_usd}")

# Check if can afford a specific amount
if wallet.can_afford(0.01):
    print("Can afford $0.01 request")
```

### Per-Request Price Limits
Limit how much an agent can pay for a single request:

```python
# When calling the tool directly
result = tool._run(
    url="https://api.example.com/expensive",
    max_price_usd=0.05  # Won't pay more than $0.05 for this request
)
```

### Payment History
Track all payments made by the wallet:

```python
for payment in wallet.payments:
    print(f"{payment.resource_url}: ${payment.amount_usd}")

# Get summary
summary = wallet.get_payment_summary()
print(f"Total spent: ${summary['spent_usd']}")
print(f"Payments made: {summary['payment_count']}")
```

### Multi-Network Support
Supports multiple EVM networks:

```python
# Base (recommended - low fees)
wallet = X402Wallet(private_key=key, network="base-mainnet")

# Ethereum
wallet = X402Wallet(private_key=key, network="ethereum-mainnet")

# Testnets
wallet = X402Wallet(private_key=key, network="base-sepolia")
wallet = X402Wallet(private_key=key, network="arc-testnet")
```

## API Reference

### X402Wallet

```python
X402Wallet(
    private_key: str,      # Hex-encoded private key
    network: str,          # Network name (e.g., "base-mainnet")
    budget_usd: float,     # Maximum USD to spend
)
```

**Properties:**
- `address` - Wallet address
- `spent_usd` - Total USD spent
- `remaining_usd` - Remaining budget
- `payments` - List of PaymentRecord objects

**Methods:**
- `can_afford(amount_usd)` - Check if budget allows payment
- `sign_payment(to, amount, valid_before)` - Sign EIP-3009 authorization
- `get_payment_summary()` - Get spending summary dict
- `reset_budget(new_budget)` - Reset budget and clear history

### X402Tool

```python
X402Tool(
    wallet: X402Wallet,    # Wallet for payments
    auto_pay: bool = True, # Auto-pay when within budget
    timeout: float = 30.0, # HTTP timeout
)
```

**Tool Input Fields:**
- `url` (required) - URL to request
- `method` - HTTP method (default: "GET")
- `body` - Request body
- `headers` - Additional headers
- `max_price_usd` - Per-request price limit

## Networks

| Network | Chain ID | Environment |
|---------|----------|-------------|
| `base-mainnet` | 8453 | Production |
| `base-sepolia` | 84532 | Testnet |
| `ethereum-mainnet` | 1 | Production |
| `ethereum-sepolia` | 11155111 | Testnet |
| `arc-testnet` | 5042002 | Testnet |

## Security Considerations

1. **Never commit private keys** - Use environment variables or secret managers
2. **Set appropriate budgets** - Limit what crews can spend
3. **Use testnets first** - Test with `base-sepolia` before mainnet
4. **Monitor spending** - Check `wallet.get_payment_summary()` regularly

## Examples

See the [examples/](examples/) directory:
- `research_crew.py` - Research crew with payment capability

## How It Differs From API Keys

| API Keys | x402 |
|----------|------|
| 1 key per service | 1 wallet for all services |
| Monthly subscriptions | Pay per request |
| Human signup required | Zero onboarding |
| Credential rotation | No credentials to leak |
| Service-level limits | Agent-level budgets |

## Related Packages

- [langchain-x402](https://pypi.org/project/langchain-x402/) - x402 integration for LangChain

## Resources

- [x402 Protocol Spec](https://x402.org)
- [AgentRails Documentation](https://agentrails.io/docs)
- [EIP-3009 Specification](https://eips.ethereum.org/EIPS/eip-3009)
- [CrewAI Documentation](https://docs.crewai.com)

## License

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

## Contributing

Contributions welcome! Please read our contributing guidelines and submit PRs to the [GitHub repository](https://github.com/kmatthewsio/crewai-x402).
