|
| 1 | +import { |
| 2 | + AgentKit, |
| 3 | + cdpApiActionProvider, |
| 4 | + cdpWalletActionProvider, |
| 5 | + CdpWalletProvider, |
| 6 | + erc20ActionProvider, |
| 7 | + walletActionProvider, |
| 8 | +} from "@coinbase/agentkit"; |
| 9 | +import { getLangChainTools } from "@coinbase/agentkit-langchain"; |
| 10 | +import { HumanMessage } from "@langchain/core/messages"; |
| 11 | +import { MemorySaver } from "@langchain/langgraph"; |
| 12 | +import { createReactAgent } from "@langchain/langgraph/prebuilt"; |
| 13 | +import { ChatOpenAI } from "@langchain/openai"; |
| 14 | +import { getWalletData, saveWalletData } from "./storage"; |
| 15 | + |
| 16 | +// Define types for agent and configuration |
| 17 | +interface AgentConfig { |
| 18 | + configurable: { |
| 19 | + thread_id: string; |
| 20 | + }; |
| 21 | +} |
| 22 | + |
| 23 | +// Type for the agent |
| 24 | +type Agent = ReturnType<typeof createReactAgent>; |
| 25 | + |
| 26 | +/** |
| 27 | + * Get or create wallet for a user |
| 28 | + */ |
| 29 | +async function getOrCreateWalletForUser(userId: string) { |
| 30 | + const walletDataStr = await getWalletData(userId); |
| 31 | + |
| 32 | + let walletProvider; |
| 33 | + |
| 34 | + // Configure CDP Wallet Provider |
| 35 | + const config = { |
| 36 | + apiKeyName: process.env.CDP_API_KEY_NAME as string, |
| 37 | + apiKeyPrivateKey: process.env.CDP_API_KEY_PRIVATE_KEY?.replace( |
| 38 | + /\\n/g, |
| 39 | + "\n", |
| 40 | + ), |
| 41 | + cdpWalletData: walletDataStr || undefined, |
| 42 | + networkId: process.env.NETWORK_ID || "base-mainnet", |
| 43 | + }; |
| 44 | + |
| 45 | + // Create a new wallet if one doesn't exist |
| 46 | + walletProvider = await CdpWalletProvider.configureWithWallet(config); |
| 47 | + |
| 48 | + if (!walletDataStr) { |
| 49 | + // Export wallet data and save |
| 50 | + const exportedWallet = await walletProvider.exportWallet(); |
| 51 | + await saveWalletData(userId, JSON.stringify(exportedWallet)); |
| 52 | + } |
| 53 | + |
| 54 | + return { walletProvider, config }; |
| 55 | +} |
| 56 | + |
| 57 | +/** |
| 58 | + * Initialize the agent with CDP Agentkit |
| 59 | + * @param userId - The user's identifier (XMTP address) |
| 60 | + * @returns Agent executor and config |
| 61 | + */ |
| 62 | +export async function initializeAgent( |
| 63 | + userId: string, |
| 64 | +): Promise<{ agent: Agent; config: AgentConfig }> { |
| 65 | + try { |
| 66 | + // Initialize LLM |
| 67 | + const llm = new ChatOpenAI({ |
| 68 | + model: "gpt-4o-mini", |
| 69 | + }); |
| 70 | + |
| 71 | + // Get or create wallet provider for the user |
| 72 | + const { walletProvider } = await getOrCreateWalletForUser(userId); |
| 73 | + |
| 74 | + // Initialize AgentKit with payment-focused action providers |
| 75 | + const agentkit = await AgentKit.from({ |
| 76 | + walletProvider, |
| 77 | + actionProviders: [ |
| 78 | + walletActionProvider(), |
| 79 | + erc20ActionProvider(), |
| 80 | + cdpApiActionProvider({ |
| 81 | + apiKeyName: process.env.CDP_API_KEY_NAME as string, |
| 82 | + apiKeyPrivateKey: process.env.CDP_API_KEY_PRIVATE_KEY?.replace( |
| 83 | + /\\n/g, |
| 84 | + "\n", |
| 85 | + ), |
| 86 | + }), |
| 87 | + cdpWalletActionProvider({ |
| 88 | + apiKeyName: process.env.CDP_API_KEY_NAME as string, |
| 89 | + apiKeyPrivateKey: process.env.CDP_API_KEY_PRIVATE_KEY?.replace( |
| 90 | + /\\n/g, |
| 91 | + "\n", |
| 92 | + ), |
| 93 | + }), |
| 94 | + ], |
| 95 | + }); |
| 96 | + |
| 97 | + const tools = await getLangChainTools(agentkit); |
| 98 | + |
| 99 | + // Store buffered conversation history in memory |
| 100 | + const memory = new MemorySaver(); |
| 101 | + const agentConfig: AgentConfig = { |
| 102 | + configurable: { thread_id: `Payment Agent for ${userId}` }, |
| 103 | + }; |
| 104 | + |
| 105 | + // Create React Agent using the LLM and CDP AgentKit tools |
| 106 | + const agent = createReactAgent({ |
| 107 | + llm, |
| 108 | + tools, |
| 109 | + checkpointSaver: memory, |
| 110 | + messageModifier: ` |
| 111 | + You are a DeFi Payment Agent that assists users with sending payments to any wallet address using natural language instructions. |
| 112 | +
|
| 113 | + When a user asks you to make a payment: |
| 114 | + 1. Provide clear information about network fees (if any) and transaction status. |
| 115 | + 2. Notify users of successful transactions with relevant details. |
| 116 | + |
| 117 | + You can only perform payment-related tasks. For other requests, politely explain that you're |
| 118 | + specialized in processing payments and can't assist with other tasks. |
| 119 | +
|
| 120 | + Your default currency is USDC and the token address is 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913. It's gasless on base-mainnet. |
| 121 | + |
| 122 | + If you encounter an error, provide clear troubleshooting advice and offer to retry the transaction. |
| 123 | + |
| 124 | + Before executing your first action, get the wallet balance to see how much funds you have. |
| 125 | + If you don't have enough funds, ask the user to deposit more funds into your wallet and provide them your wallet address. |
| 126 | + |
| 127 | + If there is a 5XX (internal) HTTP error, ask the user to try again later. |
| 128 | + |
| 129 | + Be concise, helpful, and security-focused in all your interactions. |
| 130 | + `, |
| 131 | + }); |
| 132 | + |
| 133 | + // Export and save updated wallet data |
| 134 | + const exportedWallet = await walletProvider.exportWallet(); |
| 135 | + await saveWalletData(userId, JSON.stringify(exportedWallet)); |
| 136 | + |
| 137 | + return { agent, config: agentConfig }; |
| 138 | + } catch (error) { |
| 139 | + console.error("Failed to initialize agent:", error); |
| 140 | + throw error; |
| 141 | + } |
| 142 | +} |
| 143 | + |
| 144 | +/** |
| 145 | + * Process a message with the agent |
| 146 | + * @param agent - The agent executor |
| 147 | + * @param config - Agent configuration |
| 148 | + * @param message - The user message |
| 149 | + * @returns The agent's response |
| 150 | + */ |
| 151 | +export async function processMessage( |
| 152 | + agent: Agent, |
| 153 | + config: AgentConfig, |
| 154 | + message: string, |
| 155 | +): Promise<string> { |
| 156 | + let response = ""; |
| 157 | + |
| 158 | + try { |
| 159 | + const stream = await agent.stream( |
| 160 | + { messages: [new HumanMessage(message)] }, |
| 161 | + config, |
| 162 | + ); |
| 163 | + |
| 164 | + for await (const chunk of stream) { |
| 165 | + if ("agent" in chunk) { |
| 166 | + response += (chunk.agent.messages[0].content as string) + "\n"; |
| 167 | + } else if ("tools" in chunk) { |
| 168 | + // Tool execution messages can be added to the response or handled separately |
| 169 | + // For now, we'll add them to provide transparency |
| 170 | + response += (chunk.tools.messages[0].content as string) + "\n"; |
| 171 | + } |
| 172 | + } |
| 173 | + |
| 174 | + return response.trim(); |
| 175 | + } catch (error) { |
| 176 | + console.error("Error processing message:", error); |
| 177 | + return "Sorry, I encountered an error while processing your request. Please try again later."; |
| 178 | + } |
| 179 | +} |
0 commit comments