Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add JSDoc documentation for full repository #1

Merged
merged 51 commits into from
Jan 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
4f1012d
docs: Add JSDoc documentation to actions.ts
madjin Dec 29, 2024
fbee0dd
docs: Add JSDoc documentation to cache.ts
madjin Dec 29, 2024
eeb9ed8
docs: Add JSDoc documentation to config.ts
madjin Dec 29, 2024
23860e6
docs: Add JSDoc documentation to context.ts
madjin Dec 29, 2024
d30f2a3
docs: Add JSDoc documentation to CircuitBreaker.ts
madjin Dec 29, 2024
41236ab
docs: Add JSDoc documentation to database.ts
madjin Dec 29, 2024
e2cf793
docs: Add JSDoc documentation to defaultCharacter.ts
madjin Dec 29, 2024
769b87a
docs: Add JSDoc documentation to embedding.ts
madjin Dec 29, 2024
ba7a59c
docs: Add JSDoc documentation to environment.ts
madjin Dec 29, 2024
c128ccc
docs: Add JSDoc documentation to evaluators.ts
madjin Dec 29, 2024
e674843
docs: Add JSDoc documentation to generation.ts
madjin Dec 29, 2024
ebe848a
docs: Add JSDoc documentation to goals.ts
madjin Dec 29, 2024
5470bd4
docs: Add JSDoc documentation to index.ts
madjin Dec 29, 2024
b81a81c
docs: Add JSDoc documentation to knowledge.ts
madjin Dec 29, 2024
e57b5a9
docs: Add JSDoc documentation to logger.ts
madjin Dec 29, 2024
330ed8c
docs: Add JSDoc documentation to memory.ts
madjin Dec 29, 2024
68f171f
docs: Add JSDoc documentation to messages.ts
madjin Dec 29, 2024
4cf530b
docs: Add JSDoc documentation to models.ts
madjin Dec 29, 2024
021dca2
docs: Add JSDoc documentation to parsing.ts
madjin Dec 29, 2024
df12040
docs: Add JSDoc documentation to posts.ts
madjin Dec 29, 2024
6d8772d
docs: Add JSDoc documentation to providers.ts
madjin Dec 29, 2024
204448a
docs: Add JSDoc documentation to relationships.ts
madjin Dec 29, 2024
d53f2f1
docs: Add JSDoc documentation to runtime.ts
madjin Dec 29, 2024
94b0cfb
docs: Add JSDoc documentation to settings.ts
madjin Dec 29, 2024
6f1a695
docs: Add JSDoc documentation to constants.ts
madjin Dec 29, 2024
7051991
docs: Add JSDoc documentation to createRuntime.ts
madjin Dec 29, 2024
d878435
docs: Add JSDoc documentation to testSetup.ts
madjin Dec 29, 2024
13a89d6
docs: Add JSDoc documentation to types.ts
madjin Dec 29, 2024
1a43575
docs: Add JSDoc documentation to actions.test.ts
madjin Dec 29, 2024
053e421
docs: Add JSDoc documentation to cache.test.ts
madjin Dec 29, 2024
f25c10b
docs: Add JSDoc documentation to context.test.ts
madjin Dec 29, 2024
06462f9
docs: Add JSDoc documentation to database.test.ts
madjin Dec 29, 2024
e1e1611
docs: Add JSDoc documentation to defaultCharacters.test.ts
madjin Dec 29, 2024
2f26fbb
docs: Add JSDoc documentation to env.test.ts
madjin Dec 29, 2024
7b99256
docs: Add JSDoc documentation to environment.test.ts
madjin Dec 29, 2024
86ead6f
docs: Add JSDoc documentation to evaluators.test.ts
madjin Dec 29, 2024
53e823b
docs: Add JSDoc documentation to generation.test.ts
madjin Dec 29, 2024
66b8c3f
docs: Add JSDoc documentation to goals.test.ts
madjin Dec 29, 2024
b6c8216
docs: Add JSDoc documentation to knowledge.test.ts
madjin Dec 29, 2024
2d9bd2a
docs: Add JSDoc documentation to messages.test.ts
madjin Dec 29, 2024
2a7f8d0
docs: Add JSDoc documentation to models.test.ts
madjin Dec 29, 2024
6bfda0f
docs: Add JSDoc documentation to parsing.test.ts
madjin Dec 29, 2024
da215a7
docs: Add JSDoc documentation to posts.test.ts
madjin Dec 29, 2024
480e7e5
docs: Add JSDoc documentation to providers.test.ts
madjin Dec 29, 2024
1f4a9fd
docs: Add JSDoc documentation to relationships.test.ts
madjin Dec 29, 2024
ccbe57b
docs: Add JSDoc documentation to runtime.test.ts
madjin Dec 29, 2024
8e9bc3a
docs: Add JSDoc documentation to videoGeneration.test.ts
madjin Dec 29, 2024
f213d48
docs: Add JSDoc documentation to types.ts
madjin Dec 29, 2024
9134d3c
docs: Add JSDoc documentation to utils.ts
madjin Dec 29, 2024
3b33f2f
docs: Add JSDoc documentation to uuid.ts
madjin Dec 29, 2024
817b0ae
fix mistakes, update with cleaner script
madjin Jan 2, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions packages/core/src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,80 @@ import type {
UUID,
} from "./types";

