@elizaos/core 1.0.0-beta.8 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,233 @@
1
+ # @elizaos/core
2
+
3
+ ## Overview
4
+
5
+ The `@elizaos/core` package provides a robust foundation for building AI agents with dynamic interaction capabilities. It enables agents to manage entities, memories, and context, and to interact with external systems, going beyond simple message responses to handle complex scenarios and execute tasks effectively.
6
+
7
+ ## Key Features
8
+
9
+ - **AgentRuntime:** Central orchestrator for managing agent lifecycle, plugins, and interactions.
10
+ - **Actions:** Define tasks the agent can perform, with validation and execution logic.
11
+ - **Providers:** Supply real-time data and context to the agent, enabling interaction with dynamic environments and external APIs.
12
+ - **Evaluators:** Process conversation data to extract insights, build long-term memory, and maintain contextual awareness.
13
+ - **Plugin System:** Extensible architecture allowing for modular addition of functionalities.
14
+ - **Entity and Memory Management:** Core support for tracking entities and their associated information.
15
+
16
+ ## Installation
17
+
18
+ 1. Add `@elizaos/core` to your `agent/package.json` dependencies:
19
+
20
+ ```json
21
+ {
22
+ "dependencies": {
23
+ "@elizaos/core": "workspace:*"
24
+ }
25
+ }
26
+ ```
27
+
28
+ 2. Navigate to your `agent/` directory.
29
+ 3. Install dependencies:
30
+ ```bash
31
+ bun install
32
+ ```
33
+ 4. Build your project:
34
+ ```bash
35
+ bun run build
36
+ ```
37
+
38
+ ## Configuration
39
+
40
+ The following environment variables are used by `@elizaos/core`. Configure them in a `.env` file at your project root.
41
+
42
+ - `LOG_LEVEL`: Logging verbosity (e.g., 'debug', 'info', 'error').
43
+ - `LOG_DIAGNOSTIC`: Enable/disable diagnostic logging (`true`/`false`).
44
+ - `LOG_JSON_FORMAT`: Output logs in JSON format (`true`/`false`).
45
+ - `DEFAULT_LOG_LEVEL`: Default log level if not in debug mode.
46
+ - `SECRET_SALT`: Secret salt for encryption purposes.
47
+ - `SENTRY_DSN`: Sentry DSN for error reporting.
48
+ - `SENTRY_ENVIRONMENT`: Sentry deployment environment (e.g., 'production', 'staging').
49
+ - `SENTRY_TRACES_SAMPLE_RATE`: Sentry performance tracing sample rate (0.0 - 1.0).
50
+ - `SENTRY_SEND_DEFAULT_PII`: Send Personally Identifiable Information to Sentry (`true`/`false`).
51
+
52
+ **Example `.env`:**
53
+
54
+ ```plaintext
55
+ LOG_LEVEL=debug
56
+ LOG_DIAGNOSTIC=true
57
+ LOG_JSON_FORMAT=false
58
+ DEFAULT_LOG_LEVEL=info
59
+ SECRET_SALT=yourSecretSaltHere
60
+ SENTRY_DSN=yourSentryDsnHere
61
+ SENTRY_ENVIRONMENT=development
62
+ SENTRY_TRACES_SAMPLE_RATE=1.0
63
+ SENTRY_SEND_DEFAULT_PII=true
64
+ ```
65
+
66
+ **Note:** Add your `.env` file to `.gitignore` to protect sensitive information.
67
+
68
+ ## Core Architecture
69
+
70
+ `@elizaos/core` is built around a few key concepts that work together within the `AgentRuntime`.
71
+
72
+ ### AgentRuntime
73
+
74
+ The `AgentRuntime` is the heart of the system. It manages the agent's lifecycle, loads plugins, orchestrates interactions, and provides a central point for actions, providers, and evaluators to operate. It's typically initialized with a set of plugins, including the `corePlugin` which provides foundational capabilities.
75
+
76
+ ### Actions
77
+
78
+ Actions define specific tasks or capabilities the agent can perform. Each action typically includes:
79
+
80
+ - A unique `name`.
81
+ - A `description` explaining its purpose and when it should be triggered.
82
+ - A `validate` function to determine if the action is applicable in a given context.
83
+ - A `handler` function that executes the action's logic.
84
+
85
+ Actions enable the agent to respond intelligently and perform operations based on user input or internal triggers.
86
+
87
+ ### Providers
88
+
89
+ Providers are responsible for supplying data and context to the `AgentRuntime` and its components. They can:
90
+
91
+ - Fetch data from external APIs or databases.
92
+ - Provide real-time information about the environment.
93
+ - Offer access to external services or tools.
94
+
95
+ This allows the agent to operate with up-to-date and relevant information.
96
+
97
+ ### Evaluators
98
+
99
+ Evaluators analyze conversation data and other inputs to extract meaningful information, build the agent's memory, and maintain contextual awareness. They help the agent:
100
+
101
+ - Understand user intent.
102
+ - Extract facts and relationships.
103
+ - Reflect on past interactions to improve future responses.
104
+ - Update the agent's knowledge base.
105
+
106
+ ## Getting Started
107
+
108
+ ### Initializing with `corePlugin`
109
+
110
+ The `corePlugin` bundles essential actions, providers, and evaluators from `@elizaos/core`. To use it, add it to the `AgentRuntime` during initialization:
111
+
112
+ ```typescript
113
+ import { AgentRuntime, corePlugin } from '@elizaos/core';
114
+
115
+ const agentRuntime = new AgentRuntime({
116
+ plugins: [
117
+ corePlugin,
118
+ // You can add other custom or third-party plugins here
119
+ ],
120
+ // Other AgentRuntime configurations can be specified here
121
+ });
122
+
123
+ // After initialization, agentRuntime is ready to be used.
124
+ // You should see console messages like "✓ Registering action: <plugin actions>"
125
+ // indicating successful plugin registration.
126
+ ```
127
+
128
+ ### Example: Defining a Custom Action (Conceptual)
129
+
130
+ While `corePlugin` provides many actions, you might need to define custom actions for specific agent behaviors. Here's a conceptual outline:
131
+
132
+ ```typescript
133
+ // myCustomAction.ts
134
+ // (This is a simplified conceptual example)
135
+
136
+ export const myCustomAction = {
137
+ name: 'customGreet',
138
+ description: 'Greets a user in a special way.',
139
+ validate: async ({ context }) => {
140
+ // Logic to determine if this action should run
141
+ // e.g., return context.message.text.includes('special hello');
142
+ return true; // Placeholder
143
+ },
144
+ handler: async ({ runtime, context }) => {
145
+ // Logic to execute the action
146
+ // e.g., runtime.sendMessage(context.roomId, "A very special hello to you!");
147
+ console.log('Custom Greet action executed!');
148
+ return { success: true, message: 'Custom greeting sent.' };
149
+ },
150
+ };
151
+
152
+ // Then, this action would be registered with the AgentRuntime, typically via a custom plugin.
153
+ ```
154
+
155
+ For detailed instructions on creating and registering plugins and actions, refer to the specific documentation or examples within the codebase.
156
+
157
+ ## Development & Testing
158
+
159
+ ### Running Tests
160
+
161
+ The `@elizaos/core` package uses **Vitest** for testing.
162
+
163
+ 1. **Prerequisites**:
164
+
165
+ - Ensure `bun` is installed (`npm install -g bun`).
166
+ - Environment variables in `.env` (as described in Configuration) are generally **not required** for most core tests but might be for specific integration tests if any.
167
+
168
+ 2. **Setup**:
169
+
170
+ - Navigate to the `packages/core` directory: `cd packages/core`
171
+ - Install dependencies: `bun install`
172
+
173
+ 3. **Execute Tests**:
174
+ ```bash
175
+ bun test
176
+ ```
177
+ Test results will be displayed in the terminal.
178
+
179
+ ### TODO Items
180
+
181
+ The following improvements and features are planned for `@elizaos/core`:
182
+
183
+ - **Feature**: Add ability for plugins to register their sources (Context: Exporting a default `sendMessageAction`).
184
+ - **Enhancement**: Improve formatting of posts (Context: Returning formatted posts joined by a newline).
185
+ - **Bug**: Resolve server ID creation/retrieval issues (Context: Creating a room with specific world, name, and server IDs).
186
+ - **Enhancement**: Refactor message sending logic to an `ensureConnection` approach (Context: Sending messages to room participants).
187
+
188
+ ## Troubleshooting & FAQ
189
+
190
+ ### Common Issues
191
+
192
+ - **AgentRuntime not responding to triggers**:
193
+
194
+ - **Cause**: Improperly defined action `validate` functions or handlers. Trigger conditions might not be met.
195
+ - **Solution**: Verify `validate` functions correctly identify trigger conditions. Ensure `handler` functions execute as intended. Check console logs for errors during validation/handling.
196
+
197
+ - **Provider data is outdated/incorrect**:
198
+
199
+ - **Cause**: Issues with external data source integration or API failures.
200
+ - **Solution**: Check API connections and ensure the provider's data fetching logic is accurate. Review network configurations if needed.
201
+
202
+ - **Evaluator fails to maintain context**:
203
+ - **Cause**: Evaluator not capturing necessary facts/relationships correctly.
204
+ - **Solution**: Review evaluator configuration. Ensure it uses correct data from `AgentRuntime` and is updated with the latest configuration for accurate context.
205
+
206
+ ### Frequently Asked Questions
207
+
208
+ - **Q: How do I define and use a new Action?**
209
+
210
+ - **A**: Define an action object with `name`, `description`, `validate`, and `handler` functions. Integrate it into `AgentRuntime` usually by creating a plugin that registers the action. Ensure the action's name and description clearly align with its task for proper triggering.
211
+
212
+ - **Q: My action is registered, but the agent is not calling it.**
213
+
214
+ - **A**: Double-check the action's `name` and `description` for clarity and relevance to the triggering conditions. Verify that the `validate` function correctly returns `true` (or a truthy value indicating applicability) under the desired conditions. Inspect logs for any errors or warnings related to your action.
215
+
216
+ - **Q: Can Providers access external API data?**
217
+
218
+ - **A**: Yes, Providers are designed to interact with external systems, including fetching data from external APIs. This enables the agent to use real-time, dynamic context.
219
+
220
+ - **Q: How do I extend the agent's evaluation capabilities?**
221
+
222
+ - **A**: Implement custom evaluators and integrate them with `AgentRuntime` (typically via a plugin). These can be tailored to extract specific information, enhancing the agent's memory and contextual understanding.
223
+
224
+ - **Q: How can I create a mock environment for testing?**
225
+ - **A**: The package may include mock adapters (e.g., `MockDatabaseAdapter` if it's part of core utilities) that simulate interactions (like database connections) without actual external dependencies, facilitating controlled testing.
226
+
227
+ ### Debugging Tips
228
+
229
+ - Utilize console logs (`LOG_LEVEL=debug`) for detailed error messages and execution flow during action validation and handler execution.
230
+ - Use mock classes/adapters where available to simulate environments and isolate functions for testing specific behaviors.
231
+ - Ensure `AgentRuntime` is loaded with the correct configurations and plugins.
232
+
233
+ ---
package/dist/actions.d.ts CHANGED
@@ -2,17 +2,11 @@ import type { Action } from './types';
2
2
  /**
3
3
  * Composes a set of example conversations based on provided actions and a specified count.
4
4
  * It randomly selects examples from the provided actions and formats them with generated names.
5
+ *
5
6
  * @param actionsData - An array of `Action` objects from which to draw examples.
6
7
  * @param count - The number of examples to generate.
7
8
  * @returns A string containing formatted examples of conversations.
8
9
  */
9
- /**
10
- * Compose a specified number of random action examples from the given actionsData.
11
- *
12
- * @param {Action[]} actionsData - The list of actions to generate examples from.
13
- * @param {number} count - The number of examples to compose.
14
- * @returns {string} The formatted action examples.
15
- */
16
10
  export declare const composeActionExamples: (actionsData: Action[], count: number) => string;
17
11
  /**
18
12
  * Formats the names of the provided actions into a comma-separated string.
@@ -21,7 +15,7 @@ export declare const composeActionExamples: (actionsData: Action[], count: numbe
21
15
  */
22
16
  export declare function formatActionNames(actions: Action[]): string;
23
17
  /**
24
- * Formats the provided actions into a detailed string listing each action's name and description, separated by commas and newlines.
18
+ * Formats the provided actions into a detailed string listing each action's name and description.
25
19
  * @param actions - An array of `Action` objects to format.
26
20
  * @returns A detailed string of actions, including names and descriptions.
27
21
  */
@@ -1,4 +1,6 @@
1
- import type { Agent, Component, Entity, IDatabaseAdapter, Log, Memory, Participant, Relationship, Room, Task, UUID, World, MemoryMetadata } from './types';
1
+ import type { Agent, Component, Entity, IDatabaseAdapter, Log, Memory, MemoryMetadata, Participant, Relationship, Room, Task, UUID, World } from './types';
2
+ import { type Pool as PgPool } from 'pg';
3
+ import { PGlite } from '@electric-sql/pglite';
2
4
  /**
3
5
  * An abstract class representing a database adapter for managing various entities
4
6
  * like entities, memories, entities, goals, and rooms.
@@ -8,7 +10,7 @@ import type { Agent, Component, Entity, IDatabaseAdapter, Log, Memory, Participa
8
10
  *
9
11
  * @template DB - The type of the database instance.
10
12
  * @abstract
11
- * @implements {IDatabaseAdapter}
13
+ * implements IDatabaseAdapter
12
14
  */
13
15
  export declare abstract class DatabaseAdapter<DB = unknown> implements IDatabaseAdapter {
14
16
  /**
@@ -25,19 +27,24 @@ export declare abstract class DatabaseAdapter<DB = unknown> implements IDatabase
25
27
  * @returns A Promise that resolves when closing is complete.
26
28
  */
27
29
  abstract close(): Promise<void>;
30
+ /**
31
+ * Retrieves a connection to the database.
32
+ * @returns A Promise that resolves to the database connection.
33
+ */
34
+ abstract getConnection(): Promise<PGlite | PgPool>;
28
35
  /**
29
36
  * Retrieves an account by its ID.
30
- * @param entityId The UUID of the user account to retrieve.
37
+ * @param entityIds The UUIDs of the user account to retrieve.
31
38
  * @returns A Promise that resolves to the Entity object or null if not found.
32
39
  */
33
- abstract getEntityById(entityId: UUID): Promise<Entity | null>;
40
+ abstract getEntityByIds(entityIds: UUID[]): Promise<Entity[] | null>;
34
41
  abstract getEntitiesForRoom(roomId: UUID, includeComponents?: boolean): Promise<Entity[]>;
35
42
  /**
36
- * Creates a new entity in the database.
37
- * @param entity The entity object to create.
43
+ * Creates a new entities in the database.
44
+ * @param entities The entity objects to create.
38
45
  * @returns A Promise that resolves when the account creation is complete.
39
46
  */
40
- abstract createEntity(entity: Entity): Promise<boolean>;
47
+ abstract createEntities(entities: Entity[]): Promise<boolean>;
41
48
  /**
42
49
  * Updates an existing entity in the database.
43
50
  * @param entity The entity object with updated properties.
@@ -87,12 +94,13 @@ export declare abstract class DatabaseAdapter<DB = unknown> implements IDatabase
87
94
  abstract getMemories(params: {
88
95
  entityId?: UUID;
89
96
  agentId?: UUID;
90
- roomId?: UUID;
91
97
  count?: number;
92
98
  unique?: boolean;
93
99
  tableName: string;
94
100
  start?: number;
95
101
  end?: number;
102
+ roomId?: UUID;
103
+ worldId?: UUID;
96
104
  }): Promise<Memory[]>;
97
105
  abstract getMemoriesByRoomIds(params: {
98
106
  roomIds: UUID[];
@@ -161,11 +169,14 @@ export declare abstract class DatabaseAdapter<DB = unknown> implements IDatabase
161
169
  */
162
170
  abstract searchMemories(params: {
163
171
  tableName: string;
164
- roomId: UUID;
165
172
  embedding: number[];
166
- match_threshold: number;
167
- count: number;
168
- unique: boolean;
173
+ match_threshold?: number;
174
+ count?: number;
175
+ unique?: boolean;
176
+ query?: string;
177
+ roomId?: UUID;
178
+ worldId?: UUID;
179
+ entityId?: UUID;
169
180
  }): Promise<Memory[]>;
170
181
  /**
171
182
  * Creates a new memory in the database.
@@ -239,19 +250,19 @@ export declare abstract class DatabaseAdapter<DB = unknown> implements IDatabase
239
250
  * @param roomId The UUID of the room to retrieve.
240
251
  * @returns A Promise that resolves to the room ID or null if not found.
241
252
  */
242
- abstract getRoom(roomId: UUID): Promise<Room | null>;
253
+ abstract getRoomsByIds(roomIds: UUID[]): Promise<Room[] | null>;
243
254
  /**
244
255
  * Retrieves all rooms for a given world.
245
256
  * @param worldId The UUID of the world to retrieve rooms for.
246
257
  * @returns A Promise that resolves to an array of Room objects.
247
258
  */
248
- abstract getRooms(worldId: UUID): Promise<Room[]>;
259
+ abstract getRoomsByWorld(worldId: UUID): Promise<Room[]>;
249
260
  /**
250
- * Creates a new room with an optional specified ID.
261
+ * Creates a new rooms with an optional specified ID.
251
262
  * @param roomId Optional UUID to assign to the new room.
252
- * @returns A Promise that resolves to the UUID of the created room.
263
+ * @returns A Promise that resolves to the UUID of the created rooms.
253
264
  */
254
- abstract createRoom({ id, source, type, channelId, serverId, worldId }: Room): Promise<UUID>;
265
+ abstract createRooms(rooms: Room[]): Promise<UUID[]>;
255
266
  /**
256
267
  * Updates a specific room in the database.
257
268
  * @param room The room object with updated properties.
@@ -277,12 +288,12 @@ export declare abstract class DatabaseAdapter<DB = unknown> implements IDatabase
277
288
  */
278
289
  abstract getRoomsForParticipants(userIds: UUID[]): Promise<UUID[]>;
279
290
  /**
280
- * Adds a user as a participant to a specific room.
281
- * @param entityId The UUID of the user to add as a participant.
291
+ * Adds users as a participant to a specific room.
292
+ * @param entityIds The UUIDs of the users to add as a participant.
282
293
  * @param roomId The UUID of the room to which the user will be added.
283
294
  * @returns A Promise that resolves to a boolean indicating success or failure.
284
295
  */
285
- abstract addParticipant(entityId: UUID, roomId: UUID): Promise<boolean>;
296
+ abstract addParticipantsRoom(entityIds: UUID[], roomId: UUID): Promise<boolean>;
286
297
  /**
287
298
  * Removes a user as a participant from a specific room.
288
299
  * @param entityId The UUID of the user to remove as a participant.
@@ -354,7 +365,7 @@ export declare abstract class DatabaseAdapter<DB = unknown> implements IDatabase
354
365
  * Retrieves all agents from the database.
355
366
  * @returns A Promise that resolves to an array of Agent objects.
356
367
  */
357
- abstract getAgents(): Promise<Agent[]>;
368
+ abstract getAgents(): Promise<Partial<Agent>[]>;
358
369
  /**
359
370
  * Creates a new agent in the database.
360
371
  * @param agent The agent object to create.
@@ -374,12 +385,6 @@ export declare abstract class DatabaseAdapter<DB = unknown> implements IDatabase
374
385
  * @returns A Promise that resolves to a boolean indicating success or failure of the deletion.
375
386
  */
376
387
  abstract deleteAgent(agentId: UUID): Promise<boolean>;
377
- /**
378
- * Ensures an agent exists in the database.
379
- * @param agent The agent object to ensure exists.
380
- * @returns A Promise that resolves when the agent has been ensured to exist.
381
- */
382
- abstract ensureAgentExists(agent: Partial<Agent>): Promise<void>;
383
388
  /**
384
389
  * Ensures an embedding dimension exists in the database.
385
390
  * @param dimension The dimension to ensure exists.
@@ -420,6 +425,7 @@ export declare abstract class DatabaseAdapter<DB = unknown> implements IDatabase
420
425
  abstract getTasks(params: {
421
426
  roomId?: UUID;
422
427
  tags?: string[];
428
+ entityId?: UUID;
423
429
  }): Promise<Task[]>;
424
430
  /**
425
431
  * Retrieves a specific task by its ID.
@@ -446,4 +452,10 @@ export declare abstract class DatabaseAdapter<DB = unknown> implements IDatabase
446
452
  * @returns Promise resolving when the deletion is complete
447
453
  */
448
454
  abstract deleteTask(id: UUID): Promise<void>;
455
+ abstract getMemoriesByWorldId(params: {
456
+ worldId: UUID;
457
+ count?: number;
458
+ tableName?: string;
459
+ }): Promise<Memory[]>;
460
+ abstract deleteRoomsByWorldId(worldId: UUID): Promise<void>;
449
461
  }
package/dist/index.d.ts CHANGED
@@ -2,11 +2,13 @@ export * from './types';
2
2
  export * from './actions';
3
3
  export * from './database';
4
4
  export * from './entities';
5
- export * from './import';
6
5
  export * from './logger';
7
6
  export * from './prompts';
8
7
  export * from './roles';
9
8
  export * from './runtime';
10
9
  export * from './settings';
11
- export * from './uuid';
12
- export * from './audioUtils';
10
+ export * from './utils';
11
+ export * from './services';
12
+ export * from './instrumentation/types';
13
+ export * from './instrumentation/service';
14
+ export * from './sentry/instrument';