Skip to main content

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;
})
conversationLength
number
Number of messages to retain in conversation context (default: 100)
agentId
UUID
Unique identifier for the agent. If not provided, generated from character name
character
Character
Character configuration defining the agent’s personality and behavior. If not provided, an anonymous character is created
plugins
Plugin[]
Array of plugins to register with the agent
adapter
IDatabaseAdapter
Database adapter for persistence. Required for production use
logLevel
string
default:"error"
Logging verbosity: “trace”, “debug”, “info”, “warn”, “error”, or “fatal”
actionPlanning
boolean
default:"true"
Enable multi-action execution. When false, agent executes only one action per response (performance optimization for games)
llmMode
string
default:"DEFAULT"
Override model selection: “DEFAULT” (use specified model), “SMALL” (force TEXT_SMALL), or “LARGE” (force TEXT_LARGE)
checkShouldRespond
boolean
default:"true"
Enable shouldRespond evaluation. When false, agent always responds (ChatGPT mode)
enableAutonomy
boolean
Enable autonomous operation with continuous thinking loop
sandboxMode
boolean
Enable secure secret isolation. Secrets become opaque tokens in the runtime

Core Properties

agentId
UUID
The unique identifier for this agent instance
character
Character
The character configuration defining agent behavior
actions
Action[]
Registered actions the agent can perform
evaluators
Evaluator[]
Registered evaluators for message assessment
providers
Provider[]
Registered providers for external data/services
plugins
Plugin[]
Registered plugins extending agent functionality
adapter
IDatabaseAdapter
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>
skipMigrations
boolean
Skip database migrations (for serverless mode)
allowNoDatabase
boolean
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>
plugin
Plugin
required
Plugin to register
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
Action
required
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
Evaluator
required
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>
blocked
boolean
If true, the message is blocked from processing
rewrittenText
string
Optional replacement text (sanitized/redacted version)
reason
string
Reason for blocking/rewriting

Provider Management

registerProvider

Register a provider for external data/services.
runtime.registerProvider(provider: Provider): void
provider
Provider
required
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
Memory
required
Message to compose state for
includeList
string[]
Provider names to include
onlyInclude
boolean
If true, only include providers in includeList
skipCache
boolean
Skip state cache lookup
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
key
string
required
Setting key to retrieve
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
key
string
required
Setting key
value
string | boolean | null
required
Setting value
secret
boolean
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
serviceName
ServiceTypeName
required
Service name to retrieve
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>
memory
Memory
required
Memory object to store
tableName
string
required
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.
runtime.endRun(): void

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();

Build docs developers (and LLMs) love