LangChain x402 Integration
LangChain's comprehensive framework combines with x402 protocol to create AI agents that can autonomously purchase data, access premium APIs, and conduct micropayments. With LangChain's robust tools system and x402's sub-2-second settlement, you can build production-ready agents that handle financial transactions intelligently while maintaining security and spending controls.
⚡ x402 Integration Method
Integration Type: Tools Functions
LangChain's Tools system provides seamless x402 integration through custom payment tools with built-in error handling, retry logic, and spending controls for production payment workflows.
Setup Complexity
Maintenance
Documentation
Examples
Installation & Setup
Install the necessary packages to get started with x402 payments in LangChain:
# Install the necessary packages pip install langchain langchain-openai x402-langchain
The x402-langchain package is a helper library that simplifies wrapping facilitators into LangChain-compatible tools, bridging our facilitator ecosystem with your agent framework.
Integration Examples
Autonomous Data Purchase Agent
Build an AI agent that autonomously purchases premium market data using x402 micropayments with spending controls and error handling
from x402_langchain import create_x402_agent
from langchain.chat_models import ChatOpenAI
from langchain.tools import BaseTool
# Configure x402 agent with spending limits
agent = create_x402_agent(
private_key=os.getenv('X402_PRIVATE_KEY'),
llm=ChatOpenAI(model="gpt-4"),
spending_limits={
'daily': 10.0,
'per_transaction': 1.0,
'hourly': 2.0
},
network='polygon'
)
class MarketDataTool(BaseTool):
name = "market_data_purchase"
description = "Purchase real-time market data with x402 payments"
async def _arun(self, symbol: str) -> str:
try:
# Agent automatically handles 402 payment flow
data = await agent.fetch_data(
f"https://api.premium-data.com/stock/{symbol}"
)
return f"Market data for {symbol}: {data['price']}"
except PaymentRequiredError as e:
return f"Payment failed: {e}"
except RateLimitError:
return "Rate limited, try again later"
# Agent can now autonomously purchase data
result = await agent.run(
"Get the latest price for AAPL and analyze the trend"
)Prerequisites:
LangChain installation
x402-langchain package
Circle wallet setup
Polygon RPC access
Multi-Agent Payment Orchestration
Coordinate payments between multiple specialized agents for complex workflow automation
from x402_langchain import AsyncX402Agent
import asyncio
class PaymentOrchestrator:
def __init__(self):
self.data_agent = AsyncX402Agent(
role="data_purchaser",
spending_limit=5.0
)
self.analysis_agent = AsyncX402Agent(
role="compute_purchaser",
spending_limit=3.0
)
async def execute_workflow(self, query):
# Parallel payment execution
tasks = [
self.data_agent.purchase_data(
"https://api.financial-data.com/premium"
),
self.analysis_agent.purchase_compute(
"https://ml-compute.com/analysis"
)
]
try:
data, analysis = await asyncio.gather(*tasks)
return self.synthesize_results(data, analysis)
except Exception as e:
await self.handle_payment_failure(e)
async def handle_payment_failure(self, error):
# Implement fallback payment strategy
if isinstance(error, InsufficientFundsError):
await self.request_budget_increase()
elif isinstance(error, NetworkError):
await self.retry_with_backoff()
orchestrator = PaymentOrchestrator()
result = await orchestrator.execute_workflow(
"Analyze market trends for tech stocks"
)Prerequisites:
Advanced LangChain
Multi-agent patterns
Async programming
Payment error handling
Choosing Your Facilitator
The X402PaymentTool is generic and works with any facilitator that has a compatible client. Here's how you might initialize different clients based on your specific needs:
For Enterprise (CDP)
from x402_facilitators import CDPClient client = CDPClient(api_key="...")
See the CDP Facilitator Guide for details.
For Zero Fees (Mogami)
from x402_facilitators import MogamiClient client = MogamiClient(wallet_pk="...")
See the Mogami Facilitator Guide for details.
For Developer Experience (thirdweb)
from x402_facilitators import ThirdwebClient client = ThirdwebClient(secret_key="...")
See the thirdweb Facilitator Guide for details.
Custom Setup
# Use any facilitator from our hub
from x402_facilitators import CustomClient
client = CustomClient(config={"..."})Browse all 8 facilitators in our hub.
Quick Info
Category
RAG & Knowledge
Primary Language
Python
License
MIT
Latest Version
0.3.13
Community Stats
GitHub Stars
117,000
Weekly Downloads
2,500,000
Community Size
Very Large
Payment-Enabled Use Cases
Autonomous data acquisition agents
Pay-per-use API access systems
Premium content purchasing bots
Real-time market data agents
Computational resource purchasing
Agent-to-agent commerce platforms
Subscription management automation
Micropayment-enabled RAG systems
Strengths
Production-ready payment integration
Comprehensive security controls
Sub-2-second payment settlement
Zero protocol fees (only gas costs)
Supports micropayments from $0.001
Robust error handling and retry logic
Extensive LangChain ecosystem
Strong community and documentation
Limitations
Requires blockchain knowledge
Gas fees for very small payments
Network dependency for payments
Security complexity for key management
Learning curve for payment concepts
Testnet setup required for development
Get the Complete Template
Access a complete, runnable repository with working LangChain x402 integration examples, configuration templates, and step-by-step setup guides.
View on GitHub: LangChain x402 TemplateReady to Build Payment-Enabled Agents?
Get started with our complete LangChain x402 integration template. Includes working examples, facilitator configurations, and production-ready code.