/**
* Interface for defining a cache adapter that can get, set, and delete key-value pairs.
* @interface
*/
export interface ICacheAdapter {
get(key: string): Promise<string | undefined>;
set(key: string, value: string): Promise<void>;
delete(key: string): Promise<void>;
}

/**
* Memory cache adapter class that implements the ICacheAdapter interface.
*/

export class MemoryCacheAdapter implements ICacheAdapter {
data: Map<string, string>;

/**
* Constructor for creating an instance of the class with optional initial data.
* @param {Map<string, string>} [initalData] - The initial data to initialize the instance with.
*/
constructor(initalData?: Map<string, string>) {
this.data = initalData ?? new Map<string, string>();
}

/**
* Retrieves the value stored in the data structure with the specified key.
*
* @param {string} key - The key to lookup in the data structure.
* @returns {Promise<string | undefined>} The value associated with the specified key, or undefined if the key is not found.
*/
async get(key: string): Promise<string | undefined> {
return this.data.get(key);
}

/**
* Sets a key-value pair in the data store.
*
* @param {string} key - The key for the data entry.
* @param {string} value - The value to store.
* @returns {Promise<void>}
*/
async set(key: string, value: string): Promise<void> {
this.data.set(key, value);
}

/**
* Asynchronously deletes the value associated with the given key from the data.
*
* @param {string} key - The key of the value to be deleted.
* @returns {Promise<void>} A promise that resolves once the value is deleted.
*/
async delete(key: string): Promise<void> {
this.data.delete(key);
}
}

/**
* Class representing a file system cache adapter.
* Implements the ICacheAdapter interface.
*/

