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 langchain

Quick 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

Using X402PaymentTool Class

Tool Schema

The tool accepts the following parameters:

Tool Behavior

When the agent calls the tool:

  1. Makes HTTP request to the URL

  2. If 402 response received:

    • Parses payment request

    • Creates Solana payment transaction

    • Broadcasts transaction

    • Retries request with payment authorization

  3. 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

  1. Set appropriate maximum payment amounts

  2. Provide clear tool descriptions

  3. Monitor payment usage and costs

  4. Handle errors gracefully

  5. Use secure wallet storage

  6. Test with devnet before production

  7. Log payment transactions

  8. Consider rate limiting

  9. Use separate wallets for different agents if needed

  10. Monitor agent behavior and payment patterns

Next Steps

Last updated