Skip to content

Coinbase AgentKit + AiMo Integration

Overview

This guide walks you through integrating Coinbase AgentKit into your Next.js on-chain agent application.

Example Repository: https://github.com/AIMOverse/base-agent-kit-example

You will:

  1. Scaffold a new Next.js project with AgentKit.
  2. Collect required API credentials.
  3. Configure environment variables.
  4. Instantiate an agent with AgentKit and AIMO API.
  5. Run the development server.

Prerequisites

  • Node.js 18+ (recommended LTS)
  • pnpm installed
  • A Coinbase Developer Platform (CDP) account
  • Access to create API keys and a Smart Wallet (or Wallet-as-a-Service credentials)
  • An AIMO API key for LLM routing via the AIMO network

1. Scaffold the Next.js Project

Run the official AgentKit initializer:

pnpm create onchain-agent@latest

Follow the interactive prompts and select Next.js as your framework. After completion, cd into the generated directory.

2. Collect Required API Keys

You'll need the following secrets before continuing:

KeyDescriptionWhere to Get It
AIMO_API_KEYAimo platform key for LLM routingAimo dashboard
CDP_API_KEYCoinbase Developer Platform keyCDP dashboard
CDP_API_SECRETSecret corresponding to the CDP API keyShown once at creation
NETWORK_IDNetwork to deploy on (e.g., base-sepolia)Configuration choice

Security notes:

  • Never commit secrets to git.
  • Prefer .env.local and secret managers in production.
  • Rotate keys regularly.

3. Project Structure (Next.js)

After scaffolding a Next.js project, you'll have:

.
├─ app/
│  ├─ api/
│  │  └─ agent/
│  │     ├─ create-agent.ts
│  │     ├─ prepare-agentkit.ts
│  │     └─ route.ts
│  ├─ page.tsx
│  └─ layout.tsx
├─ public/
├─ package.json
├─ .env.local
├─ next.config.js
└─ pnpm-lock.yaml

The agent configuration lives in app/api/agent/create-agent.ts.

4. Configure Environment Variables

Create a .env.local file in the project root:

# AIMO Network API
AIMO_API_KEY=your_aimo_key_here
 
# Coinbase Developer Platform
CDP_API_KEY=your_cdp_key
CDP_API_SECRET=your_cdp_secret
 
# Network configuration
NETWORK_ID=base-sepolia
 
# Runtime config
NODE_ENV=development

Add an .env.example (without real secrets) to help collaborators:

AIMO_API_KEY=
CDP_API_KEY=
CDP_API_SECRET=
NETWORK_ID=base-sepolia
NODE_ENV=development

5. Configure the Agent with AIMO API

The core agent configuration happens in app/api/agent/create-agent.ts. This file uses the Vercel AI SDK with AIMO's OpenAI-compatible API:

// app/api/agent/create-agent.ts
import { createOpenAI } from "@ai-sdk/openai";
import { getVercelAITools } from "@coinbase/agentkit-vercel-ai-sdk";
import { prepareAgentkitAndWalletProvider } from "./prepare-agentkit";
 
/**
 * Agent Configuration Guide
 *
 * This file handles the core configuration of your AI agent's behavior and capabilities.
 *
 * Key Steps to Customize Your Agent:
 *
 * 1. Select your LLM:
 *    - Modify the `openai` instantiation to choose your preferred LLM
 *    - Configure model parameters like temperature and max tokens
 *
 * 2. Instantiate your Agent:
 *    - Pass the LLM, tools, and memory into the agent configuration
 *    - Configure agent-specific parameters
 */
 
// Configure OpenAI-compatible client for AIMO API
const openai = createOpenAI({
  apiKey: process.env.AIMO_API_KEY,
  baseURL: "https://devnet.aimo.network/api/v1"
});
 
// The agent configuration type
type Agent = {
  tools: ReturnType<typeof getVercelAITools>;
  system: string;
  model: ReturnType<typeof openai>;
  maxSteps?: number;
};
let agent: Agent;
 
/**
 * Initializes and returns an instance of the AI agent.
 * If an agent instance already exists, it returns the existing one.
 *
 * @function createAgent
 * @returns {Promise<Agent>} The initialized AI agent configuration.
 *
 * @description Handles agent setup with AIMO API and AgentKit tools
 *
 * @throws {Error} If the agent initialization fails.
 */
