Production-ready SDK for building autonomous AI agents on Somnia blockchain
Complete toolkit for building AI agents on blockchain - combines AI reasoning, smart contracts, autonomous runtime, and real-time monitoring.
π Full Documentation on GitBook - Complete guides, tutorials, examples, and API reference
π¦ npm Package - Install and use the SDK
Key Features: Autonomous Agents β’ Smart Contracts β’ LLM Integration β’ Token Management β’ Multicall Batching β’ Monitoring β’ CLI Tools
# Install
npm install somnia-agent-kit
# Or install globally for CLI
npm install -g somnia-agent-kitimport { SomniaAgentKit, SOMNIA_NETWORKS } from 'somnia-agent-kit';
// Option 1: With manual config
const kit = new SomniaAgentKit({
network: SOMNIA_NETWORKS.testnet,
contracts: {
agentRegistry: '0xC9f3452090EEB519467DEa4a390976D38C008347',
agentManager: '0x77F6dC5924652e32DBa0B4329De0a44a2C95691E',
agentExecutor: '0x157C56dEdbAB6caD541109daabA4663Fc016026e',
agentVault: '0x7cEe3142A9c6d15529C322035041af697B2B5129',
},
privateKey: process.env.PRIVATE_KEY, // Optional
});
// Or: Auto-load from .env (recommended)
const kit = new SomniaAgentKit();
await kit.initialize();
// Register an agent
await kit.contracts.registry.registerAgent(
'My AI Agent',
'Trading bot for DeFi',
'QmX...', // IPFS hash
['trading', 'defi'] // capabilities
);import { SomniaAgentKit } from 'somnia-agent-kit';
// Auto-load config from .env
const kit = new SomniaAgentKit();
await kit.initialize();// Register new agent
const tx = await kit.contracts.registry.registerAgent(
'My AI Agent',
'Trading bot for DeFi',
'QmX...', // IPFS hash
['trading', 'defi'] // capabilities
);
await tx.wait();
// Query agents
const totalAgents = await kit.contracts.registry.getTotalAgents();
const agent = await kit.contracts.registry.getAgent(1);
console.log(agent.name, agent.owner, agent.isActive);import { parseEther, formatEther } from 'somnia-agent-kit';
// Get agent address
const agent = await kit.contracts.registry.getAgent(agentId);
const agentAddress = agent.owner;
// Deposit native tokens to vault
await kit.contracts.vault.depositNative(agentAddress, {
value: parseEther('1.0')
});
// Check balance
const balance = await kit.contracts.vault.getNativeBalance(agentAddress);
console.log(`Balance: ${formatEther(balance)} STT`);
// Withdraw funds
await kit.contracts.vault.withdrawNative(
agentAddress,
recipientAddress,
parseEther('0.5')
);// Create task for agent
const tx = await kit.contracts.manager.createTask(
agentId,
JSON.stringify({ action: 'analyze', symbol: 'ETH/USD' }),
{ value: parseEther('0.001') } // Payment
);
await tx.wait();
// Execute task
await kit.contracts.executor.execute(taskId);import { Agent, OllamaAdapter, LLMPlanner } from 'somnia-agent-kit';
const agent = new Agent({
name: 'Trading Bot',
description: 'Automated DeFi trading',
capabilities: ['analyze', 'trade', 'monitor'],
llm: new OllamaAdapter({ model: 'llama3.2' }),
planner: new LLMPlanner(),
triggers: [
{ type: 'interval', config: { interval: 60000 } } // Run every minute
],
memory: { enabled: true, maxSize: 1000 }
});
// Start agent
await agent.start();
// Stop agent
await agent.stop();import { OllamaAdapter, OpenAIAdapter } from 'somnia-agent-kit';
// Local AI (FREE)
const ollama = new OllamaAdapter({
baseURL: 'http://localhost:11434',
model: 'llama3.2'
});
const response = await ollama.chat([
{ role: 'user', content: 'Should I buy ETH now?' }
]);
// OpenAI
const openai = new OpenAIAdapter({
apiKey: process.env.OPENAI_API_KEY
});
const analysis = await openai.chat([
{ role: 'system', content: 'You are a DeFi trading expert' },
{ role: 'user', content: 'Analyze ETH price trend' }
]);import { ERC20Manager, ERC721Manager } from 'somnia-agent-kit';
// ERC20 tokens
const erc20 = new ERC20Manager(kit.getChainClient());
await erc20.transfer(tokenAddress, recipientAddress, amount);
const balance = await erc20.getBalance(tokenAddress, walletAddress);
const allowance = await erc20.getAllowance(tokenAddress, owner, spender);
// ERC721 NFTs
const erc721 = new ERC721Manager(kit.getChainClient());
await erc721.transferNFT(nftAddress, fromAddress, toAddress, tokenId);
const owner = await erc721.getOwner(nftAddress, tokenId);import { MultiCall } from 'somnia-agent-kit';
const multicall = new MultiCall(kit.getChainClient());
// Batch multiple reads in one call
const results = await multicall.aggregate([
{
target: registryAddress,
callData: registry.interface.encodeFunctionData('getAgent', [1])
},
{
target: vaultAddress,
callData: vault.interface.encodeFunctionData('getNativeBalance', [agentAddress])
},
{
target: registryAddress,
callData: registry.interface.encodeFunctionData('getTotalAgents')
}
]);import { Logger, Metrics, Dashboard } from 'somnia-agent-kit';
// Structured logging
const logger = new Logger({ level: 'info' });
logger.info('Agent started', { agentId: 1, timestamp: Date.now() });
logger.error('Task failed', { taskId: 123, error: 'Timeout' });
// Track metrics
const metrics = new Metrics();
metrics.recordLLMCall(250, true); // duration, success
metrics.recordTransaction('0x...', true, 0.001);
console.log(metrics.getSummary());
// Web dashboard
const dashboard = new Dashboard({ port: 3001 });
await dashboard.start();
// Visit http://localhost:3001# Install CLI globally
npm install -g somnia-agent-kit
# Initialize project
sak init
# Agent management
sak agent:list
sak agent:register --name "My Bot"
sak agent:info --id 1
# Task operations
sak task:create --agent-id 1 --data '{"action":"analyze"}'
sak task:status --task-id 123
# Wallet operations
sak wallet:balance
sak wallet:send --to 0x... --amount 1.0
# Network info
sak network:infoDeployed on Somnia Testnet (Chain ID: 50312)
| Contract | Address |
|---|---|
| AgentRegistry | 0xC9f3452090EEB519467DEa4a390976D38C008347 |
| AgentManager | 0x77F6dC5924652e32DBa0B4329De0a44a2C95691E |
| AgentExecutor | 0x157C56dEdbAB6caD541109daabA4663Fc016026e |
| AgentVault | 0x7cEe3142A9c6d15529C322035041af697B2B5129 |
RPC: https://dream-rpc.somnia.network
Explorer: https://explorer.somnia.network
Create .env file:
# Network
SOMNIA_RPC_URL=https://dream-rpc.somnia.network
SOMNIA_CHAIN_ID=50312
# Private Key (optional - only for write operations)
PRIVATE_KEY=0x...
# Contract Addresses
AGENT_REGISTRY_ADDRESS=0xC9f3452090EEB519467DEa4a390976D38C008347
AGENT_MANAGER_ADDRESS=0x77F6dC5924652e32DBa0B4329De0a44a2C95691E
AGENT_EXECUTOR_ADDRESS=0x157C56dEdbAB6caD541109daabA4663Fc016026e
AGENT_VAULT_ADDRESS=0x7cEe3142A9c6d15529C322035041af697B2B5129
# LLM API Keys (optional)
OPENAI_API_KEY=sk-...
DEEPSEEK_API_KEY=sk-...Local documentation files:
- Quick Start - Get started in 5 minutes
- SDK Usage - Core SDK features and examples
- Agent Development - Build autonomous agents
- Task Management - Task operations
- Vault Operations - Fund management
- LLM Integration - AI reasoning and planning
- CLI Guide - Command-line tools
- API Reference - Complete API documentation
Check out the examples directory:
- 01-quickstart - Initialize SDK and query agents
- 02-register-agent - Register new agent on-chain
- 03-ai-agent - Build AI-powered agent with Ollama
- 04-task-execution - Create and execute tasks
- 05-monitoring - Logging, metrics, and dashboard
- 06-multicall-batch - Batch contract calls
- 07-token-management - ERC20/ERC721 operations
Run examples:
npx ts-node examples/01-quickstart/index.ts# Clone repository
git clone https://github.com/xuanbach0212/somnia-agent-kit.git
cd somnia-agent-kit
# Install dependencies
pnpm install
# Build all packages
pnpm build
# Run tests
pnpm test
# Build specific package
pnpm build:kitsomnia-agent-kit/
βββ packages/
β βββ agent-kit/ # Main SDK package
β βββ src/
β β βββ core/ # Blockchain SDK
β β βββ runtime/ # Autonomous agents
β β βββ llm/ # LLM integration
β β βββ monitor/ # Monitoring
β β βββ tokens/ # Token management
β β βββ cli/ # CLI tools
β βββ dist/ # Built files
βββ contracts/ # Smart contracts
β βββ contracts/ # Solidity files
β βββ scripts/ # Deploy scripts
β βββ test/ # Contract tests
βββ examples/ # Usage examples
βββ docs/ # Documentation
βββ test/ # Integration tests
- π¦ npm Package: https://www.npmjs.com/package/somnia-agent-kit
- π GitBook Documentation: https://somnia-agent-kit.gitbook.io/somnia-agent-kit
- π» GitHub Repository: https://github.com/xuanbach0212/somnia-agent-kit
- π Website: https://somnia.network
- π Explorer: https://explorer.somnia.network
- π¬ Discord: https://discord.gg/somnia
MIT License - see LICENSE for details.
Built with β€οΈ for Somnia Network