📚API Reference

Comprehensive API documentation for all modules, classes, and functions

Version: 2.0.1 Last Updated: 2025-01-16


Table of Contents

  1. LLM Adapters


Core Modules

SomniaAgentKit

Main SDK Class - Entry point for the Somnia Agent Kit SDK

Location: packages/agent-kit/src/index.ts

Constructor

Parameters:

  • userConfig (optional): Partial configuration object

    • Merged with defaults and environment variables

    • See AgentKitConfig for structure

Example:

Methods

async initialize(): Promise<void>

Initialize the SDK and connect to the network.

Returns: Promise<void>

Throws: Error if network connection fails or chain ID mismatch

Example:


isInitialized(): boolean

Check if the SDK is initialized.

Returns: boolean


getChainClient(): ChainClient

Get the ChainClient instance for blockchain interactions.

Returns: ChainClient instance

Example:


getSignerManager(): SignerManager

Get the SignerManager instance for transaction signing.

Returns: SignerManager instance

Example:


getProvider(): ethers.Provider

Get the ethers.js provider instance.

Returns: ethers.Provider


getSigner(): ethers.Signer | ethers.Wallet | null

Get the signer instance if available.

Returns: Signer instance or null if no private key configured


get contracts: SomniaContracts

Get the contracts wrapper instance.

Returns: SomniaContracts instance

Throws: Error if SDK not initialized

Example:


getConfig(): Readonly<AgentKitConfig>

Get the current configuration (read-only).

Returns: Frozen config object


getNetworkInfo(): NetworkInfo

Get network information.

Returns: Object with name, rpcUrl, chainId


ChainClient

Blockchain Client - Manages provider, signer, and blockchain interactions

Location: packages/agent-kit/src/core/chainClient.ts

Constructor

Methods

async connect(): Promise<void>

Connect to the network and validate chain ID.

Throws: Error if chain ID mismatch


isConnected(): boolean

Check if connected to the network.

Returns: boolean


getProvider(): ethers.JsonRpcProvider

Get the provider instance.

Returns: ethers.JsonRpcProvider


getSignerManager(): SignerManager

Get the signer manager instance.

Returns: SignerManager


getSigner(): ethers.Wallet | ethers.Signer

Get the signer instance.

Returns: Signer instance

Throws: Error if no signer configured


async getBlockNumber(useCache?: boolean): Promise<number>

Get current block number with optional caching (2-second TTL).

Parameters:

  • useCache (default: true): Use cached value if available

Returns: Promise<number> - Current block number

Example:


async refreshBlockNumber(): Promise<number>

Force refresh block number (bypass cache).

Returns: Promise<number>


async getGasPrice(): Promise<bigint>

Get current gas price.

Returns: Promise<bigint> - Gas price in wei


async estimateGas(tx: ethers.TransactionRequest): Promise<bigint>

Estimate gas for a transaction.

Parameters:

  • tx: Transaction request object

Returns: Promise<bigint> - Estimated gas limit


async sendTransaction(tx: ethers.TransactionRequest): Promise<ethers.TransactionReceipt>

Send a transaction and wait for receipt.

Parameters:

  • tx: Transaction request

Returns: Promise<ethers.TransactionReceipt>

Throws: Error if transaction fails


async waitForTransaction(txHash: string, confirmations?: number): Promise<ethers.TransactionReceipt>

Wait for transaction confirmation.

Parameters:

  • txHash: Transaction hash

  • confirmations (default: 1): Number of confirmations to wait for

Returns: Promise<ethers.TransactionReceipt>


async getTransactionReceipt(txHash: string): Promise<ethers.TransactionReceipt | null>

Get transaction receipt.

Parameters:

  • txHash: Transaction hash

Returns: Promise<ethers.TransactionReceipt | null>


async getTransaction(txHash: string): Promise<ethers.TransactionResponse | null>

Get transaction details.

Parameters:

  • txHash: Transaction hash

Returns: Promise<ethers.TransactionResponse | null>


async getTx(txHash: string): Promise<ethers.TransactionResponse | null>

Alias for getTransaction().


getContract(address: string, abi: ethers.Interface | ethers.InterfaceAbi): ethers.Contract

Get a contract instance with signer.

Parameters:

  • address: Contract address

  • abi: Contract ABI or Interface

Returns: ethers.Contract connected to signer


getReadOnlyContract(address: string, abi: ethers.Interface | ethers.InterfaceAbi): ethers.Contract

Get a read-only contract instance.

Parameters:

  • address: Contract address

  • abi: Contract ABI or Interface

Returns: ethers.Contract connected to provider


Event Listening

on(event: string, handler: ethers.Listener): void

Subscribe to provider events.

Parameters:

  • event: Event name ('block', 'pending', 'error', etc.)

  • handler: Event handler function

Example:


off(event: string, handler?: ethers.Listener): void

Unsubscribe from provider events.

Parameters:

  • event: Event name

  • handler (optional): Specific handler to remove (removes all if not provided)


once(event: string, handler: ethers.Listener): void

Subscribe to event (one time only).


removeAllListeners(event?: string): void

Remove all event listeners.

Parameters:

  • event (optional): Specific event (removes all if not provided)


listenerCount(event?: string): any

Get listener count for an event.

Parameters:

  • event (optional): Event name

Returns: Number of listeners


disconnect(): void

Disconnect from network and remove all listeners.


SignerManager

Signer Management - Handles wallet creation, transaction signing, and sending

Location: packages/agent-kit/src/core/signerManager.ts

Constructor

Parameters:

  • provider: Ethers provider instance

  • privateKey (optional): Private key (with or without 0x prefix)

Static Factory Methods

static fromMnemonic(mnemonic: string, provider: ethers.Provider, path?: string): SignerManager

Create SignerManager from mnemonic phrase.

Parameters:

  • mnemonic: 12 or 24 word mnemonic phrase

  • provider: Provider instance

  • path (optional): Derivation path (default: "m/44'/60'/0'/0/0")

Returns: SignerManager instance

Example:


static fromSigner(signer: ethers.Signer, provider: ethers.Provider): SignerManager

Create SignerManager from external signer.

Parameters:

  • signer: External signer (e.g., hardware wallet, browser wallet)

  • provider: Provider instance

Returns: SignerManager instance

Example:


Methods

getSigner(): ethers.Wallet | ethers.Signer

Get the current signer.

Returns: Signer instance

Throws: Error if no signer configured


async getAddress(): Promise<string>

Get signer address.

Returns: Promise<string> - Ethereum address


async getBalance(address?: string): Promise<bigint>

Get account balance.

Parameters:

  • address (optional): Address to check (defaults to signer address)

Returns: Promise<bigint> - Balance in wei


async signMessage(message: string): Promise<string>

Sign a message.

Parameters:

  • message: Message to sign

Returns: Promise<string> - Signature


async signTransaction(tx: ethers.TransactionRequest): Promise<string>

Sign a transaction (without sending).

Parameters:

  • tx: Transaction request

Returns: Promise<string> - Signed transaction


async sendTx(to: string, data: string, value?: bigint): Promise<ethers.TransactionReceipt>

CRITICAL METHOD - Send transaction to blockchain.

Parameters:

  • to: Recipient address

  • data: Transaction data (hex string)

  • value (optional): Value to send in wei

Returns: Promise<ethers.TransactionReceipt>

Throws: Error if transaction fails

Example:


async estimateGas(tx: ethers.TransactionRequest): Promise<bigint>

Estimate gas for a transaction.

Parameters:

  • tx: Transaction request

Returns: Promise<bigint> - Estimated gas limit

Example:


async getNonce(): Promise<number>

Get current nonce for the signer (pending transactions included).

Returns: Promise<number> - Current nonce


async getGasPrice(): Promise<bigint>

Get current gas price.

Returns: Promise<bigint> - Gas price in wei


hasSigner(): boolean

Check if signer is configured.

Returns: boolean


setSigner(privateKey: string): void

Set a new signer using private key.

Parameters:

  • privateKey: Private key (with or without 0x)


SomniaContracts

Contract Wrapper - Type-safe access to Somnia smart contracts

Location: packages/agent-kit/src/core/contracts.ts

Constructor

Static Factory

static fromChainClient(client: ChainClient, addresses: ContractAddresses): SomniaContracts

Create SomniaContracts from ChainClient (recommended).

Parameters:

  • client: ChainClient instance

  • addresses: Contract addresses

Returns: SomniaContracts instance

Example:


Methods

async initialize(): Promise<void>

Initialize contract instances.

Returns: Promise<void>


isInitialized(): boolean

Check if contracts are initialized.

Returns: boolean


Contract Getters

get AgentRegistry: AgentRegistry

Get AgentRegistry contract instance.

Returns: Typechain-generated AgentRegistry contract

Throws: Error if not initialized


get registry: AgentRegistry

Lowercase alias for AgentRegistry.


get AgentExecutor: AgentExecutor

Get AgentExecutor contract instance.

Returns: Typechain-generated AgentExecutor contract


get executor: AgentExecutor

Lowercase alias for AgentExecutor.


get AgentManager: AgentManager

Get AgentManager contract instance.

Returns: Typechain-generated AgentManager contract

Throws: Error if agentManager address not configured


get manager: AgentManager

Lowercase alias for AgentManager.


get AgentVault: AgentVault

Get AgentVault contract instance.

Returns: Typechain-generated AgentVault contract

Throws: Error if agentVault address not configured


get vault: AgentVault

Lowercase alias for AgentVault.


getAddresses(): Readonly<ContractAddresses>

Get all contract addresses.

Returns: Frozen object with addresses


async updateSigner(signer: ethers.Signer): Promise<void>

Update signer and reinitialize contracts.

Parameters:

  • signer: New signer instance

Returns: Promise<void>


getInstances(): Readonly<ContractInstances> | null

Get all contract instances (for advanced usage).

Returns: Frozen object with instances or null if not initialized


Config

Configuration System - Environment variable loading, defaults, and validation

Location: packages/agent-kit/src/core/config.ts

Types & Interfaces

AgentKitConfig Interface


NetworkConfig Interface


ContractAddresses Interface


LLMProviderConfig Interface


Constants

SOMNIA_NETWORKS

Predefined network configurations.


DEFAULT_CONFIG

Default configuration values.


Functions

validateConfig(config: AgentKitConfig): void

Validate configuration object.

Parameters:

  • config: Configuration to validate

Throws: Error if invalid


loadFromEnv(): Partial<AgentKitConfig>

Load configuration from environment variables.

Returns: Partial<AgentKitConfig>

