@shade402/langchain
v0.0.1
Published
LangChain.js integration for X402 payment protocol
Maintainers
Readme
@shade402/langchain
LangChain.js integration for X402 payment protocol. Enables AI agents built with LangChain to autonomously make payments for API access.
Overview
The LangChain package provides a payment tool that can be integrated into LangChain agents, allowing them to automatically pay for access to X402-protected APIs. This enables autonomous AI agents to access paid APIs without manual intervention.
Features
- LangChain tool integration for X402 payments
- Automatic payment handling in agent workflows
- Configurable payment limits for safety
- Support for all HTTP methods
- Full TypeScript support
- Seamless integration with LangChain agents
Installation
npm install @shade402/langchain
# or
pnpm add @shade402/langchain
# or
yarn add @shade402/langchainDependencies
@shade402/core: Core X402 protocol implementation@shade402/client: X402 HTTP client@solana/web3.js: Solana wallet operations@langchain/core: LangChain core typeslangchain: LangChain.js frameworkzod: Schema validation
Usage
Basic Setup
import { createX402PaymentTool } from '@shade402/langchain';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
import { ChatOpenAI } from '@langchain/openai';
import { Keypair } from '@solana/web3.js';
// Create wallet for agent
const wallet = Keypair.generate();
// Create payment tool
const paymentTool = createX402PaymentTool({
walletKeypair: wallet,
rpcUrl: 'https://api.devnet.solana.com',
maxPayment: '1.0', // Maximum payment amount in USD
name: 'x402_payment',
description: 'Make a payment to access a paid API endpoint'
});
// Create agent with payment tool
const model = new ChatOpenAI({ temperature: 0 });
const tools = [paymentTool];
const agent = await createOpenAIFunctionsAgent({
llm: model,
tools,
prompt: /* your prompt */
});
const executor = new AgentExecutor({
agent,
tools,
verbose: true
});
// Agent can now use the payment tool
const result = await executor.invoke({
input: 'Fetch data from https://api.example.com/premium-data'
});Advanced Configuration
import { createX402PaymentTool } from '@shade402/langchain';
import { Keypair } from '@solana/web3.js';
const wallet = Keypair.generate();
const paymentTool = createX402PaymentTool({
walletKeypair: wallet,
rpcUrl: process.env.SOLANA_RPC_URL,
maxPayment: '5.0', // Allow up to $5 per payment
name: 'api_payment',
description: 'Pay for API access using X402 protocol. Use this when you need to access a paid API endpoint.',
allowLocal: false // Set to true for localhost in development
});Using the Tool Class
You can also use the class directly for more control:
import { X402PaymentTool } from '@shade402/langchain';
import { Keypair } from '@solana/web3.js';
const wallet = Keypair.generate();
const paymentTool = new X402PaymentTool({
walletKeypair: wallet,
rpcUrl: 'https://api.devnet.solana.com',
maxPayment: '1.0',
name: 'x402_payment',
description: 'Make X402 payment for API access'
});
// Add to agent tools
const tools = [paymentTool];API Reference
createX402PaymentTool
Factory function to create an X402 payment tool for LangChain.
function createX402PaymentTool(
options: X402PaymentToolOptions
): DynamicStructuredToolParameters:
options.walletKeypair: Solana wallet keypair for making paymentsoptions.rpcUrl: Optional Solana RPC URL (default: devnet)options.maxPayment: Maximum payment amount (default: '1.0')options.name: Tool name (default: 'x402_payment')options.description: Tool descriptionoptions.allowLocal: Allow localhost URLs (default: false)
Returns: LangChain DynamicStructuredTool instance
Tool Schema:
url: string - The API endpoint URL to accessmethod: string (optional) - HTTP method (GET, POST, PUT, DELETE), default: 'GET'
X402PaymentTool
Class-based implementation of the payment tool.
class X402PaymentTool extends DynamicStructuredToolConstructor:
new X402PaymentTool(options: X402PaymentToolOptions)Methods:
async execute(url: string, method?: string): Promise<string>- Execute payment and fetch API
Examples
Simple Agent with Payment Tool
import { createX402PaymentTool } from '@shade402/langchain';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
import { ChatOpenAI } from '@langchain/openai';
import { Keypair } from '@solana/web3.js';
import { ChatPromptTemplate } from '@langchain/core/prompts';
const wallet = Keypair.generate();
const paymentTool = createX402PaymentTool({
walletKeypair: wallet,
rpcUrl: 'https://api.devnet.solana.com',
maxPayment: '1.0'
});
const model = new ChatOpenAI({ temperature: 0 });
const prompt = ChatPromptTemplate.fromMessages([
['system', 'You are a helpful assistant that can access paid APIs.'],
['human', '{input}']
]);
const agent = await createOpenAIFunctionsAgent({
llm: model,
tools: [paymentTool],
prompt
});
const executor = new AgentExecutor({
agent,
tools: [paymentTool],
verbose: true
});
const result = await executor.invoke({
input: 'Get the latest data from https://api.example.com/data'
});Agent with Multiple Tools
import { createX402PaymentTool } from '@shade402/langchain';
import { DynamicStructuredTool } from '@langchain/core/tools';
import { z } from 'zod';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
import { ChatOpenAI } from '@langchain/openai';
import { Keypair } from '@solana/web3.js';
const wallet = Keypair.generate();
// Payment tool
const paymentTool = createX402PaymentTool({
walletKeypair: wallet,
maxPayment: '2.0'
});
// Other tools
const searchTool = new DynamicStructuredTool({
name: 'web_search',
description: 'Search the web',
schema: z.object({
query: z.string()
}),
func: async ({ query }) => {
// Your search implementation
return 'Search results...';
}
});
const tools = [paymentTool, searchTool];
const model = new ChatOpenAI({ temperature: 0 });
const agent = await createOpenAIFunctionsAgent({
llm: model,
tools,
prompt: /* your prompt */
});
const executor = new AgentExecutor({ agent, tools });Error Handling
import { createX402PaymentTool } from '@shade402/langchain';
import { Keypair } from '@solana/web3.js';
const wallet = Keypair.generate();
const paymentTool = createX402PaymentTool({
walletKeypair: wallet,
maxPayment: '1.0'
});
// Tool will return error messages as strings
// Agent should handle these in its reasoning
const result = await paymentTool.invoke({
url: 'https://api.example.com/data',
method: 'GET'
});
if (result.startsWith('Payment error:')) {
console.error('Payment failed:', result);
}Production Configuration
import { createX402PaymentTool } from '@shade402/langchain';
import { Keypair } from '@solana/web3.js';
import { readFileSync } from 'fs';
// Load wallet from secure storage
const walletKeypair = Keypair.fromSecretKey(
Buffer.from(JSON.parse(readFileSync('wallet.json', 'utf-8')))
);
const paymentTool = createX402PaymentTool({
walletKeypair,
rpcUrl: process.env.SOLANA_MAINNET_RPC_URL,
maxPayment: '10.0', // Higher limit for production
name: 'x402_payment',
description: 'Pay for API access. Only use when explicitly needed.',
allowLocal: false
});Tool Behavior
The payment tool automatically:
- Detects when a 402 Payment Required response is received
- Parses the payment request
- Creates and broadcasts the payment transaction
- Retries the original request with payment authorization
- Returns the API response data
If payment fails, the tool returns an error message that the agent can use in its reasoning.
Integration Tips
Prompt Engineering
Include instructions about when to use the payment tool:
You have access to a payment tool for accessing paid APIs. Use it only when:
1. The API explicitly requires payment
2. The payment amount is reasonable
3. You have been instructed to access the paid APIPayment Limits
Set appropriate maxPayment limits based on your use case:
- Development: $0.10 - $1.00
- Testing: $1.00 - $5.00
- Production: Based on your budget and use case
Wallet Management
- Store wallet keys securely (environment variables, key management service)
- Use separate wallets for different agents if needed
- Monitor wallet balances
- Set up alerts for low balances
Security Considerations
- Never expose wallet private keys in client-side code
- Use environment variables for sensitive configuration
- Set appropriate
maxPaymentlimits to prevent excessive payments - Monitor agent behavior and payment patterns
- Use mainnet RPC endpoints for production
- Keep wallet keys secure and rotate them regularly
- Set
allowLocal: falsein production
TypeScript Support
The package is written in TypeScript and provides full type definitions:
import type {
X402PaymentToolOptions
} from '@shade402/langchain';License
MIT
