UNPKG

@hashgraphonline/conversational-agent

Version:

Hashgraph Online conversational AI agent implementing HCS-10 communication, HCS-2 registries, and content inscription on Hedera

245 lines (243 loc) 8.73 kB
import { BaseMessage } from '@langchain/core/messages'; import { ContentStorage } from './ContentStorage'; /** * Entity association for storing blockchain entity contexts */ export interface EntityAssociation { /** The blockchain entity ID (e.g., tokenId, accountId, topicId) */ entityId: string; /** User-provided or derived friendly name */ entityName: string; /** Type of entity (token, account, topic, schedule, etc.) */ entityType: string; /** When the entity was created/associated */ createdAt: Date; /** Transaction ID that created this entity */ transactionId?: string; } /** * Options for resolving entity references */ export interface EntityResolutionOptions { /** Filter by specific entity type */ entityType?: string; /** Maximum number of results to return */ limit?: number; /** Whether to use fuzzy matching for natural language queries */ fuzzyMatch?: boolean; } /** * Configuration for SmartMemoryManager */ export interface SmartMemoryConfig { /** Maximum tokens for active memory window */ maxTokens?: number; /** Reserve tokens for response generation */ reserveTokens?: number; /** Model name for token counting */ modelName?: string; /** Maximum messages to store in content storage */ storageLimit?: number; } /** * Search options for history search */ export interface SearchOptions { /** Whether to perform case-sensitive search */ caseSensitive?: boolean; /** Maximum number of results to return */ limit?: number; /** Whether to use regex pattern matching */ useRegex?: boolean; } /** * Memory statistics for active memory window */ export interface MemoryStats { /** Total active messages in memory window */ totalActiveMessages: number; /** Current token count including system prompt */ currentTokenCount: number; /** Maximum token capacity */ maxTokens: number; /** Remaining token capacity */ remainingCapacity: number; /** System prompt token count */ systemPromptTokens: number; /** Memory usage percentage */ usagePercentage: number; } /** * TODO: investigate using chroma / rag for long term memory * Smart memory manager that combines active memory window with long-term storage * Provides context-aware memory management with automatic pruning and searchable history */ export declare class SmartMemoryManager { private memoryWindow; private _contentStorage; private tokenCounter; private config; private static readonly DEFAULT_CONFIG; constructor(config?: SmartMemoryConfig); /** * Get the content storage instance for file/content reference operations * @returns ContentStorage instance */ get contentStorage(): ContentStorage; /** * Add a message to the active memory window * Automatically handles pruning and storage of displaced messages * @param message - Message to add */ addMessage(message: BaseMessage): void; /** * Get all active messages from the memory window * @returns Array of active messages in chronological order */ getMessages(): BaseMessage[]; /** * Clear active memory window * @param clearStorage - Whether to also clear the content storage (default: false) */ clear(clearStorage?: boolean): void; /** * Set the system prompt for the memory window * @param systemPrompt - System prompt text */ setSystemPrompt(systemPrompt: string): void; /** * Get the current system prompt * @returns Current system prompt text */ getSystemPrompt(): string; /** * Search through stored message history * @param query - Search term or pattern * @param options - Search configuration * @returns Array of matching messages from history */ searchHistory(query: string, options?: SearchOptions): BaseMessage[]; /** * Get recent messages from storage history * @param count - Number of recent messages to retrieve * @returns Array of recent messages from storage */ getRecentHistory(count: number): BaseMessage[]; /** * Check if a message can be added without exceeding limits * @param message - Message to test * @returns True if message can be added */ canAddMessage(message: BaseMessage): boolean; /** * Get statistics about the active memory window * @returns Memory usage statistics */ getMemoryStats(): MemoryStats; /** * Get statistics about the content storage * @returns Storage usage statistics */ getStorageStats(): ReturnType<ContentStorage['getStorageStats']>; /** * Get combined statistics for both active memory and storage * @returns Combined memory and storage statistics */ getOverallStats(): { activeMemory: MemoryStats; storage: ReturnType<ContentStorage['getStorageStats']>; totalMessagesManaged: number; activeMemoryUtilization: number; storageUtilization: number; }; /** * Update the configuration and apply changes * @param newConfig - New configuration options */ updateConfig(newConfig: Partial<SmartMemoryConfig>): void; /** * Get current configuration * @returns Current configuration settings */ getConfig(): Required<SmartMemoryConfig>; /** * Get messages from storage within a time range * @param startTime - Start of time range * @param endTime - End of time range * @returns Messages within the specified time range */ getHistoryFromTimeRange(startTime: Date, endTime: Date): BaseMessage[]; /** * Get messages from storage by message type * @param messageType - Type of messages to retrieve ('human', 'ai', 'system', etc.) * @param limit - Maximum number of messages to return * @returns Messages of the specified type */ getHistoryByType(messageType: string, limit?: number): BaseMessage[]; /** * Get recent messages from storage within the last N minutes * @param minutes - Number of minutes to look back * @returns Messages from the last N minutes */ getRecentHistoryByTime(minutes: number): BaseMessage[]; /** * Export the current state for persistence or analysis * @returns Serializable representation of memory state */ exportState(): { config: Required<SmartMemoryConfig>; activeMessages: Array<{ content: unknown; type: string; }>; systemPrompt: string; memoryStats: MemoryStats; storageStats: ReturnType<ContentStorage['getStorageStats']>; storedMessages: ReturnType<ContentStorage['exportMessages']>; }; /** * Get a summary of conversation context for external use * Useful for providing context to other systems or for logging * @param includeStoredContext - Whether to include recent stored messages * @returns Context summary object */ getContextSummary(includeStoredContext?: boolean): { activeMessageCount: number; systemPrompt: string; recentMessages: BaseMessage[]; memoryUtilization: number; hasStoredHistory: boolean; recentStoredMessages?: BaseMessage[]; storageStats?: ReturnType<ContentStorage['getStorageStats']>; }; /** * Perform maintenance operations * Optimizes storage and cleans up resources */ performMaintenance(): void; /** * Store an entity association for later resolution * @param entityId - The blockchain entity ID * @param entityName - User-provided or derived friendly name * @param entityType - Type of entity (token, account, topic, etc.) * @param transactionId - Optional transaction ID that created this entity */ storeEntityAssociation(entityId: string, entityName: string, entityType: string, transactionId?: string): void; /** * Resolve entity references from natural language queries * @param query - Search query (entity name or natural language reference) * @param options - Resolution options for filtering and fuzzy matching * @returns Array of matching entity associations */ resolveEntityReference(query: string, options?: EntityResolutionOptions): EntityAssociation[]; /** * Get all entity associations, optionally filtered by type * @param entityType - Optional filter by entity type * @returns Array of entity associations */ getEntityAssociations(entityType?: string): EntityAssociation[]; /** * Clean up resources and dispose of components */ dispose(): void; }