Complete guide for building fully autonomous AI agents with lifecycle management, triggers, planning, and execution.
Overview
The Runtime module provides a complete framework for building autonomous agents that can:
React to events (blockchain, time-based, webhooks)
Plan tasks using AI reasoning
Execute actions autonomously
Learn from past interactions
Follow safety policies
Agent Lifecycle
Agent States
enumAgentState{Created,// Agent created but not startedRunning,// Agent is active and processingPaused,// Agent temporarily pausedStopped,// Agent stoppedError// Agent encountered error}
Create Agent
Initialize Agent
Start Agent
Pause Agent
Resume Agent
Stop Agent
Get Agent State
Triggers
Triggers define when your agent should act.
Interval Trigger
Execute at regular time intervals:
OnChain Trigger
React to blockchain events:
Webhook Trigger
Receive HTTP webhooks:
Multiple Triggers
Planning
LLM Planner
Uses AI to break down goals into actionable steps:
// Test execution without actually running
const executor = new Executor(chainClient, contracts, {
dryRun: true
});
const results = await executor.executeAll(tasks);
// Tasks are simulated, no actual execution
const agent = new Agent({
name: 'Learning Agent',
description: 'Agent with memory',
capabilities: ['learn', 'adapt'],
llm: new OllamaAdapter({ model: 'llama3.2' }),
planner: new LLMPlanner()
}, {
enableMemory: true,
memoryBackend: 'file', // 'file' or 'memory'
memoryPath: './data/memory',
sessionId: 'agent-1'
});
import { Memory, FileBackend } from 'somnia-agent-kit';
// Create memory
const memory = new Memory({
backend: new FileBackend('./data/memory'),
sessionId: 'agent-1'
});
// Add input
await memory.addInput('User asked about ETH price', {
timestamp: Date.now(),
source: 'user'
});
// Add output
await memory.addOutput('ETH price is $2000', {
timestamp: Date.now(),
confidence: 0.95
});
// Get recent memories
const recent = await memory.getRecent(10);
console.log('Recent memories:', recent);
// Search memories
const results = await memory.search('ETH price');
console.log('Search results:', results);
// Clear old memories
await memory.clear();
import { Policy } from 'somnia-agent-kit';
const policy = new Policy();
// Add permission rules
policy.addPermission('user1', 'execute');
policy.addPermission('user2', 'read');
// Add operational limits
policy.setOperationalLimit('maxGasPrice', 100); // gwei
policy.setOperationalLimit('maxTransactionValue', 1000); // USD
policy.setOperationalLimit('dailyLimit', 10000); // USD
// Add safety rules
policy.addSafetyRule('no_weekend_trading', (context) => {
const day = new Date().getDay();
return day !== 0 && day !== 6; // Not Sunday or Saturday
});
policy.addSafetyRule('price_threshold', (context) => {
return context.price > 1000 && context.price < 5000;
});
// Check permission
if (policy.checkPermission('user1', 'execute')) {
// User has permission
await executeAction();
}
// Check operational limits
if (policy.checkOperationalLimit('gasPrice', currentGasPrice)) {
// Within limits
await sendTransaction();
}
// Check safety rules
if (policy.checkAllSafetyRules(context)) {
// All rules passed
await executeTrade();
}
import { FileStorage } from 'somnia-agent-kit';
const storage = new FileStorage('./data/agent');
// Save event
await storage.saveEvent({
type: 'task_completed',
taskId: 123,
result: 'success'
});
// Save action
await storage.saveAction(
{ type: 'trade', symbol: 'ETH' },
{ txHash: '0x...' }
);
// Get history
const history = await storage.getHistory();
console.log('Events:', history.events.length);
console.log('Actions:', history.actions.length);