Skip to main content

x402 payment protocol integration for LangChain - enable AI agents to pay for APIs with USDC

Project description

langchain-x402

PyPI version License: MIT

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

langchain-x402 integrates the x402 payment protocol with LangChain, allowing your AI agents 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

pip install langchain-x402

Quick Start

import os
from langchain_x402 import X402Wallet, X402PaymentTool
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_react_agent

# 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
tool = X402PaymentTool(wallet=wallet)

# 3. Add to your agent
llm = ChatOpenAI(model="gpt-4o")
agent = create_react_agent(llm, tools=[tool], prompt=your_prompt)
executor = AgentExecutor(agent=agent, tools=[tool])

# 4. Agent can now access any x402-enabled API
result = executor.invoke({
    "input": "Get premium data from https://api.example.com/paid-endpoint"
})

Features

Automatic Payment Handling

The X402PaymentTool automatically detects 402 responses and handles payment negotiation:

tool = X402PaymentTool(
    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:

wallet = X402Wallet(
    private_key=key,
    network="base-mainnet",
    budget_usd=5.00  # Agent 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:

# In the tool input
result = tool.invoke({
    "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:

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:

# 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

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

X402PaymentTool

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

Tool Input Schema:

{
    "url": str,                    # Required: URL to request
    "method": str = "GET",         # HTTP method
    "body": str | None,            # Request body
    "headers": dict | None,        # Additional headers
    "max_price_usd": float | None, # 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 agents 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/ directory:

  • basic_agent.py - Simple ReAct agent with payment capability
  • multi_api.py - Agent accessing multiple paid APIs

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

Resources

License

MIT License - see LICENSE for details.

Contributing

Contributions welcome! Please read our contributing guidelines and submit PRs to the GitHub repository.

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

langchain_x402-0.1.0.tar.gz (12.2 kB view details)

Uploaded Source

Built Distribution

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

langchain_x402-0.1.0-py3-none-any.whl (12.0 kB view details)

Uploaded Python 3

File details

Details for the file langchain_x402-0.1.0.tar.gz.

File metadata

  • Download URL: langchain_x402-0.1.0.tar.gz
  • Upload date:
  • Size: 12.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for langchain_x402-0.1.0.tar.gz
Algorithm Hash digest
SHA256 26fc4a69f51b39e57a52e7058b2cb4117aa758fe189566223c0f132db5dfb673
MD5 7117a59db9b96a1a1b9bafe851ea613e
BLAKE2b-256 9fbdc967e2972b7e573eaf76de17c7533552592ea441d204836b75e43c0c2554

See more details on using hashes here.

File details

Details for the file langchain_x402-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: langchain_x402-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 12.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for langchain_x402-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c6eeaf8c92632471d50991cfe2dbed67408da97d18fb9c201679078b647c6756
MD5 3aafef342812456d2a69e8f9d9b77e54
BLAKE2b-256 ad3a19118745265559bd740539b9088d4df3c5da87b533c17b351771908b93ff

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