This page provides comprehensive examples of using the ICP Agent Kit with natural language processing and LangChain tools.

Basic Natural Language Commands

Simple Operations

import { ICPAgent } from 'icp-agent-kit';

const agent = new ICPAgent({
  network: 'mainnet',
  openai: { apiKey: process.env.OPENAI_API_KEY }
});
await agent.initialize();

// Check balance
const balance = await agent.processNaturalLanguage(
  "What is my ICP balance?"
);
console.log(balance);
// Output: "Your ICP balance is 25.5 ICP (Account: 60ab9a...)"

// Create identity
const identity = await agent.processNaturalLanguage(
  "Create a new identity called trading"
);
console.log(identity);
// Output: "Successfully created identity 'trading' with principal: tcf25-..."

// Transfer tokens
const transfer = await agent.processNaturalLanguage(
  "Transfer 5 ICP to ryjl3-tyaaa-aaaaa-aaaba-cai"
);
console.log(transfer);
// Output: "Successfully transferred 5 ICP. Transaction ID: 12345..."

Multi-Step Workflows

Identity and Balance Workflow

// Step 1: Create and configure identity
await agent.processNaturalLanguage(
  "Create a new identity from seed phrase"
);

// Step 2: Check the new balance
const balance = await agent.processNaturalLanguage(
  "What's the balance of the identity I just created?"
);

// Step 3: Conditional action
await agent.processNaturalLanguage(
  "If the balance is zero, switch back to my main identity"
);

Canister Deployment Workflow

const devAgent = agent.createAgent('developer');

// Step 1: Plan deployment
const plan = await devAgent.chat(
  "I want to deploy a hello world canister. What are the steps?"
);
console.log(plan);

// Step 2: Create canister
const canister = await devAgent.chat(
  "Create a new canister with 5T cycles for development"
);

// Step 3: Deploy code
const deployment = await devAgent.chat(
  "Deploy my hello_world.wasm to the canister we just created"
);

// Step 4: Verify
const status = await devAgent.chat(
  "Check if the deployment was successful and show the canister status"
);

Agent-Specific Examples

Developer Agent Examples

const devAgent = agent.createAgent('developer');

// Example 1: Debugging deployment issues
await devAgent.chat("My canister deployment is failing with 'insufficient cycles'");
// Response: "The error indicates your canister needs more cycles. Current deployments 
//           typically require at least 1T cycles. Let me check your canister's balance..."

// Example 2: Best practices consultation
await devAgent.chat("What's the recommended canister architecture for a DEX?");
// Response: "For a DEX, I recommend a multi-canister architecture:
//           1. Trading Engine Canister - handles order matching
//           2. Token Registry Canister - manages supported tokens
//           3. User Account Canister - tracks balances..."

// Example 3: Upgrade guidance
await devAgent.chat("How do I safely upgrade my production canister?");
// Response: "For safe production upgrades:
//           1. First, take a snapshot of current state
//           2. Test the upgrade on a staging canister
//           3. Use stable memory for critical data..."

DeFi Agent Examples

const defiAgent = agent.createAgent('defi');

// Example 1: Portfolio management
const portfolio = await defiAgent.chat(
  "Show me a summary of all my token holdings"
);

// Example 2: Batch transfers
await defiAgent.chat(
  "I need to send payments to my team: 10 ICP to Alice, 15 ICP to Bob, 5 ICP to Charlie"
);

// Example 3: Token analysis
await defiAgent.chat(
  "What's the most efficient way to transfer ICRC-1 tokens with minimal fees?"
);

Direct Tool Usage

Using Tools Without Natural Language

import { 
  createGetBalanceTool,
  createCreateCanisterTool,
  transferICPTool 
} from 'icp-agent-kit/tools';

// Create tools
const balanceTool = createGetBalanceTool(agent);
const canisterTool = createCreateCanisterTool(agent);

// Execute tools directly
const balance = await balanceTool.invoke({}, { configurable: { agent } });
const canister = await canisterTool.invoke(
  { cycles: '5T' }, 
  { configurable: { agent } }
);

