12 min read
Overview
Coinbase’s AgentKit is a powerful tool for building autonomous AI agents that can interact with blockchain networks, perform tasks, and engage with users on social media platforms. This guide will walk you through the process of creating a simple AI agent that can manage wallets, deploy tokens, and interact with users on Twitter (X).
What You Will Do
- Build an autonomous AI agent that can interact with Base blockchain using AgentKit
- Add a Twitter (X) integration to the agent to interact with users
- Test the agent on the Base network
What You Will Need
- A QuickNode account
- Development Tools
- Node.js (>=20.x), TypeScript, and a code editor (e.g., VS Code)
- API Keys
- Coinbase CDP API credentials
- Twitter API (Developer account) keys
- An LLM (OpenAI, Claude, etc.) API key
- Familiarity with JavaScript/TypeScript basics, blockchain fundamentals, and AI tools
What is Coinbase AgentKit?
AgentKit is Coinbase’s toolkit for integrating AI agents with blockchain functionality. It serves as the bridge between large language models (LLMs) such as ChatGPT, and blockchain operations, enabling agents to:
- Manage wallets and perform transactions
- Deploy tokens, mint NFTs, trade tokens, and interact with smart contracts
- Operate autonomously or in response to specific inputs
- Plugs into any AI agent framework
- Support for LangChain and any existing LangChain tools
AI Agent Architecture
The AI Agent is built on three main components: blockchain operations, AI decision-making, and user interactions.
At its core, it uses Coinbase's AgentKit to handle all blockchain operations (like deploying tokens or managing wallets) through the CDP SDK. This core functionality is enhanced by an AI layer powered by LLMs that makes decisions about what actions to take.
What makes our implementation special is the custom Twitter (X) integration we've added. While AgentKit provides the default blockchain tools, we've extended the system with a custom Twitter tool that allows the agent to interact with users through social media.
The agent can run in three modes: autonomous (making its own decisions), interactive (responding to direct commands), and Twitter mode (our custom addition that responds to social media interactions). We will focus on the autonomous and Twitter modes in this guide.
All these components are orchestrated by our BaseAIAgent
class in the codebase, which acts as the central controller, coordinating between user inputs, AI decisions, and blockchain operations. This modular design means you can easily add your own custom tools or modify existing functionality without disrupting the core system.
How to Set Up Your Web3 AI Agent
1. Install the Coinbase AI AgentKit Add-On
Installing add-ons such as Coinbase AI AgentKit on QuickNode is simple and straightforward. If you haven't signed up already, you can create an account here. If you haven't created an endpoint yet, you can do so by selecting the Create Endpoint button after clicking the Create button on the top left corner.
After, navigate to the Marketplace tab on the dashboard and select the Coinbase AI AgentKit add-on. Click on the Explore button and then click on the Install button to add the add-on to your account.
2. Clone the Repository and Install Dependencies
We have a pre-built sample project in our repository, so you just need to clone it and set up the environment.
git clone https://github.com/quiknode-labs/qn-guide-examples.git
cd ai/coinbase-ai-agent
npm install
3. Configure API Keys
Before running the agent, you need to set up your environment variables. The project uses an .env
file for configuration.
Copy the example environment file:
cp .env.example .env
Then, open .env
and add the required credentials.
Getting Coinbase CDP API Key
Coinbase’s CDP API allows the AI agent to perform blockchain operations on the Base network.
- Visit the CDP Portal.
- Create an account if you don’t have one.
- Generate an API key and save both the key name and private key.
- Add the following details to your
.env
file:
CDP_API_KEY_NAME="your-cdp-api-key-name"
CDP_API_KEY_PRIVATE_KEY="your-cdp-api-key-private-key"
For additional details, refer to Coinbase’s CDP documentation.
Getting Twitter (X) API Keys and Access Tokens
To enable social interaction, the AI agent needs access to the Twitter (X) API.
- Create a Twitter Developer Account and register an app.
- Obtain API Keys and Tokens:
- Go to the app dashboard and navigate to the Keys and Tokens section.
- Copy the API Key, API Secret, Access Token, and Access Token Secret.
- Edit the App’s Permissions:
- Go to the Settings tab of your app.
- Find User authentication settings and click Edit.
- Under App permissions, choose Read and Write (or Read, Write, and Direct Messages if needed).
- Ensure your Access Token and Access Token Secret have Read-Write permissions.
- Get Your User ID:
- Use X's User Lookup method or a 3rd party website to get your bot's user ID.
Add them to your .env
file:
TWITTER_API_KEY="your-twitter-api-key"
TWITTER_API_SECRET="your-twitter-api-secret"
TWITTER_ACCESS_TOKEN="your-twitter-access-token"
TWITTER_ACCESS_SECRET="your-twitter-access-secret"
TWITTER_USER_ID="your-twitter-user-id"
For further details, refer to X's API documentation.
Getting OpenAI API Key
The AI agent uses OpenAI (or another LLM) for intelligent responses and decision-making.
- Visit OpenAI API Keys.
- Add some balances to your account if you don't have.
- Generate an API key.
- Add it to your
.env
file:
OPENAI_API_KEY="your-openai-api-key"
If you’re using a different LLM, update the API key accordingly.
4. Understanding the Codebase
Before running the agent, let’s explore the codebase to understand how the AI agent works.
The agent.ts
file serves as the core logic for the AI Agent. This section provides an overview of its functionality and key components.
The BaseAIAgent
class is responsible for:
- Managing blockchain interactions via Coinbase’s CDP AgentKit
- Processing AI-driven responses using LangChain and OpenAI
- Handling Twitter interactions, including responding to mentions and posting tweets
- Managing wallet data, ensuring transactions and operations persist across sessions
Initialization and Configuration
- Loads required libraries for blockchain, AI, and Twitter interactions.
- Reads environment variables for API keys.
- Loads saved wallet data to persist blockchain state.
- If wallet data exists, the agent restores its state.
- If no wallet data exists, it creates a new wallet.
// Rest of the code
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
}
}
// Rest of the code
// Save wallet data
const exportedWallet = await this.agentkit.exportWallet();
fs.writeFileSync(WALLET_DATA_FILE, exportedWallet);
// Rest of the code
Twitter API Integration
- Handles authentication using API keys.
- Interacts with users by monitoring tweets and posting responses.
this.twitterClient = new TwitterApi({
appKey: process.env.TWITTER_API_KEY!,
appSecret: process.env.TWITTER_API_SECRET!,
accessToken: process.env.TWITTER_ACCESS_TOKEN!,
accessSecret: process.env.TWITTER_ACCESS_SECRET!,
});
Blockchain Operations with CDP AgentKit
- The agent is configured to run on Base Sepolia.
- Uses Coinbase’s CDP SDK to perform blockchain tasks.
const config = {
networkId: "base-sepolia",
cdpWalletData: walletDataStr || undefined,
};
this.agentkit = await CdpAgentkit.configureWithWallet(config);
AI-Powered Processing
- Uses OpenAI (GPT-4o) to analyze tweets and determine appropriate responses.
- LangChain ReAct Agent processes inputs and decides on blockchain actions.
const llm = new ChatOpenAI({
openAIApiKey: process.env.OPENAI_API_KEY!,
modelName: "gpt-4o-mini",
});
Handling Twitter Mentions
checkMentions
function monitors Twitter mentions and extracts relevant tweets.- AI analyzes the tweet, determines an action, and replies appropriately.
- Uses the Twitter API to post a response and engage with users.
private async checkMentions() {
try {
// Get recent mentions using search API
const mentions = await this.twitterClient.v2.userMentionTimeline(
process.env.TWITTER_USER_ID!, // Your bot's user ID
{
"tweet.fields": ["author_id", "referenced_tweets"],
expansions: ["author_id"],
max_results: 10,
...(this.lastProcessedMentionId && {
since_id: this.lastProcessedMentionId,
}),
}
);
// console.log("Mentions:", mentions);
// Check if mentions exists and has tweets
if (mentions && Array.isArray(mentions.tweets)) {
for (const tweet of mentions.tweets) {
// Skip if it's a retweet
const isRetweet = tweet.referenced_tweets?.some(
(ref: { type: string }) => ref.type === "retweet"
);
if (isRetweet) continue;
const author = mentions.includes?.users?.find(
(user: { id: string }) => user.id === tweet.author_id
);
if (author) {
// Pass tweet ID to handleTweet
await this.handleTweet(tweet.text, author.username, tweet.id);
// Add small delay between processing mentions to avoid rate limits
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
}
} catch (error) {
console.error("Error checking mentions:", error);
}
}
Autonomous Mode (runAutonomousMode)
- Periodically posts tweets with useful insights.
- Uses a weighted random selection of prompts (educational, community engagement, blockchain-related actions).
- If needed, executes blockchain transactions (like deploying tokens).
async runAutonomousMode(interval = 3600) {
while (true) {
try {
const thought = await this.generateAutonomousAction();
const stream = await this.agent.stream(
{
messages: [
new HumanMessage(
`Create an engaging tweet based on this prompt: ${thought}\n\n` +
`Guidelines:\n` +
`- Focus on providing value through information and engagement\n` +
`- Only perform on-chain actions if explicitly prompted\n` +
`- Keep tweets concise and friendly\n` +
`- Use emojis appropriately\n` +
`- Include hashtags like #Base #Web3 when relevant\n` +
`When ready, use the send_tweet tool to share your message.`
),
],
},
this.agentConfig
);
for await (const chunk of stream) {
if ("agent" in chunk) {
console.log("Autonomous action:", chunk.agent.messages[0].content);
} else if ("tools" in chunk) {
console.log("Tool execution:", chunk.tools.messages[0].content);
}
}
await new Promise((resolve) => setTimeout(resolve, interval * 1000));
} catch (error) {
console.error("Error in autonomous mode:", error);
await new Promise((resolve) => setTimeout(resolve, 60 * 1000));
}
}
}
Monitoring Twitter Mentions (pollMentions)
- Runs in the background, checking Twitter every 20 minutes for new mentions.
- Uses
checkMentions()
to process tweets and trigger responses.
async pollMentions(interval = 1200) {
// Check every 20 minutes
console.log("Started polling for mentions...");
while (true) {
await this.checkMentions();
await new Promise((resolve) => setTimeout(resolve, interval * 1000));
}
}
5. Running Tests
To ensure the Twitter integration work correctly, you can run the tests:
npm run test
This test does not cover all functionalities but ensures the Twitter integration is working as expected. If you plan to use this code in production, we suggest creating more tests to ensure full coverage.
6. Retrieve ETH from QuickNode Multi-Chain Faucet
In order to interact with the Base testnet, your AI agent will need to have some test ETH on the network.
Coinbase's AgentKit has an ability to get some test ETH from the Coinbase's faucet automatically, but if you want to need more, you can use the QuickNode Multi-Chain Faucet and then transfer it to your agent's wallet. Note that there is a mainnet balance requirement of 0.001 ETH on Ethereum Mainnet to use the EVM faucets. You can also tweet or login with your QuickNode account to get a bonus!
7. Running the AI Agent
The agent can run in multiple modes based on how it should operate.
Autonomous Mode (Fully Automated Blockchain & Twitter Bot)
This mode allows the agent to periodically tweet, monitor blockchain events, and perform transactions automatically.
npm run start:autonomous
Twitter Mode (Monitoring and Responding to Mentions)
This mode listens for Twitter mentions and engages with users.
npm run start:mentions
Interactive Mode (Command-Line Controlled)
This mode allows you to interact with the agent via the command line. However, we don't cover this mode in this guide.
8. Testing the Agent on Twitter
Once the agent is running, you can test its functionality by tweeting at the agent's Twitter handle. The agent should respond to your tweets based on its AI decision-making logic.
Make sure that the agent is running in Twitter mode (npm run start:mentions
) to receive and respond to tweets.
You can see our test tweet, response, and the blockchain operation the agent performed below:
- Tweet:
@MyQuickAgent How are you mate? If you can, can you send some USDC to 0xsergen.eth
- Response:
@0xsergen Hey! Just sent you 1 USDC. Enjoy! 🚀
- Blockchain Operation:
Sent 1 USDC to 0xsergen.eth
Next Steps
At this point, your blockchain AI agent should be operational. You can now:
- Expand AI Capabilities – Enhance the agent’s responses by fine-tuning its AI logic using LangChain and custom prompts. See Coinbase's Add Agent Capabilities documentation for more details.
- Deploy to Production – Run the agent on a cloud server or serverless infrastructure to keep it running 24/7.
- Improve Twitter (X) Engagement – Implement advanced sentiment analysis to tailor responses based on user emotions.
- Multi-Platform Expansion – Extend the agent’s capabilities beyond Twitter to Discord, Telegram, or Web3 dApps.
Conclusion
In this guide, you built a Web3 AI Agent that seamlessly integrates Coinbase’s CDP SDK, AI-powered decision-making, and real-time Twitter interactions. This project demonstrates how AI and blockchain can work together to create autonomous agents that operate intelligently and efficiently in Web3.
The possibilities for expanding this project are endless. Now it’s time to iterate, innovate, and push the boundaries of what’s possible in AI-powered blockchain automation.
If you need help or want to share what you are building, let us know on Discord or Twitter.
Additional Resources
Here are some helpful links to expand your knowledge and explore more related content:
- QuickNode Docs
- QuickNode AI Guides
- CDP (Coinbase Developer Platform) API
- Twitter (X) API Documentation
We ❤️ Feedback!
Let us know if you have any feedback or requests for new topics. We'd love to hear from you.