AI Agent Integration

Shade402 provides integrations for popular AI agent frameworks, enabling autonomous agents to make payments for API access automatically.

Supported Frameworks

  • LangChain.js: Payment tool for LangChain agents

  • LangGraph.js: Payment nodes for LangGraph workflows

LangChain Integration

The @shade402/langchain package provides a payment tool that agents can use to access paid APIs.

Installation

pnpm add @shade402/langchain @shade402/client @shade402/core

Basic Usage

import { createX402PaymentTool } from '@shade402/langchain';
import { Keypair } from '@solana/web3.js';
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';

// Create wallet
const wallet = Keypair.generate();

// Create payment tool
const paymentTool = createX402PaymentTool({
  walletKeypair: wallet,
  rpcUrl: process.env.SOLANA_RPC_URL,
  maxPayment: '1.0', // Maximum payment per request
  name: 'x402_payment',
  description: 'Make an X402 payment to access a paid API endpoint',
});

// Create agent with payment tool
const llm = new ChatOpenAI({ temperature: 0 });
const tools = [paymentTool];

const agent = await createOpenAIFunctionsAgent({
  llm,
  tools,
  prompt: myPrompt,
});

const executor = new AgentExecutor({
  agent,
  tools,
});

// Agent can now use the payment tool
const result = await executor.invoke({
  input: 'Fetch data from https://api.example.com/premium-data',
});

Tool Configuration

interface X402PaymentToolOptions {
  walletKeypair: Keypair;           // Wallet for payments
  rpcUrl?: string;                  // Solana RPC URL
  maxPayment?: string;              // Maximum payment amount (default: '1.0')
  name?: string;                    // Tool name (default: 'x402_payment')
  description?: string;             // Tool description
  allowLocal?: boolean;             // Allow localhost URLs (development)
}

Tool Usage

The agent will use the tool when it needs to access a paid API:

// Agent decides to use the tool
const result = await executor.invoke({
  input: 'Get premium analysis from https://api.example.com/analyze',
});

// Tool automatically:
// 1. Makes request to URL
// 2. Receives 402 response
// 3. Creates payment
// 4. Retries with payment
// 5. Returns API response

LangGraph Integration

The @shade402/langgraph package provides payment nodes for LangGraph workflows.

Installation

pnpm add @shade402/langgraph @shade402/client @shade402/core @langchain/langgraph

Basic Usage

import { StateGraph } from '@langchain/langgraph';
import { paymentNode, fetchWithPaymentNode, checkPaymentRequired } from '@shade402/langgraph';
import { Keypair } from '@solana/web3.js';
import { PaymentState } from '@shade402/langgraph';

// Define state
interface MyState extends PaymentState {
  api_url: string;
  api_response?: string;
  wallet_keypair: Keypair;
}

// Create workflow
const workflow = new StateGraph<MyState>({
  channels: {
    api_url: { reducer: (x, y) => y ?? x },
    api_response: { reducer: (x, y) => y ?? x },
    wallet_keypair: { reducer: (x, y) => y ?? x },
  },
});

// Add nodes
workflow.addNode('fetch_api', fetchWithPaymentNode);
workflow.addNode('process_response', async (state: MyState) => {
  return {
    ...state,
    result: JSON.parse(state.api_response || '{}'),
  };
});

// Add edges
workflow.setEntryPoint('fetch_api');
workflow.addEdge('fetch_api', 'process_response');

// Compile and run
const app = workflow.compile();

const result = await app.invoke({
  api_url: 'https://api.example.com/premium-data',
  wallet_keypair: Keypair.generate(),
  max_payment_amount: '1.0',
});

Payment Nodes

fetchWithPaymentNode

Combined node that fetches API and handles payment automatically:

import { fetchWithPaymentNode } from '@shade402/langgraph';

workflow.addNode('fetch_api', fetchWithPaymentNode);

paymentNode

Separate payment node for more control:

import { paymentNode, checkPaymentRequired } from '@shade402/langgraph';

workflow.addNode('fetch_api', async (state: PaymentState) => {
  // Make initial request
  // ...
  return { ...state, payment_required: true };
});

workflow.addNode('make_payment', paymentNode);

workflow.addConditionalEdges(
  'fetch_api',
  checkPaymentRequired,
  {
    payment_required: 'make_payment',
    success: 'process_response',
  }
);

Conditional Edges

Use conditional functions to route based on payment status:

import { checkPaymentRequired, checkPaymentCompleted } from '@shade402/langgraph';

// Check if payment required
workflow.addConditionalEdges(
  'fetch_api',
  checkPaymentRequired,
  {
    payment_required: 'make_payment',
    success: 'process_response',
    error: 'error_handler',
  }
);

// Check if payment completed
workflow.addConditionalEdges(
  'make_payment',
  checkPaymentCompleted,
  {
    completed: 'process_response',
    failed: 'error_handler',
  }
);

State Interface

The PaymentState interface includes:

interface PaymentState {
  wallet_keypair?: Keypair;
  api_url?: string;
  api_response?: string;
  payment_completed?: boolean;
  payment_error?: string | null;
  payment_required?: boolean;
  max_payment_amount?: string;
  http_method?: string;
  allow_local?: boolean;
  rpc_url?: string;
  [key: string]: any;
}

Complete Examples

LangChain Agent with Payment Tool

import { createX402PaymentTool } from '@shade402/langchain';
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
import { Keypair } from '@solana/web3.js';

const wallet = Keypair.fromSecretKey(
  Buffer.from(process.env.WALLET_SECRET_KEY!, 'base64')
);

const paymentTool = createX402PaymentTool({
  walletKeypair: wallet,
  rpcUrl: process.env.SOLANA_RPC_URL,
  maxPayment: '1.0',
});

const llm = new ChatOpenAI({ temperature: 0 });
const tools = [paymentTool];

const agent = await createOpenAIFunctionsAgent({
  llm,
  tools,
  prompt: myPrompt,
});

const executor = new AgentExecutor({
  agent,
  tools,
  verbose: true,
});

const result = await executor.invoke({
  input: 'Fetch premium data from https://api.example.com/data and analyze it',
});

console.log(result.output);

LangGraph Workflow with Payment

import { StateGraph } from '@langchain/langgraph';
import { fetchWithPaymentNode } from '@shade402/langgraph';
import { Keypair } from '@solana/web3.js';
import { PaymentState } from '@shade402/langgraph';

const workflow = new StateGraph<PaymentState>({
  channels: {
    api_url: { reducer: (x, y) => y ?? x },
    api_response: { reducer: (x, y) => y ?? x },
    wallet_keypair: { reducer: (x, y) => y ?? x },
    max_payment_amount: { reducer: (x, y) => y ?? x },
  },
});

workflow.addNode('fetch_api', fetchWithPaymentNode);
workflow.addNode('process', async (state: PaymentState) => {
  const data = JSON.parse(state.api_response || '{}');
  return {
    ...state,
    processed: data,
  };
});

workflow.setEntryPoint('fetch_api');
workflow.addEdge('fetch_api', 'process');

const app = workflow.compile();

const wallet = Keypair.generate();
const result = await app.invoke({
  api_url: 'https://api.example.com/premium-data',
  wallet_keypair: wallet,
  max_payment_amount: '1.0',
  rpc_url: process.env.SOLANA_RPC_URL,
});

console.log(result.processed);

Best Practices

  1. Set maximum payment amounts to prevent overpayment

  2. Monitor payment usage and costs

  3. Handle payment errors gracefully

  4. Use appropriate wallet management for production

  5. Test with devnet before production

  6. Log payment transactions for audit

  7. Consider rate limiting for payment tools

  8. Use separate wallets for different agents if needed

Next Steps

Last updated