Environment Variables:

  • SOMNIA_RPC_URL, SOMNIA_CHAIN_ID

  • AGENT_REGISTRY_ADDRESS, AGENT_EXECUTOR_ADDRESS, AGENT_MANAGER_ADDRESS, AGENT_VAULT_ADDRESS

  • PRIVATE_KEY

  • OPENAI_API_KEY, OPENAI_MODEL, OLLAMA_BASE_URL, OLLAMA_MODEL

  • DEFAULT_GAS_LIMIT, LOG_LEVEL, METRICS_ENABLED


loadConfig(userConfig?: Partial<AgentKitConfig>): AgentKitConfig

MAIN FUNCTION - Load and merge configuration from defaults, environment, and user input.

Parameters:

  • userConfig (optional): User-provided config

Returns: AgentKitConfig - Complete validated configuration

Priority (highest to lowest):

  1. User-provided config

  2. Environment variables

  3. Default values

Example:


createConfigFromEnv(): AgentKitConfig

Convenience function to load all config from .env file.

Returns: AgentKitConfig

Throws: Error if required env vars missing

Example:


Utils

Utility Library - 20+ helper functions for common tasks

Location: packages/agent-kit/src/core/utils.ts

Async Utilities

sleep(ms: number): Promise<void>

Sleep for specified milliseconds.

Parameters:

  • ms: Milliseconds to sleep

Returns: Promise<void>

Example:


retry<T>(fn: () => Promise<T>, maxRetries?: number, delayMs?: number): Promise<T>

Retry async function with exponential backoff.

Parameters:

  • fn: Async function to retry

  • maxRetries (default: 3): Maximum retry attempts

  • delayMs (default: 1000): Initial delay in milliseconds

Returns: Promise<T> - Result of successful execution

Throws: Last error if all retries fail

Example:


delay<T>(ms: number, value?: T): Promise<T>

Delay execution and optionally return a value.

Parameters:

  • ms: Milliseconds to delay

  • value (optional): Value to return after delay

Returns: Promise<T>

Example:


timeout<T>(promise: Promise<T>, ms: number, errorMessage?: string): Promise<T>

Add timeout to a promise.

Parameters:

  • promise: Promise to add timeout to

  • ms: Timeout in milliseconds

  • errorMessage (optional): Custom error message

Returns: Promise<T>

Throws: Error if timeout reached

Example:


Hex & Data Conversion

toHex(value: number | bigint | string): string

Convert value to hex string.

Parameters:

  • value: Number, bigint, or string to convert

Returns: string - Hex string with 0x prefix

Example:


fromHex(hex: string): number

Parse hex string to number.

Parameters:

  • hex: Hex string

Returns: number

Example:


bytesToHex(bytes: Uint8Array): string

Convert bytes to hex string.

Parameters:

  • bytes: Uint8Array to convert

Returns: string - Hex string with 0x prefix

Example:


hexToBytes(hex: string): Uint8Array

Convert hex string to bytes.

Parameters:

  • hex: Hex string

Returns: Uint8Array

Example:


toUtf8Bytes(str: string): Uint8Array

Convert string to UTF-8 bytes.

Parameters:

  • str: String to convert

Returns: Uint8Array


toUtf8String(bytes: Uint8Array): string

Convert UTF-8 bytes to string.

Parameters:

  • bytes: Bytes to convert

Returns: string


keccak256(data: string | Uint8Array): string

Compute keccak256 hash.

Parameters:

  • data: Data to hash (string or bytes)

Returns: string - Hash as hex string

Example:


Ether & Token Utilities

formatEther(wei: bigint | string): string

Format wei to ether string.

Parameters:

  • wei: Wei amount

Returns: string - Ether amount

Example:


parseEther(ether: string): bigint

Parse ether string to wei.

Parameters:

  • ether: Ether amount as string

Returns: bigint - Wei amount

Example:


formatUnits(value: bigint | string, decimals: number): string

Format token amount with decimals.

Parameters:

  • value: Amount in smallest unit

  • decimals: Token decimals

Returns: string - Formatted amount

Example:


parseUnits(value: string, decimals: number): bigint

Parse token amount with decimals.

Parameters:

  • value: Amount as string

  • decimals: Token decimals

Returns: bigint - Amount in smallest unit

Example:


Address Utilities

isValidAddress(address: string): boolean

Validate Ethereum address format.

Parameters:

  • address: Address to validate

Returns: boolean

Example:


shortAddress(address: string): string

Get short address format (0x1234...5678).

Parameters:

  • address: Address to shorten

Returns: string - Shortened address

Example:


EventEmitter

class EventEmitter<TEvents>

Type-safe event emitter for custom event handling.

Generic Type:

  • TEvents: Record of event names to event data types

Example:

Methods:

  • on<K>(event: K, listener: EventListener<TEvents[K]>): () => void - Subscribe to event

  • once<K>(event: K, listener: EventListener<TEvents[K]>): () => void - Subscribe once

  • off<K>(event: K, listener: EventListener<TEvents[K]>): void - Unsubscribe

  • emit<K>(event: K, data: TEvents[K]): void - Emit event

  • removeAllListeners(event?: K): void - Remove all listeners

  • listenerCount(event: K): number - Get listener count


Logger Shortcuts

Logger (Re-exported)

Logger class from monitor/logger.ts.

See Logger section for full API.


LogLevel (Re-exported)

Log level enum: Error, Warn, Info, Debug, Verbose


createLogger(context?: string, config?: LoggerConfig): Logger | ChildLogger

Create a new logger instance.

Parameters:

  • context (optional): Context name for log entries

  • config (optional): Logger configuration

Returns: Logger or ChildLogger instance

