import { X402Client } from '@coinbase/x402-sdk';
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor, createReactAgent } from 'langchain/agents';
class AIAgent {
private x402Client: X402Client;
private agent: AgentExecutor;
constructor(privateKey: string, facilitatorURL: string) {
const provider = new ethers.JsonRpcProvider('YOUR_SKALE_RPC_URL');
const wallet = new ethers.Wallet(privateKey, provider);
this.x402Client = new X402Client({
wallet: wallet,
facilitatorURL: facilitatorURL,
});
const paymentTool = {
name: 'make_payment',
description: 'Make an x402 payment to access a paywalled resource',
execute: async (url: string) => {
return await this.accessPaywalledResource(url);
},
};
const llm = new ChatOpenAI({ modelName: 'gpt-4' });
this.agent = createReactAgent({
llm,
tools: [paymentTool],
});
}
async accessPaywalledResource(url: string): Promise<any> {
const response = await fetch(url);
if (response.status === 402) {
const paymentInfo = await response.json();
const payment = await this.x402Client.createPayment(paymentInfo);
await this.x402Client.settle(payment);
const retryResponse = await fetch(url, {
headers: {
'X-PAYMENT': JSON.stringify(payment),
},
});
return await retryResponse.json();
}
return await response.json();
}
async processRequest(userRequest: string): Promise<string> {
const result = await this.agent.invoke({
input: userRequest,
});
return result.output;
}
}