💻Initialization & Basic Setup
Project Setup
Refer this link to open up the sample repository. The project setup is as follows -
First, create a new directory and initialize a new npm project:
mkdir cdp-agentkit
cd cdp-agentkit
npm init -y
Install TypeScript as a dev dependency:
npm install typescript --save-dev
Initialize TypeScript configuration:
npx tsc --init
Paste the below
package.json
file in your local repository & install it withnpm install
:
{
"name": "cdp-agentkit",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node chatbot.js",
"build": "tsc",
"dev": "nodemon chatbot.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"@coinbase/cdp-agentkit-core": "^0.0.14",
"@coinbase/cdp-langchain": "^0.0.15",
"@langchain/langgraph": "^0.2.21",
"@langchain/openai": "^0.3.14",
"@langchain/core": "^0.3.19",
"dotenv": "^16.4.5",
"zod": "^3.22.4"
},
"devDependencies": {
"@types/express": "^5.0.0",
"@types/node": "^22.10.10",
"nodemon": "^3.1.9",
"ts-node": "^10.9.2",
"typescript": "^5.7.3"
}
}
Create
.env
file and paste the below keys into it:
CDP_API_KEY_NAME=
CDP_API_KEY_PRIVATE_KEY=
OPENAI_API_KEY=
Create a file called
chatbot.ts
, which we'll be using later on.
API Credentials
Coinbase CDP API Key
Go to CDP Portal.
Generate an API key and save both the key name and private key.
OpenAI API Key
Go to OpenAI Platform (AgentKit is model-agnostic, but we'll use OpenAI for this guide).
Sign up or log in to your account.
Navigate to API keys section.
Create a new API key.
Fund your account with at least $1-2 for testing.
Creating Your First Agent
Create achatbot.ts
file, which contains the logic of your agent:
import { CdpAgentkit } from "@coinbase/cdp-agentkit-core";
import { CdpToolkit } from "@coinbase/cdp-langchain";
import { MemorySaver } from "@langchain/langgraph";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { ChatOpenAI } from "@langchain/openai";
import * as dotenv from "dotenv";
import * as fs from "fs";
dotenv.config();
// Configure a file to persist the agent's CDP MPC Wallet Data
const WALLET_DATA_FILE = "wallet_data.txt";
/**
* Initialize the agent with CDP AgentKit
*
* @returns Agent executor and config
*/
async function initializeAgent() {
// Initialize LLM
const llm = new ChatOpenAI({
model: "gpt-4o-mini",
});
let walletDataStr: string | null = null;
// Read existing wallet data if available
if (fs.existsSync(WALLET_DATA_FILE)) {
try {
walletDataStr = fs.readFileSync(WALLET_DATA_FILE, "utf8");
} catch (error) {
console.error("Error reading wallet data:", error);
// Continue without wallet data
}
}
// Configure CDP AgentKit
const config = {
cdpWalletData: walletDataStr || undefined,
networkId: process.env.NETWORK_ID || "base-sepolia",
};
// Initialize CDP AgentKit
const agentkit = await CdpAgentkit.configureWithWallet(config);
// Initialize CDP AgentKit Toolkit and get tools
const cdpToolkit = new CdpToolkit(agentkit);
const tools = cdpToolkit.getTools();
// Store buffered conversation history in memory
const memory = new MemorySaver();
const agentConfig = { configurable: { thread_id: "CDP AgentKit Chatbot Example!" } };
// Create React Agent using the LLM and CDP AgentKit tools
const agent = createReactAgent({
llm,
tools,
checkpointSaver: memory,
messageModifier:
"You are a helpful agent that can interact onchain using the Coinbase Developer Platform AgentKit...",
});
// Save wallet data
const exportedWallet = await agentkit.exportWallet();
fs.writeFileSync(WALLET_DATA_FILE, exportedWallet);
return { agent, config: agentConfig };
}
Adding Agent Functionality
Extend your agent with chat capabilities. To add more functionality, see the Add Custom Capabilities guide.
import { HumanMessage } from "@langchain/core/messages";
import * as readline from "readline";
/**
* Run the agent interactively based on user input
*
* @param agent - The agent executor
* @param config - Agent configuration
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function runChatMode(agent: any, config: any) {
console.log("Starting chat mode... Type 'exit' to end.");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const question = (prompt: string): Promise<string> =>
new Promise(resolve => rl.question(prompt, resolve));
try {
// eslint-disable-next-line no-constant-condition
while (true) {
const userInput = await question("\nPrompt: ");
if (userInput.toLowerCase() === "exit") {
break;
}
const stream = await agent.stream({ messages: [new HumanMessage(userInput)] }, config);
for await (const chunk of stream) {
if ("agent" in chunk) {
console.log(chunk.agent.messages[0].content);
} else if ("tools" in chunk) {
console.log(chunk.tools.messages[0].content);
}
console.log("-------------------");
}
}
} catch (error) {
if (error instanceof Error) {
console.error("Error:", error.message);
}
process.exit(1);
} finally {
rl.close();
}
}
// Start the agent
if (require.main === module) {
console.log("Starting Agent...");
initializeAgent()
.then(({ agent, config }) => runChatMode(agent, config))
.catch(error => {
console.error("Fatal error:", error);
process.exit(1);
});
}
Last updated