export class FsCacheAdapter implements ICacheAdapter {
/**
* Constructor for creating an instance with a specified data directory.
* @param {string} dataDir - The directory where data will be stored.
*/
constructor(private dataDir: string) {}

/**
* Asynchronously retrieves the value associated with the given key from the file system.
* @param {string} key - The key used to fetch the value.
* @returns {Promise<string | undefined>} The value associated with the key, or undefined if an error occurs.
*/
async get(key: string): Promise<string | undefined> {
try {
return await fs.readFile(path.join(this.dataDir, key), "utf8");
Expand All @@ -45,6 +90,13 @@ export class FsCacheAdapter implements ICacheAdapter {
}
}

/**
* Asynchronously sets a key-value pair in the data directory.
*
* @param {string} key - The key of the data to be set.
* @param {string} value - The value of the data to be set.
* @returns {Promise<void>} A Promise that resolves once the key-value pair is successfully set.
*/
async set(key: string, value: string): Promise<void> {
try {
const filePath = path.join(this.dataDir, key);
Expand All @@ -56,6 +108,11 @@ export class FsCacheAdapter implements ICacheAdapter {
}
}

/**
* Deletes a file from the data directory using the given key.
* @param {string} key - The key to identify the file to be deleted.
* @returns {Promise<void>} A Promise that resolves once the file is deleted.
*/
async delete(key: string): Promise<void> {
try {
const filePath = path.join(this.dataDir, key);
Expand All @@ -66,34 +123,75 @@ export class FsCacheAdapter implements ICacheAdapter {
}
}

/**
* A class representing a cache adapter that interacts with a database cache.
* @implements {ICacheAdapter}
*/

export class DbCacheAdapter implements ICacheAdapter {
/**
* Constructor for creating a new instance of a class.
* @param {IDatabaseCacheAdapter} db - The database cache adapter used for data storage.
* @param {UUID} agentId - The unique identifier for the agent.
*/
constructor(
private db: IDatabaseCacheAdapter,
private agentId: UUID
) {}

/**
* Retrieves a value from cache based on the provided key.
* @param {string} key - The key to search for in the cache.
* @returns {Promise<string | undefined>} The value associated with the key, or undefined if not found.
*/
async get(key: string): Promise<string | undefined> {
return this.db.getCache({ agentId: this.agentId, key });
}

/**
* Asynchronously sets a key-value pair in the cache for the current agent.
*
* @param {string} key - The key to set in the cache.
* @param {string} value - The value to associate with the key in the cache.
* @returns {Promise<void>} A Promise that resolves when the key-value pair has been successfully set in the cache.
*/
async set(key: string, value: string): Promise<void> {
await this.db.setCache({ agentId: this.agentId, key, value });
}

/**
* Deletes a cache entry with the specified key.
* @param {string} key - The key of the cache entry to be deleted.
* @returns {Promise<void>} A Promise that resolves once the cache entry is deleted.
*/
async delete(key: string): Promise<void> {
await this.db.deleteCache({ agentId: this.agentId, key });
}
}

/**
* A class representing a Cache Manager.
*/
export class CacheManager<CacheAdapter extends ICacheAdapter = ICacheAdapter>
implements ICacheManager
{
adapter: CacheAdapter;

/**
* Constructor for creating an instance of the class, with a specified cache adapter.
* @param {CacheAdapter} adapter - The cache adapter to be used by the instance.
*/
constructor(adapter: CacheAdapter) {
this.adapter = adapter;
}

/**
* Asynchronously retrieves a value from the cache based on the provided key.
*
* @template T - The type of value being retrieved from the cache.
* @param {string} key - The key to look up in the cache.
* @returns {Promise<T | undefined>} A promise that resolves to the value associated with the key, or undefined if the key is not found or the value has expired.
*/
async get<T = unknown>(key: string): Promise<T | undefined> {
const data = await this.adapter.get(key);

Expand All @@ -113,13 +211,26 @@ export class CacheManager<CacheAdapter extends ICacheAdapter = ICacheAdapter>
return undefined;
}

/**
* Set a key-value pair in the cache with optional expiration time.
* @param {string} key - The key to set the value for.
* @param {T} value - The value to store in the cache.
* @param {CacheOptions} [opts] - Optional additional options for caching.
* @returns {Promise<void>} - A Promise that resolves when the value is set in the cache.
*/
async set<T>(key: string, value: T, opts?: CacheOptions): Promise<void> {
return this.adapter.set(
key,
JSON.stringify({ value, expires: opts?.expires ?? 0 })
);
}

/**
* Asynchronously deletes a key from the storage adapter.
*
* @param {string} key - The key to be deleted.
* @returns {Promise<void>} A Promise that resolves once the key is successfully deleted.
*/
async delete(key: string): Promise<void> {
return this.adapter.delete(key);
}
Expand Down
6 changes: 6 additions & 0 deletions packages/core/src/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ import { elizaLogger } from "./logger";
* An abstract class representing a database adapter for managing various entities
* like accounts, memories, actors, goals, and rooms.
*/
/**
* Database adapter interface for interacting with a database.
* Contains methods for database operations like account retrieval, memory management, goal manipulation, and room management.
* Implements circuit breaker pattern for fault tolerance.
* @interface
*/
export abstract class DatabaseAdapter<DB = any> implements IDatabaseAdapter {
/**
* The database instance.
Expand Down
33 changes: 33 additions & 0 deletions packages/core/src/database/CircuitBreaker.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
/**
* Defines a type representing the state of a circuit breaker.
* Possible values are "CLOSED", "OPEN", or "HALF_OPEN".
*/
export type CircuitBreakerState = "CLOSED" | "OPEN" | "HALF_OPEN";

/**
* Represents a Circuit Breaker that can monitor the status of a system and prevent overload.
* @class
*/
export class CircuitBreaker {
private state: CircuitBreakerState = "CLOSED";
private failureCount: number = 0;
Expand All @@ -10,6 +18,13 @@ export class CircuitBreaker {
private readonly resetTimeout: number;
private readonly halfOpenMaxAttempts: number;

/**
* Constructor for the Circuit Breaker class.
* @param {Object} config - Configuration object with optional properties:
* @param {number} [config.failureThreshold] - Number of failures allowed before opening the circuit.
* @param {number} [config.resetTimeout] - Time in milliseconds before attempting to half-open the circuit.
* @param {number} [config.halfOpenMaxAttempts] - Maximum number of attempts in half-open state.
*/
constructor(
private readonly config: {
failureThreshold?: number;
Expand All @@ -22,6 +37,13 @@ export class CircuitBreaker {
this.halfOpenMaxAttempts = config.halfOpenMaxAttempts ?? 3;
}

/**
* Executes the provided asynchronous operation while respecting the state of the circuit breaker.
* If the circuit breaker is OPEN, it will transition to HALF_OPEN after a specified resetTimeout.
* Counts successful operation calls in the HALF_OPEN state and resets the circuit breaker if a maximum number of attempts is reached.
* @param {() => Promise<T>} operation - The asynchronous operation to execute.
* @returns {Promise<T>} A Promise that resolves with the result of the operation.
*/
async execute<T>(operation: () => Promise<T>): Promise<T> {
if (this.state === "OPEN") {
if (Date.now() - (this.lastFailureTime || 0) > this.resetTimeout) {
Expand Down Expand Up @@ -49,6 +71,10 @@ export class CircuitBreaker {
}
}

/**
* Increments the failure count and updates the last failure time.
* If the failure count exceeds the failure threshold, changes the state to "OPEN".
*/
private handleFailure(): void {
this.failureCount++;
this.lastFailureTime = Date.now();
Expand All @@ -58,12 +84,19 @@ export class CircuitBreaker {
}
}

/**
* Resets the state to 'CLOSED', sets the failure count to 0, and clears the last failure time.
*/
private reset(): void {
this.state = "CLOSED";
this.failureCount = 0;
this.lastFailureTime = undefined;
}

/**
* Get the current state of the object.
* @returns {"CLOSED" | "OPEN" | "HALF_OPEN"} The state of the object, which can be "CLOSED", "OPEN", or "HALF_OPEN".
*/
getState(): "CLOSED" | "OPEN" | "HALF_OPEN" {
return this.state;
}
Expand Down
45 changes: 45 additions & 0 deletions packages/core/src/embedding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@ import { IAgentRuntime, ModelProviderName } from "./types.ts";
import settings from "./settings.ts";
import elizaLogger from "./logger.ts";

/**
* Interface for embedding options.
*
* @typedef {Object} EmbeddingOptions
* @property {string} model - The name of the model to use for embedding.
* @property {string} endpoint - The API endpoint to use for embedding.
* @property {string} [apiKey] - Optional API key for authentication.
* @property {number} [length] - Optional length parameter for embedding.
* @property {boolean} [isOllama] - Optional flag for indicating if Ollama should be used.
* @property {number} [dimensions] - Optional number of dimensions for embedding.
* @property {string} [provider] - Optional provider for embedding.
*/
interface EmbeddingOptions {
model: string;
endpoint: string;
Expand All @@ -21,9 +33,19 @@ export const EmbeddingProvider = {
BGE: "BGE",
} as const;

/**
* Type definition for embedding provider type.
*/
export type EmbeddingProviderType =
(typeof EmbeddingProvider)[keyof typeof EmbeddingProvider];

/**
* Represents the configuration for an embedding, specifying the dimensions, model, and provider.
* @typedef {Object} EmbeddingConfig
* @property {number} dimensions - The number of dimensions in the embedding.
* @property {string} model - The specific model being used for the embedding.
* @property {EmbeddingProviderType} provider - The type of provider supplying the embedding.
*/
export type EmbeddingConfig = {
readonly dimensions: number;
readonly model: string;
Expand Down Expand Up @@ -57,6 +79,12 @@ export const getEmbeddingConfig = (): EmbeddingConfig => ({
: "BGE",
});

/**
* Fetches remote embeddings for the given input using the specified options.
* @param {string} input - The input text to generate embeddings for.
* @param {EmbeddingOptions} options - The options object containing endpoint, apiKey, model, dimensions, length, and isOllama.
* @returns {Promise<number[]>} - A promise that resolves to an array of numbers representing the embeddings.
*/
async function getRemoteEmbedding(
input: string,
options: EmbeddingOptions
Expand Down Expand Up @@ -111,6 +139,11 @@ async function getRemoteEmbedding(
}
}

/**
* Determines the embedding type based on the runtime environment and configuration settings.
* @param {IAgentRuntime} runtime - The runtime information for the agent.
* @returns {"local" | "remote"} - The type of embedding to use: "local" for Node.js or custom embeddings, "remote" for OpenAI embeddings.
*/
export function getEmbeddingType(runtime: IAgentRuntime): "local" | "remote" {
const isNode =
typeof process !== "undefined" &&
Expand All @@ -130,6 +163,10 @@ export function getEmbeddingType(runtime: IAgentRuntime): "local" | "remote" {
return isLocal ? "local" : "remote";
}

/**
* Retrieves a zero vector for embeddings based on the configured embedding dimension.
* @returns {number[]} A zero vector with the specified embedding dimension filled with zeros.
*/
export function getEmbeddingZeroVector(): number[] {
let embeddingDimension = 384; // Default BGE dimension

Expand Down Expand Up @@ -157,6 +194,14 @@ export function getEmbeddingZeroVector(): number[] {
* @throws {Error} If the API request fails
*/

/**
* Embeds the provided input string using the specified provider and model.
*
* @async
* @param {IAgentRuntime} runtime - The agent runtime object.
* @param {string} input - The input string to embed.
* @returns {Promise<number[]>} The embedding array for the input string.
*/
export async function embed(runtime: IAgentRuntime, input: string) {
elizaLogger.debug("Embedding request:", {
modelProvider: runtime.character.modelProvider,
Expand Down
Loading
Loading