The x402-Agent Framework enables AI agents to autonomously pay for API access, tools, and services using cryptocurrency micropayments. When an agent encounters an HTTP 402 "Payment Required" response, it automatically processes the payment and continues with the task.
level42 is an early-stage Python project in the AI payments / x402 ecosystem. It currently has 1 GitHub stars and 0 forks.
A lightweight Python framework for building autonomous AI agents that can pay for tools, APIs, and other agents in real-time using L42 micropayments.
The Level42 Framework eliminates API key management and subscription friction by enabling pay-per-use interactions through HTTP 402 status codes and USDC payments on blockchain networks. Build agents that can autonomously discover, pay for, and use external services without manual intervention.
pip install level42
# Include Solana support
pip install level42[solana]
# Include development tools
pip install level42[dev]
# Include documentation tools
pip install level42[docs]
# Install everything
pip install level42[solana,dev,docs]
git clone https://github.com/tjelz/level42.git
cd level42
pip install -e ".[dev]"
from level42 import Level42Agent
from langchain_openai import ChatOpenAI
# Initialize your LLM
llm = ChatOpenAI(model="gpt-4")
# Create an agent with your wallet
agent = Level42Agent(
llm=llm,
wallet_key="your_base_network_private_key"
)
# Register a paid API tool
agent.register_tool(
name="weather",
endpoint="https://api.weather.com/v1/current",
description="Get current weather data"
)
# Run a task - payments handled automatically
result = agent.run("Get the current weather in San Francisco")
print(result)
from level42 import Level42Agent, AgentSwarm
from langchain_openai import ChatOpenAI
# Create multiple agents
llm = ChatOpenAI(model="gpt-4")
agent1 = Level42Agent(llm=llm, wallet_key="key1")
agent2 = Level42Agent(llm=llm, wallet_key="key2")
# Create a swarm with shared wallet
swarm = AgentSwarm(shared_wallet=True)
swarm.add_agent(agent1)
swarm.add_agent(agent2)
# Collaborate on a task with automatic cost splitting
result = swarm.collaborate("Research the latest AI developments and summarize findings")
from level42 import Level42Agent, PaymentProcessor
agent = Level42Agent(llm=llm, wallet_key="your_key")
# Configure deferred payments (batches after 10 calls)
processor = PaymentProcessor(agent.wallet_manager)
# Make multiple API calls - payments batched automatically
for i in range(15):
result = agent.run(f"API call {i}")
# Payments processed in batch after 10th call
Visit our comprehensive documentation at docs.level42.dev for:
from level42 import Level42Agent
agent = Level42Agent(
llm=your_llm, # LangChain-compatible LLM
wallet_key="0x...", # Private key for payments
network="base", # Blockchain network
max_spend_per_hour=10.0 # Spending limit in USDC
)
# Register API tools
agent.register_tool("weather", "https://api.weather.com/v1/current")
# Execute tasks with automatic payments
result = agent.run("What's the weather in San Francisco?")
# Check balance and transfer funds
balance = agent.get_balance()
agent.transfer_to_agent("other_agent", 5.0)
from level42.swarm import AgentSwarm
swarm = AgentSwarm(shared_wallet=True, cost_splitting="equal")
swarm.add_agent(researcher, "researcher")
swarm.add_agent(analyst, "analyst")
# Collaborative task execution
result = swarm.collaborate(
task="Research AI developments and create analysis",
strategy="sequential" # or "parallel", "divide_and_conquer"
)
# Automatic cost splitting and fund transfers
swarm.split_costs(total_cost)
swarm.transfer_funds("agent1", "agent2", 10.0)
from level42.wallet import WalletManager
wallet = WalletManager("0xprivate_key...", network="base")
# Balance and payment operations
balance = wallet.get_balance()
native_balance = wallet.get_native_balance()
# Single and batch payments
tx_hash = wallet.make_payment(1.0, "0xrecipient...")
tx_hashes = wallet.batch_payments([payment1, payment2, payment3])
# Transaction monitoring
history = wallet.get_transaction_history()
For complete API documentation with all methods, parameters, and examples, visit the API Reference section.
# Optional: Set default network
export LEVEL42_DEFAULT_NETWORK=base
# Optional: Set default spending limits
export LEVEL42_MAX_SPEND_PER_HOUR=10.0
# Optional: Enable debug logging
export LEVEL42_DEBUG=true
Create ~/.level42/config.yaml:
default_network: base
max_spend_per_hour: 10.0
deferred_payment_threshold: 10
networks:
base:
rpc_url: "https://mainnet.base.org"
usdc_contract: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
solana:
rpc_url: "https://api.mainnet-beta.solana.com"
usdc_mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
from level42 import Level42Agent
from langchain_openai import ChatOpenAI
# Create trading agent
agent = Level42Agent(
llm=ChatOpenAI(model="gpt-4"),
wallet_key="your_key",
max_spend_per_hour=50.0
)
# Register financial data APIs
agent.register_tool("stock_price", "https://api.stocks.com/v1/price")
agent.register_tool("crypto_price", "https://api.crypto.com/v1/price")
# Execute trading strategy
result = agent.run("""
Analyze AAPL stock price and BTC price.
If AAPL is down more than 2% and BTC is up more than 5%,
recommend a trading strategy.
""")
from level42 import Level42Agent, AgentSwarm
# Create specialized research agents
researcher = Level42Agent(llm=llm, wallet_key="key1")
analyst = Level42Agent(llm=llm, wallet_key="key2")
writer = Level42Agent(llm=llm, wallet_key="key3")
# Register different tools for each agent
researcher.register_tool("arxiv", "https://api.arxiv.org/search")
analyst.register_tool("sentiment", "https://api.sentiment.com/analyze")
writer.register_tool("grammar", "https://api.grammar.com/check")
# Create collaborative swarm
swarm = AgentSwarm(shared_wallet=True)
swarm.add_agent(researcher)
swarm.add_agent(analyst)
swarm.add_agent(writer)
# Execute research project
report = swarm.collaborate("""
Research recent developments in quantum computing,
analyze market sentiment,
and write a comprehensive report.
""")
# Run all tests
make test
# Run with coverage
python -m pytest tests/ -v --cov=x402_agent --cov-report=html
# Run specific test file
python -m pytest tests/test_agent.py -v
# Format code
make format
# Run linting
make lint
# Type checking
make type-check
# Security audit
make security-check
# Install docs dependencies
pip install -e ".[docs]"
# Build docs
make docs
# Serve docs locally
cd docs && python -m http.server 8000
# Check your wallet balance
balance = agent.get_balance()
print(f"Current balance: {balance} USDC")
# Fund your wallet with USDC on Base Network
# Visit https://bridge.base.org to bridge funds
# Ensure your private key is valid and has 0x prefix
wallet_key = "0x1234567890abcdef..." # 64 hex characters
# Test wallet connection
from x402_agent import WalletManager
wallet = WalletManager(wallet_key, "base")
print(f"Wallet address: {wallet.address}")
# Check network configuration
agent = Level42Agent(
llm=llm,
wallet_key="your_key",
network="base" # or "solana"
)
# Verify RPC endpoint
import requests
response = requests.get("https://mainnet.base.org")
print(f"Network status: {response.status_code}")
# Enable debug logging
import logging
logging.basicConfig(level=logging.DEBUG)
# Check API response format
# Ensure the API returns proper x402 headers:
# X-Payment-Amount: 0.01
# X-Payment-Address: 0x1234...
# X-Payment-Currency: USDC
# Enable debug logging
import logging
logging.basicConfig(level=logging.DEBUG)
# Create agent with debug mode
agent = Level42Agent(
llm=llm,
wallet_key="your_key",
debug=True
)
# Monitor payment transactions
agent.payment_processor.enable_logging()
# Optimize for high-frequency trading
agent = Level42Agent(
llm=llm,
wallet_key="your_key",
deferred_payment_threshold=50, # Batch more payments
max_spend_per_hour=1000.0 # Higher spending limit
)
# Use connection pooling for better performance
import requests
session = requests.Session()
agent.payment_processor.session = session
# Get spending summary
summary = agent.get_spending_summary()
print(f"Total spent today: ${summary['today']}")
print(f"Most expensive tool: {summary['top_tool']}")
# Export transaction history
transactions = agent.export_transactions()
import pandas as pd
df = pd.DataFrame(transactions)
df.to_csv("agent_transactions.csv")
# Set up spending alerts
def spending_alert(amount, tool_name):
if amount > 1.0: # Alert for payments over $1
print(f"High payment alert: ${amount} for {tool_name}")
agent.payment_processor.add_callback(spending_alert)
# Monitor agent health
health = agent.get_health_status()
print(f"Agent status: {health['status']}")
print(f"Wallet balance: ${health['balance']}")
print(f"Active tools: {health['tools_count']}")
We welcome contributions! Please see our Contributing Guide for details.
# Clone the repository
git clone https://github.com/tjelz/level42.git
cd level42
# Install in development mode
pip install -e ".[dev]"
# Run tests
make test
# Submit a pull request
Please report bugs and feature requests on our GitHub Issues page.
This project is licensed under the MIT License - see the LICENSE file for details.
The Level42 Framework will soon launch its native utility token to power the ecosystem:
Stay tuned for the official token launch announcement!
Built with ❤️ by the Level42 team
Empowering the future of autonomous AI through seamless micropayments
The living ecosystem where AI agents complete tasks through workflow loops, improve through iterative execution, are evaluated by mentor agents or humans in the loop, and turn completed work into reusable work experience and data to improve future agents.
The living ecosystem where AI agents complete tasks through workflow loops, improve through iterative execution, are evaluated by mentor agents or humans in the loop, and turn completed work into reusable work experience and data to improve future agents.
Self-healing infrastructure for AI agent payments. 90.3% auto-recovery.
The first agentic payment network: policy-controlled, gasless, and real money-ready. OmniClaw CLI + Financial Policy Engine let autonomous agents pay and earn safely at machine speed.
The A2A x402 Extension brings cryptocurrency payments to the Agent-to-Agent (A2A) protocol, enabling agents to monetize their services through on-chain payments. This extension revives the spirit of HTTP 402 "Payment Required" for the decentralized agent ecosystem.
DePIN for Vintage Hardware — Proof-of-Antiquity blockchain where old machines outmine new ones. AI-powered hardware fingerprinting, 15+ CPU architectures, Solana bridge (wRTC). $0 VC.