export async function createAgent(): Promise<Agent> {
  // If agent has already been initialized, return it
  if (agent) {
    return agent;
  }
 
  if (!process.env.AIMO_API_KEY) {
    throw new Error("I need an AIMO_API_KEY in your .env.local file to power my intelligence.");
  }
 
  const { agentkit, walletProvider } = await prepareAgentkitAndWalletProvider();
 
  try {
    // Initialize LLM via AIMO network
    // Format: model_id:model_name
    const model = openai("HjRMtkc54ZNgq2PGCsiuhR1z4WR2YDTfA4PfW1GHXbLh:kimi-k2-0711-preview");
 
    // Initialize Agent system prompt
    const canUseFaucet = walletProvider.getNetwork().networkId == "base-sepolia";
    const faucetMessage = `If you ever need funds, you can request them from the faucet.`;
    const cantUseFaucetMessage = `If you need funds, you can provide your wallet details and request funds from the user.`;
 
    const system = `
        You are a helpful agent that can interact onchain using the Coinbase Developer Platform AgentKit. You are
        empowered to interact onchain using your tools. ${canUseFaucet ? faucetMessage : cantUseFaucetMessage}.
        Before executing your first action, get the wallet details to see what network
        you're on. If there is a 5XX (internal) HTTP error code, ask the user to try again later. If someone
        asks you to do something you can't do with your currently available tools, you must say so, and
        explain that they can add more capabilities by adding more action providers to your AgentKit configuration.
        ALWAYS include this link when mentioning missing capabilities, which will help them discover available action providers: https://github.com/coinbase/agentkit/tree/main/typescript/agentkit#action-providers
        If users require more information regarding CDP or AgentKit, recommend they visit docs.cdp.coinbase.com for more information.
        Be concise and helpful with your responses. Refrain from restating your tools' descriptions unless it is explicitly requested.
        `;
 
    // Get AgentKit tools for Vercel AI SDK
    const tools = getVercelAITools(agentkit);
 
    agent = {
      tools,
      system,
      model,
      maxSteps: 10,
    };
 
    return agent;
  } catch (error) {
    console.error("Error initializing agent:", error);
    throw new Error("Failed to initialize agent");
  }
}

Key Configuration Points

  1. OpenAI-Compatible API Setup: The createOpenAI function is configured to use AIMO's API endpoint as a drop-in replacement for OpenAI
  2. Environment Variable: Uses AIMO_API_KEY instead of OPENAI_API_KEY
  3. Model Format: AIMO uses a model_id:model_name format for model selection
  4. Base URL: Points to https://devnet.aimo.network/api/v1 for the AIMO devnet

6. Install Dependencies

If not already installed by the scaffold:

pnpm install

7. Run the Next.js Development Server

pnpm dev

The application will be available at http://localhost:3000.

8. Test the Agent

Open your browser and navigate to http://localhost:3000. You can interact with the agent through the web interface.

Example interactions:

  • "What is my wallet address?"
  • "What network am I on?"
  • "Check my wallet balance"

Expected behavior:

  • The agent initializes with AIMO API connection
  • AgentKit tools are available for on-chain interactions
  • Responses are generated via the AIMO network

9. Understanding AgentKit Tools

AgentKit provides built-in tools via getVercelAITools(agentkit) that enable on-chain operations:

  • Wallet operations: Get address, check balances
  • Token transfers: Send tokens to addresses
  • Network queries: Check network status and details
  • Smart contract interactions: Deploy and interact with contracts

These tools are automatically configured when you call prepareAgentkitAndWalletProvider() and are available to the agent based on your CDP credentials and wallet configuration.

10. Troubleshooting

IssueLikely CauseRemedy
Missing required env var errorNot set in .env.localAdd key and restart
Unauthorized (401) from CDPWrong API key/secretRegenerate in CDP dashboard
Unauthorized (401) from AIMOWrong AIMO API keyCheck AIMO dashboard
Wallet signing failureInvalid private key formatEnsure hex string without whitespace
Tool not foundTool not properly registeredConfirm AgentKit initialization
Slow responsesLLM latency or network issuesEnable streaming / check network
5XX errors from AIMOAIMO service issuesRetry later or contact support

11. Security Best Practices

  • Never log full secrets—mask them in logs
  • Use secret managers (AWS Secrets Manager, Vault, Vercel Environment Variables) in staging/production
  • Set strict IAM scopes on CDP keys
  • Consider rate limiting and circuit breakers for LLM calls
  • Add request tracing (e.g., OpenTelemetry) for observability
  • Rotate API keys regularly
  • Use .env.local for local development (automatically ignored by git)

12. Next Steps

  • Add persistence (conversation memory store)
  • Add more on-chain tools (transfer, balance check, swap)
  • Integrate cost tracking per interaction
  • Implement evaluation harness for agent reliability
  • Deploy to production (Vercel, Railway, etc.)
  • Add monitoring and alerting

Quick Reference

# Scaffold
pnpm create onchain-agent@latest
 
# Configure environment
cp .env.example .env.local
# Fill in required keys
 
# Install dependencies
pnpm install
 
# Run development server
pnpm dev
 
# Build for production
pnpm build
 
# Start production server
pnpm start

Additional Resources