// Chain tools programmatically
if (parseFloat(balance.result) > 10) {
  await transferICPTool.invoke({
    to: 'savings-account',
    amount: '5',
    memo: 'Monthly savings'
  }, { configurable: { agent } });
}

Complex Scenarios

Automated Canister Monitoring

// Set up monitoring for multiple canisters
const monitoringScript = `
Monitor all my canisters and:
1. Alert me if any canister has less than 1T cycles
2. Automatically top up canisters that fall below 500B cycles
3. Generate a daily report of cycles consumption
`;

const result = await agent.processNaturalLanguage(monitoringScript);

// The agent will:
// - List all controlled canisters
// - Check cycles balances
// - Set up monitoring with the cycles plugin
// - Configure auto top-up rules

Token Distribution System

const defiAgent = agent.createAgent('defi');

// Complex distribution logic
const distribution = await defiAgent.chat(`
I need to distribute 1000 REWARD tokens to these addresses based on their contribution:
- Alice (40%): ${aliceAccount}
- Bob (35%): ${bobAccount}  
- Charlie (25%): ${charlieAccount}

Calculate the exact amounts and execute the transfers.
`);

// The agent will:
// - Calculate token amounts (400, 350, 250)
// - Validate all recipient addresses
// - Execute transfers in sequence
// - Provide transaction summaries

Development Pipeline

const devAgent = agent.createAgent('developer');

// Full deployment pipeline
const pipeline = await devAgent.chat(`
Execute my deployment pipeline:
1. Create a staging canister
2. Deploy the latest build
3. Run smoke tests (call the 'health' method)
4. If tests pass, upgrade the production canister
5. Verify the upgrade was successful
`);

// The agent orchestrates the entire pipeline with error handling

Error Handling Examples

Graceful Error Recovery

try {
  await agent.processNaturalLanguage(
    "Transfer 1000 ICP to an invalid address xyz"
  );
} catch (error) {
  console.log("Error caught:", error.message);
  
  // Ask for clarification
  const clarification = await agent.processNaturalLanguage(
    "The transfer failed. Can you help me validate the recipient address?"
  );
}

Validation Before Execution

// The agent validates before executing
const validation = await agent.processNaturalLanguage(
  "I want to transfer all my ICP to alice. Is this safe?"
);
// Response: "Transferring all your ICP would leave your account empty. 
//           You need to keep some ICP for transaction fees. 
//           Would you like to keep 0.1 ICP for fees?"

Interactive Conversations

Context-Aware Dialog

// Start a conversation
const agent1 = agent.createAgent('general');

// First interaction
await agent1.chat("I'm new to ICP. Where should I start?");
// Response: "Welcome to ICP! I recommend starting with:
//           1. Understanding identities and principals
//           2. Learning about ICP tokens and cycles..."

// Follow-up with context
await agent1.chat("Tell me more about the first point");
// Response: "Identities in ICP are like your blockchain account...
//           [Detailed explanation about identities]"

// Another follow-up
await agent1.chat("Can you show me how to create one?");
// Response: "Of course! Let me create an example identity for you...
//           [Creates identity and shows the process]"

Learning by Doing

const teacher = agent.createAgent('general');

// Interactive learning
await teacher.chat("Teach me about cycles by doing");
// Response: "Let's learn about cycles hands-on! First, let me check 
//           a canister's cycles balance to show you..."

// [Agent executes get_cycles_balance tool]

// "This canister has 5.2T cycles. Cycles are like fuel for computation.
//  Now, let's see how much 1 ICP converts to..."

// [Agent executes pricing check]

// "Currently, 1 ICP = 1.3T cycles. Would you like to try topping up
//  a canister to see how it works?"

Advanced Patterns

Conditional Logic

// Complex conditional operations
const smartTransfer = await agent.processNaturalLanguage(`
Check my ICP balance and:
- If it's over 100 ICP, transfer 20 ICP to my savings
- If it's between 50-100 ICP, transfer 10 ICP
- If it's under 50 ICP, just tell me the balance
`);

Batch Operations with Confirmation

