Overview
The AgentRuntime class is the central orchestrator for elizaOS agents. It manages plugins, actions, evaluators, providers, services, and the agent’s execution lifecycle.
Constructor
new AgentRuntime(options?: {
conversationLength?: number;
agentId?: UUID;
character?: Character;
plugins?: Plugin[];
fetch?: typeof fetch;
adapter?: IDatabaseAdapter;
settings?: RuntimeSettings;
allAvailablePlugins?: Plugin[];
logLevel?: "trace" | "debug" | "info" | "warn" | "error" | "fatal";
disableBasicCapabilities?: boolean;
advancedCapabilities?: boolean;
actionPlanning?: boolean;
llmMode?: "DEFAULT" | "SMALL" | "LARGE";
checkShouldRespond?: boolean;
enableAutonomy?: boolean;
sandboxMode?: boolean;
sandboxTokenManager?: SandboxTokenManager;
sandboxAuditHandler?: (event: SandboxFetchAuditEvent) => void;
})
Number of messages to retain in conversation context (default: 100)
Unique identifier for the agent. If not provided, generated from character name
Character configuration defining the agent’s personality and behavior. If not provided, an anonymous character is created
Array of plugins to register with the agent
Database adapter for persistence. Required for production use
Logging verbosity: “trace”, “debug”, “info”, “warn”, “error”, or “fatal”
Enable multi-action execution. When false, agent executes only one action per response (performance optimization for games)
Override model selection: “DEFAULT” (use specified model), “SMALL” (force TEXT_SMALL), or “LARGE” (force TEXT_LARGE)
Enable shouldRespond evaluation. When false, agent always responds (ChatGPT mode)
Enable autonomous operation with continuous thinking loop
Enable secure secret isolation. Secrets become opaque tokens in the runtime
Core Properties
The unique identifier for this agent instance
The character configuration defining agent behavior
Registered actions the agent can perform
Registered evaluators for message assessment
Registered providers for external data/services
Registered plugins extending agent functionality
Database adapter for persistence operations
Initialization
initialize
Initialize the runtime, register plugins, and set up the database.
await runtime.initialize(options?: {
skipMigrations?: boolean;
allowNoDatabase?: boolean;
}): Promise<void>
Skip database migrations (for serverless mode)
Allow running without a persistent database (uses in-memory adapter)
Example:
import { AgentRuntime } from "@elizaos/core";
import { sqlitePlugin } from "@elizaos/plugin-sql";
const runtime = new AgentRuntime({
character: myCharacter,
plugins: [sqlitePlugin],
logLevel: "info"
});
await runtime.initialize();
Plugin Management
registerPlugin
Register a plugin with the runtime.
await runtime.registerPlugin(plugin: Plugin): Promise<void>
Example:
import { customPlugin } from "./my-plugin";
await runtime.registerPlugin(customPlugin);
Action Management
registerAction
Register an action that the agent can perform.
runtime.registerAction(action: Action): void
Action definition with handler and validation
getAllActions
Get all registered actions.
runtime.getAllActions(): Action[]
getFilteredActions
Get actions filtered by tool policy.
runtime.getFilteredActions(context?: {
profile?: ToolProfileId;
characterPolicy?: ToolPolicyConfig;
channelPolicy?: ToolPolicyConfig;
providerPolicy?: ToolPolicyConfig;
worldPolicy?: ToolPolicyConfig;
roomPolicy?: ToolPolicyConfig;
}): Action[]
Returns: Array of actions allowed by the policy context.
Evaluator Management
registerEvaluator
Register an evaluator for message assessment.
runtime.registerEvaluator(evaluator: Evaluator): void
Evaluator definition with phase (pre/post) and handler
evaluatePre
Run all pre-phase evaluators on an incoming message. Pre-evaluators can block or rewrite messages before processing.
await runtime.evaluatePre(
message: Memory,
state?: State
): Promise<PreEvaluatorResult>
If true, the message is blocked from processing
Optional replacement text (sanitized/redacted version)
Reason for blocking/rewriting
Provider Management
registerProvider
Register a provider for external data/services.
runtime.registerProvider(provider: Provider): void
Provider definition with data retrieval function
State Management
composeState
Compose state from providers for a given message.
await runtime.composeState(
message: Memory,
includeList?: string[] | null,
onlyInclude?: boolean,
skipCache?: boolean,
trajectoryPhase?: string
): Promise<State>
Message to compose state for
Provider names to include
If true, only include providers in includeList
Returns: Composed state with provider data, values, and text.
Settings Management
getSetting
Get a setting value from character configuration or environment.
runtime.getSetting(key: string): string | boolean | number | null
Returns: Setting value or null if not found.
Example:
const apiKey = runtime.getSetting("OPENAI_API_KEY");
const enableFeature = runtime.getSetting("ENABLE_ADVANCED_MODE");
setSetting
Set a setting value in the character configuration.
runtime.setSetting(
key: string,
value: string | boolean | null,
secret?: boolean
): void
value
string | boolean | null
required
Setting value
If true, store in secrets instead of settings
Service Management
getService
Get a registered service by name.
runtime.getService<T extends Service>(serviceName: ServiceTypeName): T | null
Returns: Service instance or null if not found.
Example:
const messageService = runtime.getService<IMessageService>("message");
if (messageService) {
await messageService.sendMessage(content);
}
Memory Operations
createMemory
Create a new memory in the database.
await runtime.createMemory(
memory: Memory,
tableName: string
): Promise<void>
Table name (“messages”, “documents”, etc.)
getMemories
Retrieve memories from the database.
await runtime.getMemories(params: {
roomId: UUID;
count?: number;
unique?: boolean;
tableName: string;
agentId?: UUID;
start?: number;
end?: number;
}): Promise<Memory[]>
searchMemories
Search memories by embedding similarity.
await runtime.searchMemories(params: {
tableName: string;
roomId: UUID;
embedding: number[];
match_threshold?: number;
match_count?: number;
unique?: boolean;
}): Promise<Memory[]>
Entity Management
getEntityById
Get an entity by its ID.
await runtime.getEntityById(entityId: UUID): Promise<Entity | null>
createEntity
Create a new entity.
await runtime.createEntity(entity: Entity): Promise<boolean>
ensureConnection
Ensure all necessary entities, rooms, and relationships exist for a connection.
await runtime.ensureConnection(
entityId: UUID,
roomId: UUID,
userName?: string,
name?: string,
source?: string,
worldId?: UUID,
channelId?: string,
messageServerId?: string,
type?: ChannelType,
worldName?: string,
metadata?: Record<string, unknown>
): Promise<void>
Run Management
startRun
Start a new run for tracking prompts and model calls.
const runId = runtime.startRun(roomId?: UUID): UUID
endRun
End the current run.
getCurrentRunId
Get the current run ID (creates one if needed).
runtime.getCurrentRunId(): UUID
Lifecycle
stop
Stop the runtime and clean up resources.
await runtime.stop(): Promise<void>
Example Usage
import { AgentRuntime } from "@elizaos/core";
import { sqlitePlugin } from "@elizaos/plugin-sql";
// Create and initialize runtime
const runtime = new AgentRuntime({
character: {
name: "MyAgent",
bio: ["A helpful assistant"],
templates: {},
messageExamples: [],
postExamples: [],
topics: [],
adjectives: [],
knowledge: [],
plugins: [],
secrets: {}
},
plugins: [sqlitePlugin],
logLevel: "info",
actionPlanning: true
});
await runtime.initialize();
// Register custom action
runtime.registerAction({
name: "GREET_USER",
description: "Greet the user warmly",
handler: async (runtime, message, state) => {
return {
success: true,
text: `Hello, ${message.content.text}!`
};
},
validate: async () => true
});
// Use the runtime
const state = await runtime.composeState(message);
const apiKey = runtime.getSetting("OPENAI_API_KEY");
// Clean up
await runtime.stop();