LangChain Integration
The @shade402/langchain package provides a LangChain tool that enables AI agents to make X402 payments for API access.
Installation
pnpm add @shade402/langchain @shade402/client @shade402/core @langchain/core langchainQuick Start
import { createX402PaymentTool } from '@shade402/langchain';
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
import { Keypair } from '@solana/web3.js';
// Create wallet
const wallet = Keypair.generate();
// Create payment tool
const paymentTool = createX402PaymentTool({
walletKeypair: wallet,
rpcUrl: process.env.SOLANA_RPC_URL,
maxPayment: '1.0',
});
// Create agent
const llm = new ChatOpenAI({ temperature: 0 });
const tools = [paymentTool];
const agent = await createOpenAIFunctionsAgent({ llm, tools, prompt: myPrompt });
const executor = new AgentExecutor({ agent, tools });
// Use agent
const result = await executor.invoke({
input: 'Fetch data from https://api.example.com/premium-data',
});Tool Configuration
Using createX402PaymentTool
createX402PaymentToolUsing X402PaymentTool Class
X402PaymentTool ClassTool Schema
The tool accepts the following parameters:
Tool Behavior
When the agent calls the tool:
Makes HTTP request to the URL
If 402 response received:
Parses payment request
Creates Solana payment transaction
Broadcasts transaction
Retries request with payment authorization
Returns API response as string
Error Handling
The tool handles errors gracefully:
Payment errors: Returns error message with code
Network errors: Returns error message
Validation errors: Returns error message
Errors are returned as strings, allowing the agent to handle them:
Complete Example
Multiple Payment Tools
You can create multiple payment tools with different configurations:
Custom Tool Description
Provide a clear description to help the agent understand when to use the tool:
Production Considerations
Wallet Management
Error Monitoring
Rate Limiting
Consider implementing rate limiting for payment tools:
Best Practices
Set appropriate maximum payment amounts
Provide clear tool descriptions
Monitor payment usage and costs
Handle errors gracefully
Use secure wallet storage
Test with devnet before production
Log payment transactions
Consider rate limiting
Use separate wallets for different agents if needed
Monitor agent behavior and payment patterns
Next Steps
Learn about LangGraph Integration
Check out Examples for more use cases
Review Security best practices
Last updated