Example:


Runtime Modules

Agent

Agent Lifecycle Management - Create, register, and manage AI agents

Location: packages/agent-kit/src/runtime/agent.ts

Agent States

Constructor

AgentConfig:

Methods

async initialize(registry: AgentRegistry, executor: AgentExecutor): Promise<void>

Initialize agent with contract instances.


async register(signer: ethers.Signer): Promise<string>

Register agent on-chain.

Returns: Promise<string> - Agent address


async start(): Promise<void>

Start agent execution.


async pause(): Promise<void>

Pause agent execution.


async resume(): Promise<void>

Resume agent execution.


async stop(): Promise<void>

Stop agent execution.


async terminate(): Promise<void>

Terminate agent (irreversible).


getState(): AgentState

Get current agent state.

Returns: AgentState


getId(): string

Get agent ID.

Returns: string


getAddress(): string | null

Get agent on-chain address.

Returns: string | null


getConfig(): Readonly<AgentConfig>

Get agent configuration.

Returns: Frozen config object


Planner

AI/Rule-Based Planning - LLM and rule-based task planning

Location: packages/agent-kit/src/runtime/planner.ts

Interfaces

IPlanner

Base planner interface.

Action

Simple action format.

Classes

RulePlanner

Rule-based planner for predefined task types.

Usage:

Supported task types: transfer, swap, contract_call, deploy_contract

LLMPlanner

AI-powered planner using OpenAI or Ollama.

Constructor:

Usage:

Methods:

  • setSystemPrompt(prompt: string): Customize AI instructions

  • getSystemPrompt(): Get current system prompt

Planner (Legacy)

Base planner with backward compatibility.

Methods:

  • plan(goal: any, context?: any): Promise<Action[]> - Plan actions

  • createPlan(taskId, taskType, taskData, priority) - Legacy method (deprecated)


Executor

Action Execution Engine - Execute actions with blockchain integration

Location: packages/agent-kit/src/runtime/executor.ts

Constructor

ExecutorConfig:

Methods

execute(action: Action): Promise<ExecutionResult>

Execute single action with retry logic.

Parameters:

  • action: Action to execute { type: string, params: Record<string, any> }

Returns: Promise<ExecutionResult>

Example:


executeAll(actions: Action[]): Promise<ExecutionResult[]>

Execute multiple actions (parallel or sequential).

Parameters:

  • actions: Array of actions

Returns: Promise<ExecutionResult[]>

Example:


registerHandler(action: string, handler: Function): void

Register custom action handler.

Parameters:

  • action: Action type

  • handler: async (params: any) => Promise<any>

Example:

Built-in Handlers

  • validate_address: Validates Ethereum address using ethers.isAddress()

  • validate_contract: Checks if address has bytecode

  • check_balance: Gets balance via ChainClient

  • execute_transfer: Sends ETH transfer with receipt

  • estimate_gas: Estimates transaction gas

  • approve_token: Token approval (placeholder)

  • get_quote: DEX quote (placeholder)

  • execute_swap: Token swap (placeholder)

  • call_contract: Contract method call (placeholder)

  • execute: Generic execution

Dry-Run Mode


Trigger

Event Sources - Blockchain, interval, and webhook triggers

Location: packages/agent-kit/src/runtime/trigger.ts

Interfaces

ITrigger

Base trigger interface.

Trigger Classes

OnChainTrigger

Listen to blockchain events via ChainClient.

Constructor:

Usage:


IntervalTrigger

Time-based periodic execution.

Constructor:

Usage:


WebhookTrigger

HTTP webhook receiver with Express.

Constructor:

Usage:


Trigger (Manager)

Trigger manager with factory methods.

Methods:

  • register(config): Register trigger

  • enable(triggerId): Enable trigger

  • disable(triggerId): Disable trigger

  • getAllTriggers(): Get all registered triggers

  • cleanup(): Stop and cleanup all triggers

  • createOnChainTrigger(...): Factory for OnChainTrigger

  • createIntervalTrigger(...): Factory for IntervalTrigger

  • createWebhookTrigger(...): Factory for WebhookTrigger


Storage

Event & Action Persistence - Memory and file-based storage

Location: packages/agent-kit/src/runtime/storage.ts

Interfaces

IStorage

Base storage interface for events and actions.

EventEntry

Event storage format.

ActionEntry

Action storage format.

Storage Classes

MemoryStorage

In-memory storage (perfect for testing).

Usage:


FileStorage

Persistent JSON file storage.

Constructor:

Usage:

Features:

  • Auto-creates directories

  • Atomic file operations

  • Error handling for missing files

  • JSON pretty-printing


StorageBackend

Enum for Agent options.

Usage with Agent:


Policy

Guards & Access Control - Operational policies and permissions

Location: packages/agent-kit/src/runtime/policy.ts

Operational Policy

OperationalPolicy

Configuration for operational guards.

Methods

checkPermission(address: string, action: string): boolean

Check if address has permission (for Agent.ts compatibility).

Returns: boolean - true if allowed


shouldExecute(action: Action): boolean

Main guard - check all operational policies.

Parameters:

  • action: Action to check

Returns: boolean - true if should execute

Checks:

  • Action type allowed/blocked?

  • Transfer amount within limits?

  • Rate limit not exceeded?

  • Approval required?

Example:


shouldDelay(action: Action): number | false

Check if action should be delayed.

Returns: Delay in milliseconds, or false for no delay

Example:


overrideAction(action: Action): Action

Modify action before execution (e.g., cap amounts).

Returns: Modified action

Example:


Convenience Methods

  • setOperationalPolicy(policy: OperationalPolicy): Set complete policy

  • getOperationalPolicy(): Get current policy

  • setGasLimit(limit: bigint): Set max gas

  • setRetryLimit(limit: number): Set max retries

  • setTransferLimit(min: bigint, max: bigint): Set transfer limits

  • addAllowedAction(action: string): Whitelist action type

  • addBlockedAction(action: string): Blacklist action type

  • setRateLimit(maxActions: number, windowMs: number): Set rate limit

  • recordAction(action: string): Record for rate limiting

  • clearActionHistory(): Clear rate limit history

Access Control (Enterprise)

For enterprise use cases, Policy also supports rule-based access control:

Methods:

  • addRule(rule: PolicyRule): Add permission rule

  • removeRule(ruleId: string): Remove rule

  • assignRole(role: string, address: string): Assign role

  • revokeRole(role: string, address: string): Revoke role

  • hasRole(role: string, address: string): Check role

  • evaluate(context: PolicyContext): Evaluate permission

Example:


Memory

Agent Memory System - Short-term and long-term memory for context-aware agents

Location: packages/agent-kit/src/runtime/memory.ts

Overview

The Memory module enables agents to maintain conversational context and state across interactions. It provides:

  • Short-term memory: Recent interactions within token limits

  • Long-term memory: Persistent storage of all interactions

  • Context building: Token-aware context construction for LLMs

  • Multiple backends: In-memory or file-based storage

  • Session management: Separate memory spaces for different conversations

Types and Interfaces

MemoryType

Memory entry types:

  • input: User inputs, events, goals

  • output: Agent responses, results

  • state: Agent state changes

  • system: System messages, errors


MemoryEntry

Memory entry structure.


MemoryBackend

Interface for storage backends.


MemoryFilter

Filter options for querying memory.


MemoryConfig

Configuration for Memory instance.


Backend Implementations

InMemoryBackend

Fast in-memory storage (for development/testing).

Usage:

Features:

  • Fast read/write operations

  • No disk I/O

  • Data lost on process restart

  • Perfect for testing and development


FileBackend

Persistent JSON file storage.

Constructor:

Usage:

Features:

  • Persistent storage across restarts

  • One JSON file per session

  • Automatic directory creation

  • Pretty-printed JSON for debugging


Memory Class

Constructor

Example:


async addMemory(type: MemoryType, content: any, metadata?: Record<string, any>): Promise<string>

Add memory entry.

Parameters:

  • type: Memory type

  • content: Content to store (any type)

  • metadata (optional): Additional metadata

Returns: Entry ID

Example:


async addInput(content: any, metadata?: Record<string, any>): Promise<string>

Add input memory (convenience method).

Example:


async addOutput(content: any, metadata?: Record<string, any>): Promise<string>

Add output memory (convenience method).

Example:


async addState(content: any, metadata?: Record<string, any>): Promise<string>

Add state memory (convenience method).

Example:


async getContext(maxTokens?: number): Promise<string>

CRITICAL METHOD - Build context string for LLM within token limit.

Parameters:

  • maxTokens (optional): Max tokens to include (default: from config)

Returns: Formatted context string

Algorithm:

  1. Retrieves all memory entries

  2. Starts from most recent

  3. Adds entries until token limit reached

  4. Formats with timestamps and types

  5. Returns chronologically ordered context

Example:

Output Format:


async getHistory(filter?: MemoryFilter): Promise<MemoryEntry[]>

Get all memory entries with optional filtering.

Parameters:

  • filter (optional): Filter criteria

Returns: Array of memory entries

Example:


async getRecent(limit: number = 10): Promise<MemoryEntry[]>

Get recent memory entries.

Parameters:

  • limit: Number of entries to retrieve

Returns: Array of recent entries

Example:


async getByType(type: MemoryType, limit?: number): Promise<MemoryEntry[]>

Get memory entries by type.

Parameters:

  • type: Memory type

  • limit (optional): Limit number of results

Example:


async clear(): Promise<void>

Clear all memory for current session.

Example:


async clearAll(): Promise<void>

Clear all sessions (all memory).

Example:


async count(): Promise<number>

Get memory entry count for current session.

Returns: Number of entries

Example:


getSessionId(): string

Get current session ID.

Returns: Session ID string


setSessionId(sessionId: string): void

Switch to different session.

Parameters:

  • sessionId: New session ID

Example:


async summarize(): Promise<string>

Get summary of memory contents.

Returns: Summary string with statistics

Example:


async export(): Promise<MemoryEntry[]>

Export all memory entries as JSON.

Returns: Array of all entries

Example:


async import(entries: MemoryEntry[]): Promise<void>

Import memory entries from JSON.

Parameters:

  • entries: Array of memory entries

Example:


Integration with Agent

The Agent class automatically integrates with Memory:

Constructor Options:

Agent Methods:

async addMemory(type: MemoryType, content: any, metadata?: Record<string, any>): Promise<string>

Add memory entry via agent.

Example:


async getMemoryContext(maxTokens?: number): Promise<string>

Get memory context for LLM.

Example:


async getMemoryHistory(limit?: number): Promise<MemoryEntry[]>

Get memory history.

Example:


async clearMemory(): Promise<void>

Clear agent memory.

Example:


getMemorySessionId(): string

Get current session ID.


setMemorySessionId(sessionId: string): void

Switch memory session.

Example:


getMemoryModule(): Memory

Get direct access to Memory instance (for advanced usage).

Example:


Automatic Memory Integration

When an agent processes events, memory is automatically managed:

This creates a complete memory trail of all agent interactions.


Complete Usage Example


Helper Functions

createMemory(sessionId?: string): Memory

Create memory with in-memory backend.

Example:


createFileMemory(basePath?: string, sessionId?: string): Memory

Create memory with file backend.

Example:


Best Practices

  1. Use file backend for production:

  1. Set appropriate token limits:

  1. Use session IDs for multi-user systems:

  1. Backup memory periodically:

  1. Clean up old sessions:


LLM Adapters

Standard Interface: LLMAdapter

All LLM adapters implement a unified LLMAdapter interface for consistent usage across different providers.

Location: packages/agent-kit/src/llm/types.ts

Standard Types

LLMResponse

GenerateOptions

Message


OpenAIAdapter

OpenAI GPT Integration - GPT-3.5, GPT-4, embeddings, streaming

Location: packages/agent-kit/src/llm/openaiAdapter.ts

Constructor

OpenAIConfig:

Methods

async generate(input: string, options?: GenerateOptions): Promise<LLMResponse>

Generate text completion.

Example:


async chat(messages: Message[], options?: GenerateOptions): Promise<LLMResponse>

Chat completion with message history.

Example:


async embed(text: string, model?: string): Promise<number[]>

Generate embeddings for semantic search.

Example:


async *stream(input: string, options?: GenerateOptions): AsyncGenerator<string>

Stream text completion for real-time responses.

Example:


async testConnection(): Promise<boolean>

Test connection to OpenAI API.

Example:


AnthropicAdapter

Anthropic Claude Integration - Claude 3 Opus, Sonnet, Haiku

Location: packages/agent-kit/src/llm/anthropicAdapter.ts

Constructor

AnthropicConfig:

Supported Models:

  • claude-3-opus-20240229 - Most powerful, best for complex tasks

  • claude-3-sonnet-20240229 - Balanced performance and speed

  • claude-3-haiku-20240307 - Fastest, best for simple tasks

Methods

async generate(input: string, options?: GenerateOptions): Promise<LLMResponse>

Generate text completion with Claude.

Example:


async chat(messages: Message[], options?: GenerateOptions): Promise<LLMResponse>

Chat with message history. System messages are automatically extracted.

Example:


async *stream(input: string, options?: GenerateOptions): AsyncGenerator<string>

Stream responses from Claude.

Example:


async testConnection(): Promise<boolean>

Test connection to Anthropic API.


OllamaAdapter

Local LLM Integration - Llama, Mistral, and other local models

Location: packages/agent-kit/src/llm/ollamaAdapter.ts

Constructor

OllamaConfig:

Supported Models (examples):

  • llama2, llama3 - Meta's Llama models

  • mistral, mixtral - Mistral AI models

  • codellama - Code-specialized model

  • phi - Microsoft's small models

Methods

async generate(input: string, options?: GenerateOptions): Promise<LLMResponse>

Generate text with local model.

Example:


async chat(messages: Message[], options?: GenerateOptions): Promise<LLMResponse>

Chat completion with local model.

Example:


async embed(text: string, model?: string): Promise<number[]>

Generate embeddings with local model.


async *stream(input: string, options?: GenerateOptions): AsyncGenerator<string>

Stream responses from local model.


async listModels(): Promise<OllamaModel[]>

List all available local models.

Example:


async pullModel(model: string): Promise<void>

Download a model from Ollama registry.

Example:


async deleteModel(model: string): Promise<void>

Delete a local model.


async hasModel(model: string): Promise<boolean>

Check if model exists locally.

Example:


async testConnection(): Promise<boolean>

Test connection to Ollama server.


Unified Usage Example

All adapters implement the same interface, making it easy to switch providers:

Retry and Timeout Configuration

All adapters support automatic retry with exponential backoff:

Custom Logging

All adapters support custom loggers:


Prompt Management

Dynamic prompt building and template system for AI agents.

Location: packages/agent-kit/src/prompt/

Overview

The prompt module provides:

  • Templates: Pre-built prompt templates for common agent tasks

  • Builder: Dynamic prompt construction with placeholder replacement

  • Validation: Template validation and variable checking

  • Sanitization: Security features to prevent prompt injection


Prompt Templates

PromptTemplate Interface

Built-in Templates

ACTION_PLANNER_PROMPT

Plans actions from user goals. Used by LLMPlanner.

Variables: goal, context

Example:


BLOCKCHAIN_ANALYZER_PROMPT

Analyzes blockchain state and provides recommendations.

Variables: blockNumber, network, gasPrice, task, events, state

Example:


EVENT_HANDLER_PROMPT

Handles blockchain events and determines appropriate actions.

Variables: eventType, contractAddress, blockNumber, txHash, eventData, instructions


TRANSACTION_BUILDER_PROMPT

Builds blockchain transactions based on requirements.

Variables: txType, target, amount, data, requirements


Additional Templates

  • BASIC_AGENT_PROMPT: General purpose AI agent

  • TOOL_EXECUTOR_PROMPT: Executes tools and handles results

  • DATA_QUERY_PROMPT: Queries blockchain data

  • ERROR_HANDLER_PROMPT: Handles errors and suggests recovery

  • RISK_ASSESSMENT_PROMPT: Assesses transaction risks


Prompt Builder

buildPrompt()

Build prompt from template string and data.

BuildOptions:

Placeholder Syntax:

  • {{variable}} - Simple placeholder

  • ${variable} - Alternative syntax

  • {{#if variable}}...{{/if}} - Conditional blocks

Example:


buildFromTemplate()

Build prompt from named template.

Example:


composePrompts()

Combine multiple prompts together.

Example:


injectContext()

Inject context into prompt.

Example:


sanitizeData()

Sanitize data to prevent injection attacks.

Removes:

  • Control characters (\x00-\x1F, \x7F)

  • Leading/trailing whitespace

  • Recursively sanitizes nested objects

Example:


validateTemplate()

Validate template against data.

Example:


extractVariables()

Extract variables from template string.

Example:


previewTemplate()

Preview template with example data.

Example:


createTemplate()

Create custom prompt template.

Example:


Template Helpers

getTemplate()

Get template by name.

Example:


listTemplates()

List all available templates.

Example:


getTemplateVariables()

Get variables for a template.

Example:


Complete Usage Example


Integration with LLMPlanner

The LLMPlanner automatically uses the ACTION_PLANNER_PROMPT template:

You can override with custom prompt:


Security Best Practices

  1. Always sanitize user input:

  1. Use strict mode for required variables:

  1. Enforce max length:

  1. Validate before building:


Monitoring

Logger

Structured Logging - Multi-level logging with context

Location: packages/agent-kit/src/monitor/logger.ts

Log Levels

Constructor

LoggerConfig:

Methods

error(message: string, metadata?: Record<string, any>, context?: string): void

Log error message.


warn(message: string, metadata?: Record<string, any>, context?: string): void

Log warning message.


info(message: string, metadata?: Record<string, any>, context?: string): void

Log info message.


debug(message: string, metadata?: Record<string, any>, context?: string): void

Log debug message.


verbose(message: string, metadata?: Record<string, any>, context?: string): void

Log verbose message.


child(context: string): ChildLogger

Create child logger with predefined context.

Parameters:

  • context: Context name

Returns: ChildLogger instance

Example:


getLogs(limit?: number): LogEntry[]

Get recent logs.

Parameters:

  • limit (optional): Limit number of logs

Returns: LogEntry[]


getLogsByLevel(level: LogLevel, limit?: number): LogEntry[]

Get logs by level.


getLogsByContext(context: string, limit?: number): LogEntry[]

Get logs by context.


getLogsByTimeRange(startTime: number, endTime: number): LogEntry[]

Get logs in time range.


clearLogs(): void

Clear all logs.


setLevel(level: LogLevel): void

Set log level.


getLevel(): LogLevel

Get current log level.


Metrics

Performance Metrics - Counters, gauges, histograms, timing, uptime tracking

Location: packages/agent-kit/src/monitor/metrics.ts

Constructor

MetricsConfig:

Core Methods

record(name: string, value: number, tags?: Record<string, string>): void

Record a metric value.

Parameters:

  • name: Metric name

  • value: Metric value

  • tags (optional): Metric tags/labels


increment(name: string, value?: number): void

Increment a counter.

Parameters:

  • name: Counter name

  • value (optional): Increment value (default: 1)


decrement(name: string, value?: number): void

Decrement a counter.


gauge(name: string, value: number): void

Set a gauge value.


histogram(name: string, value: number): void

Record a histogram value.


async time<T>(name: string, fn: () => Promise<T>): Promise<T>

Time an async operation.

Example:


Getter Methods

getCounter(name: string): number

Get counter value.

Returns: Counter value (0 if not found)


getGauge(name: string): number | undefined

Get gauge value.


getHistogram(name: string): number[]

Get histogram values.

Returns: Array of recorded values


getSummary(name: string): MetricSummary | null

Get metric summary with statistics.

Returns: MetricSummary with count, sum, avg, min, max, lastValue, lastTimestamp


getAllSummaries(): MetricSummary[]

Get summaries for all metrics.


getMetrics(name: string, limit?: number): Metric[]

Get raw metrics by name.


getMetricsByTimeRange(name: string, startTime: number, endTime: number): Metric[]

Get metrics in time range.


getMetricNames(): string[]

Get all metric names.


Calculated Metrics

rate(numerator: string, denominator: string): number

Calculate rate (ratio) between two counters as percentage.

Example:


calculateRate(metricName: string, windowMs?: number): number

Calculate operations per second over time window.

Parameters:

  • metricName: Counter name

  • windowMs (optional): Time window in milliseconds (default: 60000 = 60s)

Returns: Rate per second (TPS for transactions)

Example:


getPercentile(name: string, percentile: number): number | null

Calculate percentile for histogram.

Parameters:

  • name: Histogram name

  • percentile: Percentile (0-100), e.g., 50 for median, 95 for p95, 99 for p99

Example:


Uptime Tracking

getUptime(): number

Get uptime in milliseconds since metrics instance creation.


resetUptime(): void

Reset uptime counter.


Convenience Methods

recordTransaction(success: boolean, gasUsed?: number): void

Record a blockchain transaction.

Parameters:

  • success: Whether transaction succeeded

  • gasUsed (optional): Amount of gas used

Increments:

  • tx.total counter

  • tx.success or tx.failed counter

  • Records tx.gas_used histogram


recordLLMCall(duration?: number, success?: boolean): void

Record an LLM call.

Parameters:

  • duration (optional): Duration in milliseconds

  • success (optional): Whether call succeeded (default: true)

Increments:

  • llm.total counter

  • llm.success or llm.failed counter

  • Records llm.reasoning_time histogram


recordGasUsed(amount: number): void

Record gas usage.


Export Methods

getSnapshot(): Record<string, any>

Get snapshot of all metrics (alias for export).

Returns: Complete metrics snapshot including counters, gauges, histograms, calculated metrics (tx_sent, tx_success_rate, avg_gas_used, llm_calls, reasoning_time, uptime, tps)


export(): Record<string, any>

Export metrics as JSON.

Returns: Structured metrics data with counters, gauges, summaries, histograms, and calculated metrics

Example:


clear(name?: string): void

Clear metrics.

Parameters:

  • name (optional): Clear specific metric, or all if omitted


EventRecorder

Event Tracking - On-chain event listening and recording

Location: packages/agent-kit/src/monitor/eventRecorder.ts

Methods

async record(contract: ethers.Contract, eventName: string, callback?: (event: any) => void): Promise<void>

Start recording events from contract.

Parameters:

  • contract: Contract instance

  • eventName: Event name to listen for

  • callback (optional): Callback function for each event

Returns: Promise<void>

Example:


stopRecording(contract: ethers.Contract, eventName: string): void

Stop recording events.

Parameters:

  • contract: Contract instance

  • eventName: Event name


getEvents(eventName: string, limit?: number): ContractEvent[]

Get recorded events.

Parameters:

  • eventName: Event name

  • limit (optional): Limit number of events

Returns: ContractEvent[]


getEventsByTimeRange(startTime: number, endTime: number): ContractEvent[]

Get events in time range.


clearEvents(): void

Clear all recorded events.


export(): ContractEvent[]

Export all events.

Returns: ContractEvent[]


Telemetry

Remote Observability - Send logs and metrics to external monitoring services

Location: packages/agent-kit/src/monitor/telemetry.ts

Supported Formats

  • JSON: Generic JSON format for custom endpoints

  • Prometheus: Text format for Prometheus Pushgateway

  • Datadog: Datadog Series API format

  • OpenTelemetry: OTLP metrics format

Constructor

TelemetryConfig:

Methods

send(data: TelemetryData): void

Send data to telemetry (non-blocking, adds to queue).

Parameters:

  • data: Telemetry data with type ('log', 'metric', 'event'), timestamp, and data payload

Auto-flushes when batch size reached.


async sendMetrics(metrics: Metrics): Promise<void>

Send metrics snapshot to telemetry.

Parameters:

  • metrics: Metrics instance


async sendLogs(logs: LogEntry[]): Promise<void>

Send log entries to telemetry.

Parameters:

  • logs: Array of log entries


async sendEvent(event: any, tags?: Record<string, string>): Promise<void>

Send custom event to telemetry.

Parameters:

  • event: Event data

  • tags (optional): Event tags


async flush(): Promise<void>

Flush queue to endpoint immediately.

Behavior:

  • Non-blocking async operation

  • Batches items from queue

  • Formats based on config (JSON, Prometheus, Datadog, OpenTelemetry)

  • Retries with exponential backoff (1s → 2s → 4s → 10s max)


enable(): void

Enable telemetry and start auto-flush.


disable(): void

Disable telemetry and stop auto-flush.


isEnabled(): boolean

Check if telemetry is enabled.


getQueueSize(): number

Get current queue size.


clearQueue(): void

Clear telemetry queue.


async shutdown(): Promise<void>

Cleanup and flush remaining data.

Important: Call before process exit to ensure all data is sent.


Helper Functions

createTelemetry(config?: TelemetryConfig): Telemetry

Create telemetry instance with config.


async sendTelemetry(data: any): Promise<void>

Convenience function to send telemetry using default instance.

Requires: TELEMETRY_ENDPOINT environment variable

Example:


Usage Examples

Prometheus Integration:

Datadog Integration:

Custom JSON Endpoint:


Dashboard

Development Monitoring UI - Real-time agent monitoring with REST API and HTML UI

Location: packages/agent-kit/src/monitor/dashboard.ts

Constructor

DashboardConfig:

Methods

async start(): Promise<void>

Start dashboard server.

Output: Logs dashboard URL to console


async stop(): Promise<void>

Stop dashboard server.


getURL(): string

Get dashboard URL.

Returns: URL string (e.g., http://localhost:3001)


isRunning(): boolean

Check if dashboard is running.


Helper Functions

startDashboard(config: DashboardConfig): Dashboard

Convenience function to create and start dashboard.

Returns: Dashboard instance

Example:


REST API Endpoints

GET /health

Health check endpoint.

Response:


GET /metrics

Get metrics snapshot.

Response: Complete metrics data (counters, gauges, histograms, calculated metrics)

Example:


GET /logs?limit=N

Get recent logs.

Query Parameters:

  • limit (optional): Number of logs (default: 20)

Response:


GET /status

Get agent status.

Response:


GET /

HTML dashboard UI.

Features:

  • Real-time metrics display

  • Recent logs with auto-refresh (10s)

  • Agent status with uptime

  • Dark theme UI

  • Auto-refresh metrics/status every 5s


Usage Example

Complete Setup:


Quick Reference

Import Paths


Common Patterns

Basic Setup

Send Transaction

Contract Interaction

Event Listening

Logging


Type Definitions

All types are exported from the main package:


End of API Reference

For more information, see:

Last updated