// Batch with safety checks
const batchOps = await agent.processNaturalLanguage(`
I need to:
1. Create 3 new canisters for my microservices
2. Allocate 10T cycles to each
3. Add alice as controller to all of them

Please confirm the total cycles cost before proceeding.
`);
// Response: "This will create 3 canisters with 30T cycles total 
//           (approximately 23 ICP). Proceed? (yes/no)"

Monitoring and Alerts

// Set up intelligent monitoring
const monitoring = await agent.processNaturalLanguage(`
Set up monitoring for my main canister:
- Check cycles every hour
- Alert me on Slack if below 2T cycles
- Auto top-up if below 1T cycles
- Generate weekly usage reports
`);

Integration Examples

Combining Multiple Plugins

// Cross-plugin workflow
const workflow = await agent.processNaturalLanguage(`
For my new project:
1. Create a dedicated identity
2. Transfer 50 ICP to it
3. Create a canister with 20T cycles
4. Deploy my app.wasm
5. Set up cycles monitoring
`);

// The agent coordinates across:
// - Identity plugin (create identity)
// - Token plugin (transfer ICP)
// - Canister plugin (create and deploy)
// - Cycles plugin (monitoring)

Building a DApp Setup Script

const setupScript = `
Set up my new DeFi application:
1. Create identity 'defi-admin'
2. Create 3 canisters: 'token', 'exchange', 'governance'
3. Allocate 10T cycles to each
4. Deploy the respective WASM modules
5. Create initial token supply of 1M tokens
6. Set up monitoring for all canisters
`;

const setup = await agent.processNaturalLanguage(setupScript);

Best Practices Examples

Security-First Approach

// Always validate before major operations
const secureTransfer = await agent.processNaturalLanguage(
  "Before I transfer 100 ICP to this address, can you verify it's valid?"
);

// Use memos for tracking
const trackedTransfer = await agent.processNaturalLanguage(
  "Transfer 5 ICP to alice with memo: 'Invoice #12345'"
);

// Regular security checks
const audit = await agent.processNaturalLanguage(
  "List all identities and their permissions"
);

Performance Optimization

// Batch operations for efficiency
const efficientDeploy = await agent.processNaturalLanguage(
  "Deploy these 5 WASM modules to their respective canisters in parallel"
);

// Optimize cycles usage
const optimization = await agent.processNaturalLanguage(
  "Analyze my canisters' cycles consumption and suggest optimizations"
);

Production Sample Applications

The ICP Agent Kit includes two complete sample applications demonstrating real-world usage:

Decentralized Trading Bot

A complete AI-powered trading bot that demonstrates:
  • Real-time market data integration
  • AI analysis using specialized DeFi agents
  • On-chain trade recording and verification
  • Natural language trading commands
// Example usage from the trading bot
const defiAgent = agent.createAgent('defi');

// AI-powered market analysis
const analysis = await defiAgent.chat(
  "Analyze BTC/USDT for trading opportunities with current market conditions"
);

// Natural language trading
const trade = await agent.processNaturalLanguage(
  "Execute BTC trade based on AI analysis with 2% risk limit"
);

// On-chain verification
const verification = await agent.processNaturalLanguage(
  "Store trading analysis data on persistent storage canister"
);

DAO Voting System

A complete governance system featuring:
  • AI-powered proposal analysis
  • Automated vote casting with reasoning
  • Cryptographic verification
  • Real-time governance metrics
// Example from the DAO voting system
const governanceAgent = agent.createAgent('governance');

// AI proposal analysis
const recommendation = await governanceAgent.chat(
  "Analyze governance proposal PROP-2024-007 for community fund allocation"
);

// Automated voting with AI reasoning
const vote = await agent.processNaturalLanguage(
  "Cast YES vote on proposal PROP-2024-007 based on AI analysis"
);

// Governance metrics
const metrics = await agent.processNaturalLanguage(
  "Show current DAO voting statistics and participation rates"
);
Try the Sample Applications: Visit /sample-applications/ in the repository to run these examples locally and see the natural language interface in action with real blockchain operations.

Next Steps

Now that you’ve seen these examples, try: