@astreus-ai/astreus
Version:
AI Agent Framework with Chat Management
1,284 lines (1,252 loc) • 45.5 kB
text/typescript
import { Knex } from 'knex';
/**
* Astreus AI - Logger Utility
* Provides colorful console logging functionality for the framework
*/
declare enum LogLevel {
DEBUG = 0,
INFO = 1,
SUCCESS = 2,
WARN = 3,
ERROR = 4,
NONE = 5
}
interface LoggerOptions {
level: LogLevel;
prefix: boolean;
colors: boolean;
lineBreak: boolean;
timestamp: boolean;
}
/**
* Configure the logger
*/
declare function configure(newOptions: Partial<LoggerOptions>): void;
/**
* Print the framework banner
*/
declare function printBanner(): void;
/**
* Public logging functions
*/
declare const logger: {
debug: (...messages: unknown[]) => void;
info: (...messages: unknown[]) => void;
success: (...messages: unknown[]) => void;
warn: (...messages: unknown[]) => void;
error: (...messages: unknown[]) => void;
task: (taskId: string, message: string, taskName?: string) => void;
agent: (agentName: string, message: string) => void;
database: (operation: string, message: string) => void;
memory: (operation: string, message: string) => void;
session: (sessionId: string, message: string) => void;
plugin: (pluginName: string, message: string) => void;
workflow: (workflowName: string, message: string) => void;
startProgress: (message: string) => NodeJS.Timeout;
endProgress: (interval: NodeJS.Timeout, finalMessage?: string) => void;
setLineBreak: (enabled: boolean) => void;
};
type DatabaseType = "sqlite" | "postgresql";
interface TableNamesConfig {
/** Table name for agents, defaults to 'agents' */
agents?: string;
/** Table name for users, defaults to 'users' */
users?: string;
/** Table name for tasks, defaults to 'tasks' */
tasks?: string;
/** Table name for memories, defaults to 'memories' */
memories?: string;
/** Table name for chats, defaults to 'chats' */
chats?: string;
/** Custom table names for user-defined tables */
custom?: Record<string, string>;
}
interface DatabaseConfig {
/** Required: The type of database to use */
type: DatabaseType;
/** Required: Connection string or configuration object */
connection: string | Knex.StaticConnectionConfig;
/** Optional: Custom table names for system tables */
tableNames?: TableNamesConfig;
/** Optional: Prefix for all table names */
tablePrefix?: string;
}
interface DatabaseInstance {
knex: Knex;
config: DatabaseConfig;
connect(): Promise<void>;
disconnect(): Promise<void>;
executeQuery<T = any>(query: string, params?: any[]): Promise<T[]>;
getTable(tableName: string): TableOperations;
getTableNames(): Required<TableNamesConfig>;
hasTable(tableName: string): Promise<boolean>;
createTable(tableName: string, schema: (table: Knex.TableBuilder) => void): Promise<void>;
dropTable(tableName: string): Promise<void>;
ensureTable(tableName: string, schema: (table: Knex.TableBuilder) => void): Promise<void>;
registerCustomTable(name: string, tableName: string): void;
getCustomTableName(name: string): string | undefined;
}
interface TableOperations {
insert(data: Record<string, any>): Promise<number | string>;
find(filter?: Record<string, any>): Promise<Record<string, any>[]>;
findOne(filter: Record<string, any>): Promise<Record<string, any> | null>;
update(filter: Record<string, any>, data: Record<string, any>): Promise<number>;
delete(filter: Record<string, any>): Promise<number>;
}
type DatabaseFactory = (config?: DatabaseConfig) => Promise<DatabaseInstance>;
interface MemoryEntry {
id: string;
agentId: string;
sessionId: string;
userId?: string;
role: "system" | "user" | "assistant" | "task_context" | "task_event" | "task_tool" | "task_result";
content: string;
timestamp: Date;
metadata?: Record<string, unknown>;
embedding?: number[];
}
interface SimilaritySearchResult extends MemoryEntry {
similarity: number;
}
interface MemoryConfig {
/** Required: Database instance for storing memories */
database: DatabaseInstance;
/** Optional: Table name for storing memories, defaults to "memories" */
tableName?: string;
/** Optional: Maximum number of entries to retrieve at once, defaults to 100 */
maxEntries?: number;
/** Optional: Whether to enable embedding functionality, defaults to false */
enableEmbeddings?: boolean;
}
interface MemoryInstance {
config: MemoryConfig;
add(entry: Omit<MemoryEntry, "id" | "timestamp">): Promise<string>;
getBySession(sessionId: string, limit?: number): Promise<MemoryEntry[]>;
getByAgent(agentId: string, limit?: number): Promise<MemoryEntry[]>;
getByUser?(userId: string, limit?: number): Promise<MemoryEntry[]>;
/** Get a memory entry by its ID */
getById(id: string): Promise<MemoryEntry | null>;
/** Delete a specific memory entry by ID */
delete(id: string): Promise<void>;
clear(sessionId: string): Promise<void>;
summarize(sessionId: string): Promise<string>;
searchByText?(query: string, limit?: number): Promise<MemoryEntry[]>;
searchByEmbedding?(embedding: number[], limit?: number, threshold?: number): Promise<SimilaritySearchResult[]>;
/** List all sessions for a specific agent */
listSessions(agentId: string, limit?: number): Promise<{
sessionId: string;
lastMessage?: string;
messageCount: number;
lastActivity: Date;
metadata?: Record<string, unknown>;
}[]>;
}
interface MemoryFactory {
(config: MemoryConfig): Promise<MemoryInstance>;
}
type ProviderType = "openai" | "ollama";
interface ModelConfig {
/** Required: Name of the model */
name: string;
/** Optional: Maximum context window size in tokens */
contextWindow?: number;
/** Optional: Temperature for generation (0-1), defaults to 0.7 */
temperature?: number;
/** Optional: Maximum tokens to generate, dependent on model */
maxTokens?: number;
}
interface OpenAIModelConfig extends ModelConfig {
/** Optional: API key for authentication, defaults to OPENAI_API_KEY env var */
apiKey?: string;
/** Optional: Base URL for API, defaults to OPENAI_BASE_URL env var */
baseUrl?: string;
/** Optional: Organization ID for API requests */
organization?: string;
}
interface OllamaModelConfig extends ModelConfig {
/** Optional: Base URL for Ollama API, defaults to OLLAMA_BASE_URL env var or http://localhost:11434 */
baseUrl?: string;
}
type ProviderModelConfig = OpenAIModelConfig | OllamaModelConfig;
interface ProviderConfig {
/** Required: Type of the provider (openai or ollama) */
type: ProviderType;
/** Optional: Simple format - just specify model name (exclusive with models) */
model?: string;
/** Optional: Traditional format with array of models (exclusive with model) */
models?: (ProviderModelConfig | string)[];
/** Optional: Default model to use, inferred from model if only one is provided */
defaultModel?: string;
/** Optional: Model to use for generating embeddings, defaults to "text-embedding-3-small" for OpenAI */
embeddingModel?: string;
}
interface ProviderMessage {
/** Required: Role of the message sender */
role: "system" | "user" | "assistant";
/** Required: Content of the message */
content: string;
}
interface ProviderTool {
name: string;
description?: string;
parameters?: any;
}
interface ProviderToolParameterSchema {
name: string;
type: "string" | "number" | "boolean" | "object" | "array" | "null" | "integer";
description?: string;
required?: boolean;
enum?: string[] | number[] | boolean[];
format?: string;
}
interface CompletionOptions {
tools?: ProviderTool[];
toolCalling?: boolean;
systemMessage?: string;
temperature?: number;
maxTokens?: number;
}
interface ProviderToolCall {
type: string;
id: string;
name: string;
arguments: Record<string, any>;
}
interface StructuredCompletionResponse {
content: string;
tool_calls: ProviderToolCall[];
}
interface ProviderModel {
provider: ProviderType;
name: string;
config: ModelConfig;
/**
* Complete a prompt with messages
* @param messages Array of messages to send to the model
* @param options Additional options like tools to use
* @returns The completion text or structured response with tool calls
*/
complete(messages: ProviderMessage[], options?: CompletionOptions): Promise<string | StructuredCompletionResponse>;
generateEmbedding?(text: string): Promise<number[]>;
}
interface ProviderInstance {
type: ProviderType;
getModel(name: string): ProviderModel;
listModels(): string[];
getDefaultModel?(): string | null;
getEmbeddingModel?(): ProviderModel | string | null;
generateEmbedding?(text: string): Promise<number[] | null>;
}
type ProviderFactory = (config: ProviderConfig) => ProviderInstance;
declare enum VectorDatabaseType {
SAME_AS_MAIN = "same_as_main",// Use the same database as the main application
POSTGRES = "postgres",// PostgreSQL with pgvector
QDRANT = "qdrant",// Qdrant vector database
PINECONE = "pinecone",// Pinecone vector database
MILVUS = "milvus",// Milvus vector database
WEAVIATE = "weaviate"
}
interface VectorDatabaseConfig {
/** Type of vector database to use */
type: VectorDatabaseType;
/** Connection string (if applicable) */
connectionString?: string;
/** API key (if applicable) */
apiKey?: string;
/** Environment (if applicable) */
environment?: string;
/** Namespace/index (if applicable) */
namespace?: string;
/** Base URL (if applicable) */
baseUrl?: string;
/** Any other custom options */
options?: Record<string, any>;
}
interface Document {
id: string;
content: string;
metadata: Record<string, any>;
embedding?: number[];
}
interface Chunk {
id: string;
documentId: string;
content: string;
metadata: Record<string, any>;
embedding: number[];
}
interface RAGResult {
content: string;
metadata: Record<string, any>;
similarity?: number;
sourceId: string;
}
interface RAGConfig {
/** Required: Database instance for storing documents/chunks */
database: DatabaseInstance;
/** Optional: Memory instance for storing vector embeddings */
memory?: MemoryInstance;
/** Optional: Provider instance for generating embeddings */
provider?: ProviderInstance;
/** Optional: Custom table name for storing data */
tableName?: string;
/** Optional: Maximum number of results to retrieve */
maxResults?: number;
/** Optional: Vector database configuration */
vectorDatabase?: VectorDatabaseConfig;
}
interface VectorRAGConfig extends RAGConfig {
/** Optional: Chunk size for text splitting */
chunkSize?: number;
/** Optional: Chunk overlap for text splitting */
chunkOverlap?: number;
}
interface DocumentRAGConfig extends RAGConfig {
/** Optional: Whether to store document embeddings */
storeEmbeddings?: boolean;
}
interface RAGInstance {
config: RAGConfig;
search(query: string, limit?: number): Promise<RAGResult[]>;
}
interface VectorRAGInstance extends RAGInstance {
config: VectorRAGConfig;
addDocument(document: Omit<Document, "id" | "embedding">): Promise<string>;
getDocumentById(id: string): Promise<Document | null>;
deleteDocument(id: string): Promise<void>;
searchByVector(embedding: number[], limit?: number, threshold?: number): Promise<RAGResult[]>;
}
interface DocumentRAGInstance extends RAGInstance {
config: DocumentRAGConfig;
addDocument(document: Omit<Document, "id">): Promise<string>;
getDocumentById(id: string): Promise<Document | null>;
deleteDocument(id: string): Promise<void>;
searchByMetadata(filter: Record<string, any>, limit?: number): Promise<RAGResult[]>;
}
type VectorRAGFactory = (config: VectorRAGConfig) => Promise<VectorRAGInstance>;
type DocumentRAGFactory = (config: DocumentRAGConfig) => Promise<DocumentRAGInstance>;
declare enum RAGType {
VECTOR = "vector",
DOCUMENT = "document"
}
interface RAGFactoryConfig extends RAGConfig {
type: RAGType;
chunkSize?: number;
chunkOverlap?: number;
storeEmbeddings?: boolean;
}
type RAGFactory = (config: RAGFactoryConfig) => Promise<VectorRAGInstance | DocumentRAGInstance>;
interface ChatMessage extends MemoryEntry {
chatId: string;
}
interface ChatMetadata {
id: string;
title?: string;
userId?: string;
agentId: string;
status: 'active' | 'archived' | 'deleted';
createdAt: Date;
updatedAt: Date;
lastMessageAt?: Date;
messageCount: number;
metadata?: Record<string, unknown>;
}
interface ChatSummary {
id: string;
title?: string;
userId?: string;
agentId: string;
status: 'active' | 'archived' | 'deleted';
lastMessage?: string;
lastMessageAt?: Date;
messageCount: number;
createdAt: Date;
updatedAt: Date;
}
interface ChatConfig {
/** Required: Database instance for storing chat data */
database: DatabaseInstance;
/** Required: Memory instance for storing messages */
memory: MemoryInstance;
/** Optional: Table name for storing chat metadata, defaults to "chats" */
tableName?: string;
/** Optional: Maximum number of chats to retrieve at once, defaults to 50 */
maxChats?: number;
/** Optional: Auto-generate titles for chats, defaults to true */
autoGenerateTitles?: boolean;
}
interface ChatInstance {
config: ChatConfig;
createChat(params: {
chatId?: string;
userId?: string;
agentId: string;
title?: string;
metadata?: Record<string, unknown>;
}): Promise<ChatMetadata>;
createChatWithMessage(params: {
chatId?: string;
userId?: string;
agentId: string;
title?: string;
metadata?: Record<string, unknown>;
message: string;
model: any;
systemPrompt?: string;
tools?: any[];
taskManager?: any;
embedding?: number[];
useTaskSystem?: boolean;
temperature?: number;
maxTokens?: number;
}): Promise<string>;
getChat(chatId: string): Promise<ChatMetadata | null>;
updateChat(chatId: string, updates: Partial<ChatMetadata>): Promise<void>;
deleteChat(chatId: string): Promise<void>;
archiveChat(chatId: string): Promise<void>;
listChats(params?: {
userId?: string;
agentId?: string;
status?: 'active' | 'archived' | 'deleted';
limit?: number;
offset?: number;
}): Promise<ChatSummary[]>;
searchChats(params: {
query: string;
userId?: string;
agentId?: string;
limit?: number;
}): Promise<ChatSummary[]>;
addMessage(params: {
chatId: string;
agentId: string;
userId?: string;
role: "system" | "user" | "assistant" | "task_context" | "task_event" | "task_tool" | "task_result";
content: string;
metadata?: Record<string, unknown>;
}): Promise<string>;
getMessages(chatId: string, limit?: number): Promise<ChatMessage[]>;
deleteMessage(messageId: string): Promise<void>;
clearMessages(chatId: string): Promise<void>;
getChatStats(params?: {
userId?: string;
agentId?: string;
}): Promise<{
totalChats: number;
activeChats: number;
archivedChats: number;
totalMessages: number;
}>;
chat(params: {
message: string;
chatId: string;
agentId: string;
userId?: string;
model: any;
systemPrompt?: string;
tools?: any[];
taskManager?: any;
chatTitle?: string;
metadata?: Record<string, unknown>;
embedding?: number[];
useTaskSystem?: boolean;
temperature?: number;
maxTokens?: number;
}): Promise<string>;
}
interface ChatFactory {
(config: ChatConfig): Promise<ChatInstance>;
}
interface PluginWithTools {
init?: () => Promise<void>;
getTools: () => Plugin[];
}
interface AgentConfig {
/** Optional: Agent ID (auto-generated if not provided) */
id?: string;
/** Required: Name of the agent */
name: string;
/** Optional: Description of the agent's purpose */
description?: string;
/** Required: Language model provider OR provider instance */
model?: ProviderModel;
/** Alternative to model: Provider instance that contains models */
provider?: ProviderInstance;
/** Required: Memory instance for storing conversation history */
memory: MemoryInstance;
/** Optional: Database instance for storage (will create one if not provided) */
database?: DatabaseInstance;
/** Optional: System prompt that defines the agent's behavior */
systemPrompt?: string;
/** Optional: Array of tools the agent can use */
tools?: Plugin[];
/** Optional: Array of plugins the agent can use (plugins can provide multiple tools) */
plugins?: (Plugin | PluginWithTools)[];
/** Optional: RAG instance for document retrieval and search */
rag?: RAGInstance;
/** Optional: Chat instance for chat management and metadata */
chat?: ChatInstance;
}
interface AgentInstance {
id: string;
config: AgentConfig;
getAvailableTools(): string[];
addTool(tool: Plugin): void;
getChatManager(): ChatInstance | undefined;
setChatManager(chatManager: ChatInstance): void;
createChat(params: {
chatId?: string;
userId?: string;
title?: string;
metadata?: Record<string, unknown>;
}): Promise<ChatMetadata>;
getChat(chatId: string): Promise<ChatMetadata | null>;
updateChat(chatId: string, updates: Partial<ChatMetadata>): Promise<void>;
deleteChat(chatId: string): Promise<void>;
archiveChat(chatId: string): Promise<void>;
listChats(params?: {
userId?: string;
status?: 'active' | 'archived' | 'deleted';
limit?: number;
offset?: number;
}): Promise<ChatSummary[]>;
searchChats(params: {
query: string;
userId?: string;
limit?: number;
}): Promise<ChatSummary[]>;
getChatStats(params?: {
userId?: string;
}): Promise<{
totalChats: number;
activeChats: number;
archivedChats: number;
totalMessages: number;
}>;
chatWithId(params: {
message: string;
chatId: string;
userId?: string;
systemPrompt?: string;
temperature?: number;
maxTokens?: number;
metadata?: Record<string, unknown>;
}): Promise<string>;
streamChatWithId(params: {
message: string;
chatId: string;
userId?: string;
systemPrompt?: string;
temperature?: number;
maxTokens?: number;
metadata?: Record<string, unknown>;
onChunk?: (chunk: string) => void;
}): Promise<string>;
chat(params: {
message: string;
sessionId?: string;
systemPrompt?: string;
temperature?: number;
maxTokens?: number;
metadata?: Record<string, unknown>;
}): Promise<string>;
streamChat(params: {
message: string;
sessionId?: string;
systemPrompt?: string;
temperature?: number;
maxTokens?: number;
metadata?: Record<string, unknown>;
onChunk?: (chunk: string) => void;
}): Promise<string>;
getHistory(sessionId: string, limit?: number): Promise<any[]>;
clearHistory(sessionId: string): Promise<void>;
addToMemory(params: {
sessionId: string;
role: 'user' | 'assistant' | 'system';
content: string;
metadata?: Record<string, unknown>;
}): Promise<string>;
listSessions(limit?: number): Promise<{
sessionId: string;
lastMessage?: string;
messageCount: number;
lastActivity: Date;
metadata?: Record<string, unknown>;
}[]>;
getModel(): ProviderModel;
getProvider(): ProviderInstance | undefined;
}
type AgentFactory = (config: AgentConfig) => Promise<AgentInstance>;
interface ToolParameterSchema {
/** Required: Name of the parameter */
name: string;
/** Required: Data type of the parameter */
type: "string" | "number" | "boolean" | "array" | "object";
/** Required: Description of the parameter's purpose */
description: string;
/** Optional: Whether this parameter is required, defaults to false */
required?: boolean;
/** Optional: Default value if parameter is not provided */
default?: any;
}
interface Plugin {
/** Required: Unique name of the plugin */
name: string;
/** Required: Description of what the plugin does */
description: string;
/** Required: Parameters the plugin accepts */
parameters: ToolParameterSchema[];
/** Required: Function to execute the plugin's functionality */
execute: (params: Record<string, any>) => Promise<any>;
}
interface PluginConfig {
/** Required: Name of the plugin manager */
name: string;
/** Optional: Description of the plugin manager */
description?: string;
/** Optional: Version of the plugin manager */
version?: string;
/** Required: Tools to be managed by this plugin manager */
tools: Plugin[];
}
interface PluginInstance {
config: PluginConfig;
getTools(): Plugin[];
getTool(name: string): Plugin | undefined;
registerTool(tool: Plugin): void;
removeTool(name: string): boolean;
}
type PluginFactory = (config: PluginConfig) => PluginInstance;
type TaskStatus = "pending" | "running" | "completed" | "failed";
interface TaskConfig {
id?: string;
name: string;
description: string;
plugins?: string[];
input?: any;
dependencies?: string[];
dependsOn?: string[];
maxRetries?: number;
agentId?: string;
sessionId?: string;
model?: ProviderModel;
}
interface TaskResult {
success: boolean;
output?: any;
error?: Error;
context?: Record<string, any>;
}
interface TaskInstance {
id: string;
config: TaskConfig;
status: TaskStatus;
result?: TaskResult;
retries: number;
plugins: Plugin[];
createdAt: Date;
startedAt?: Date;
completedAt?: Date;
agentId?: string;
sessionId?: string;
contextId?: string;
memory?: MemoryInstance;
model?: ProviderModel;
execute(input?: any): Promise<TaskResult>;
cancel(): void;
loadPlugins(model?: ProviderModel): Promise<void>;
setMemory(memory: MemoryInstance): void;
}
interface TaskManagerConfig {
concurrency?: number;
agentId?: string;
sessionId?: string;
memory?: MemoryInstance;
database?: DatabaseInstance;
providerModel?: ProviderModel;
}
interface TaskManagerInstance {
addExistingTask(task: TaskInstance | TaskConfig, model?: ProviderModel): TaskInstance;
getTask(id: string): TaskInstance | undefined;
getAllTasks(): TaskInstance[];
createTask(config: TaskConfig, model?: ProviderModel): Promise<TaskInstance>;
cancelTask(id: string): boolean;
waitForTasksLoaded(): Promise<void>;
executeTask(id: string, input?: any): Promise<TaskResult>;
setProviderModel(model: ProviderModel): void;
getProviderModel(): ProviderModel | undefined;
getTasks(): TaskInstance[];
getTasksByAgent(agentId: string): TaskInstance[];
getTasksBySession(sessionId: string): TaskInstance[];
setAgentId(agentId: string): void;
setSessionId(sessionId: string): void;
run(taskIds?: string[]): Promise<Map<string, TaskResult>>;
cancel(taskId: string): boolean;
cancelAll(): void;
}
type TaskFactory = (config: TaskConfig) => TaskInstance;
type TaskManagerFactory = (config?: TaskManagerConfig) => TaskManagerInstance;
declare const createAgent: AgentFactory;
declare const createProvider: (config: Record<string, unknown>) => ProviderInstance;
/**
* Factory function to create a new memory instance
* @param config Configuration for the memory instance
* @returns Promise that resolves to the new memory instance
*/
declare const createMemory: MemoryFactory;
declare const createDatabase: DatabaseFactory;
interface PDFParseOptions {
/**
* The strategy for splitting the PDF
* - 'simple': Split by character count
* - 'paragraph': Split by paragraphs
* - 'section': Split by detected sections/headers (most intelligent)
*/
splitStrategy: 'simple' | 'paragraph' | 'section';
/**
* Size of chunks when using 'simple' strategy
*/
chunkSize?: number;
/**
* Overlap between chunks when using 'simple' or 'paragraph' strategy
*/
chunkOverlap?: number;
/**
* Whether to include page numbers in metadata
*/
includePageNumbers?: boolean;
/**
* Custom metadata to attach to each document
*/
metadata?: Record<string, any>;
}
interface PDFParseResult {
/**
* The documents extracted from the PDF, ready to be added to RAG
*/
documents: Omit<Document, 'id'>[];
/**
* Metadata about the PDF itself
*/
pdfMetadata: {
title?: string;
author?: string;
numPages: number;
creationDate?: Date;
};
/**
* Unique identifier for this PDF document
*/
documentId: string;
}
/**
* Parse a PDF file and extract structured content for RAG
* @param filePath Path to the PDF file
* @param options Options for parsing and chunking
* @returns Promise resolving to the parsed documents
*/
declare function parsePDF(filePath: string, options: PDFParseOptions): Promise<PDFParseResult>;
/**
* Parse a directory of PDFs and load into RAG system
* @param dirPath Directory path containing PDFs
* @param options Parse options
* @returns Array of results for each processed PDF
*/
declare function parseDirectoryOfPDFs(dirPath: string, options: PDFParseOptions): Promise<Record<string, PDFParseResult>>;
/**
* Unified factory function to create a RAG instance of the specified type
* @param config Configuration with type to determine which RAG implementation to create
* @returns Promise resolving to the appropriate RAG instance
*/
declare const createRAG: RAGFactory;
/**
* Interface for vector database operations
*/
interface VectorDatabaseConnector {
/** Adds vectors to the database */
addVectors(vectors: Array<{
id: string;
vector: number[];
metadata: Record<string, any>;
}>): Promise<void>;
/** Similarity search for vectors */
searchVectors(vector: number[], limit?: number, threshold?: number): Promise<Array<{
id: string;
similarity: number;
}>>;
/** Delete vectors by IDs */
deleteVectors(ids: string[]): Promise<void>;
/** Get metadata for a vector by ID */
getVectorMetadata(id: string): Promise<Record<string, any> | null>;
/** Close the connection */
close(): Promise<void>;
}
/**
* Factory function to create a vector database connector based on configuration
* @param config Vector database configuration
* @param database Main database instance (if using same database)
* @returns Vector database connector
*/
declare function createVectorDatabaseConnector(config?: VectorDatabaseConfig, database?: DatabaseInstance): VectorDatabaseConnector;
/**
* Load vector database configuration from environment variables
* @returns Vector database configuration
*/
declare function loadVectorDatabaseConfigFromEnv(): VectorDatabaseConfig;
/**
* Creates a chat management system that works with existing memory system
* Chat IDs are the same as session IDs for backward compatibility
* Can be used standalone or integrated with Agent instances
*/
declare function createChat(config: ChatConfig): Promise<ChatInstance>;
declare const DEFAULT_AGENT_NAME = "astreus-agent";
declare const DEFAULT_MODEL = "gpt-4o-mini";
declare const DEFAULT_TEMPERATURE = 0.3;
declare const DEFAULT_MAX_TOKENS = 4096;
declare const DEFAULT_MEMORY_SIZE = 10;
declare const DEFAULT_DB_PATH = "./.astreus/db";
declare const VECTOR_DATABASE_TYPES: {
SAME_AS_MAIN: string;
POSTGRES: string;
QDRANT: string;
PINECONE: string;
MILVUS: string;
WEAVIATE: string;
};
declare const PROVIDER_TYPES: {
OPENAI: string;
OLLAMA: string;
};
declare const DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1";
declare const DEFAULT_OPENAI_EMBEDDING_MODEL = "text-embedding-3-small";
declare const DEFAULT_OLLAMA_BASE_URL = "http://localhost:11434";
declare const DEFAULT_MODEL_CONFIGS: {
openai: {
"gpt-4o": {
apiKey: string;
baseUrl: string | undefined;
temperature: number;
maxTokens: number;
};
"gpt-4o-mini": {
apiKey: string;
baseUrl: string | undefined;
temperature: number;
maxTokens: number;
};
"gpt-4": {
apiKey: string;
baseUrl: string | undefined;
temperature: number;
maxTokens: number;
};
"gpt-3.5-turbo": {
apiKey: string;
baseUrl: string | undefined;
temperature: number;
maxTokens: number;
};
};
ollama: {
llama3: {
baseUrl: string;
temperature: number;
maxTokens: number;
};
mistral: {
baseUrl: string;
temperature: number;
maxTokens: number;
};
};
};
declare const DEFAULT_CHUNK_SIZE = 1000;
declare const DEFAULT_CHUNK_OVERLAP = 200;
declare const DEFAULT_VECTOR_SIMILARITY_THRESHOLD = 0.7;
declare const DEFAULT_MAX_RESULTS = 10;
declare const DEFAULT_TASK_CONCURRENCY = 5;
declare const DEFAULT_MAX_RETRIES = 3;
declare const TASK_STATUS: {
PENDING: string;
RUNNING: string;
COMPLETED: string;
FAILED: string;
};
declare const ERROR_MESSAGES: {
MISSING_PARAMETER: string;
INVALID_PROVIDER: string;
INVALID_MEMORY: string;
INVALID_DATABASE: string;
INVALID_RAG: string;
INVALID_VECTOR_DB: string;
INVALID_TASK: string;
INVALID_EMBEDDING: string;
};
/**
* Utility functions for parameter validation
*/
/**
* Validates that all required parameters are provided
* @param params The parameters object to validate
* @param requiredParams Array of parameter names that are required
* @param functionName Name of the function for error message context
* @throws Error if any required parameter is missing or undefined
*/
declare function validateRequiredParams(params: Record<string, any>, requiredParams: string[], functionName: string): void;
/**
* Validates a single required parameter
* @param value The parameter value to check
* @param paramName Name of the parameter for error message
* @param functionName Name of the function for error message context
* @throws Error if the parameter is missing or undefined
*/
declare function validateRequiredParam(value: any, paramName: string, functionName: string): void;
/**
* Convert a RAG instance to an array of tools that can be used by agents
* @param rag The RAG instance to convert
* @returns Array of Plugin tools for RAG functionality
*/
declare function createRAGTools(rag: RAGInstance): Plugin[];
/**
* Task Manager class that manages multiple tasks
*
* This class provides functionality for:
* - Creating and managing multiple tasks
* - Executing tasks with dependencies in order
* - Persisting task state to the database
* - Restoring tasks from previous sessions
*/
declare class TaskManager implements TaskManagerInstance {
private readonly tasks;
private tasksLoaded;
private loadingPromise;
private config;
private agentId?;
private sessionId?;
private memory?;
private database?;
private providerModel?;
/**
* Create a new TaskManager instance
* @param config Configuration options for the task manager
*/
constructor(config?: TaskManagerConfig);
/**
* Add an existing task to the manager
* @param task Task instance or configuration to add
* @param model Optional LLM model to use for tool selection
* @returns The added task instance
*/
addExistingTask(task: TaskInstance | TaskConfig, model?: ProviderModel): TaskInstance;
/**
* Helper method to check for parent ID in dependencies and add it if needed
* @param task Task to check for parent dependencies
*/
private addTaskWithParent;
/**
* Get a task by ID
* @param id ID of the task to retrieve
* @returns Task instance if found, undefined otherwise
*/
getTask(id: string): TaskInstance | undefined;
/**
* Get all tasks managed by this instance
* @returns Array of all task instances
*/
getAllTasks(): TaskInstance[];
/**
* Create and add a new task
* @param config Configuration for the new task
* @param model Optional LLM model to use for tool selection
* @returns The created task instance
*/
createTask(config: TaskConfig, model?: ProviderModel): Promise<TaskInstance>;
/**
* Cancel a task by ID
* @param id ID of the task to cancel
* @returns true if task was found and canceled, false otherwise
*/
cancelTask(id: string): boolean;
/**
* Load tasks from database
* @returns Promise that resolves when tasks are loaded
*/
private loadTasksFromDatabase;
/**
* Wait for tasks to be loaded from database
* @returns Promise that resolves when tasks are loaded
*/
waitForTasksLoaded(): Promise<void>;
/**
* Execute a specific task by ID
* @param id ID of the task to execute
* @param input Optional input data to pass to the task
* @returns Promise that resolves with the task execution result
*/
executeTask(id: string, input?: any): Promise<TaskResult>;
/**
* Get all tasks
* @deprecated Use getAllTasks() instead for newer implementations
* @returns Array of all task instances
*/
getTasks(): TaskInstance[];
/**
* Get tasks by agent ID
* @param agentId Agent ID to filter by
* @returns Array of tasks belonging to the specified agent
*/
getTasksByAgent(agentId: string): TaskInstance[];
/**
* Get tasks by session ID
* @param sessionId Session ID to filter by
* @returns Array of tasks belonging to the specified session
*/
getTasksBySession(sessionId: string): TaskInstance[];
/**
* Set the agent ID for this task manager
* @param agentId Agent ID to set
*/
setAgentId(agentId: string): void;
/**
* Set the session ID for this task manager
* @param sessionId Session ID to set
*/
setSessionId(sessionId: string): void;
/**
* Set the memory instance for this task manager
* @param memory Memory instance to use for task context storage
*/
setMemory(memory: MemoryInstance): void;
/**
* Set the provider model to use for tasks
* @param model Provider model to use
*/
setProviderModel(model: ProviderModel): void;
/**
* Get the current provider model
* @returns The current provider model or undefined
*/
getProviderModel(): ProviderModel | undefined;
/**
* Run specified tasks (or all if no IDs provided)
* @param taskIds Optional array of task IDs to run
* @returns Promise that resolves with a map of task IDs to results
*/
run(taskIds?: string[]): Promise<Map<string, TaskResult>>;
/**
* Cancel a specific task
* @deprecated Use cancelTask() instead for newer implementations
* @param taskId ID of the task to cancel
* @returns true if task was found and canceled, false otherwise
*/
cancel(taskId: string): boolean;
/**
* Cancel all tasks
*/
cancelAll(): void;
}
/**
* Task class implementing the TaskInstance interface
*/
declare class Task implements TaskInstance {
id: string;
config: TaskConfig;
status: TaskStatus;
result?: TaskResult;
retries: number;
plugins: Plugin[];
createdAt: Date;
startedAt?: Date;
completedAt?: Date;
agentId?: string;
sessionId?: string;
contextId?: string;
memory?: MemoryInstance;
database?: DatabaseInstance;
isCancelled: boolean;
private toolSelectionLogged;
constructor(config: TaskConfig, memory?: MemoryInstance, model?: ProviderModel, database?: DatabaseInstance);
/**
* Initialize plugins for the task
* This tries three methods in order:
* 1. Use LLM-selected tools if model is provided
* 2. Use keyword matching based on task name
* 3. Fall back to all agent plugins
*/
loadPlugins(model?: ProviderModel): Promise<void>;
/**
* Execute the task using configured plugins
*/
execute(input?: any): Promise<TaskResult>;
/**
* Get task context from memory using session ID
*/
getTaskContext(sessionId: string): Promise<Record<string, unknown>>;
/**
* Save task context to memory system
*/
saveTaskContext(sessionId: string, contextData: Record<string, unknown>): Promise<void>;
/**
* Cancel the task execution
*/
cancel(): void;
/**
* Set the memory instance for this task
*/
setMemory(memory: MemoryInstance): void;
/**
* Get memory entries specific to this task
* @returns Promise that resolves to an array of task-specific memory entries
*/
getTaskMemory(): Promise<MemoryEntry[]>;
/**
* Add a memory entry for this task
* @param content Content of the memory entry
* @param role Role for the memory entry (task_event, task_tool, task_result)
* @param additionalMetadata Additional metadata to include
* @returns Promise that resolves when the memory is added
*/
addTaskMemoryEntry(content: string, role?: "task_event" | "task_tool" | "task_result", additionalMetadata?: Record<string, unknown>): Promise<void>;
/**
* Create a new task asynchronously
*/
static createTask(config: TaskConfig, memory?: MemoryInstance, model?: ProviderModel, database?: DatabaseInstance): Promise<TaskInstance>;
/**
* Create a new task synchronously
*/
static createTaskSync(config: TaskConfig, memory?: MemoryInstance, model?: ProviderModel, database?: DatabaseInstance): TaskInstance;
}
/**
* Create a new TaskManager instance
* @param config Configuration for the task manager
* @returns A new TaskManager instance
*/
declare const createTaskManager: (config?: TaskManagerConfig) => TaskManagerInstance;
/**
* Create a new task asynchronously
* @param config Configuration for the task
* @param memory Optional memory instance for task context storage
* @returns Promise that resolves to the new task instance
*/
declare const createTask: (config: TaskConfig, memory?: MemoryInstance) => Promise<TaskInstance>;
/**
* Create a new task synchronously
* @param config Configuration for the task
* @param memory Optional memory instance for task context storage
* @returns The new task instance
*/
declare const createTaskSync: (config: TaskConfig, memory?: MemoryInstance) => TaskInstance;
/**
* Comprehensive Plugin Manager that handles all plugin-related functionality
* This class provides both instance-level management for specific agents
* and static global registry for framework-wide plugin management.
*/
declare class PluginManager implements PluginInstance {
config: PluginConfig;
private tools;
private static registry;
constructor(config: PluginConfig);
/**
* Get all tools registered with this instance
* @returns Array of all registered tools
*/
getTools(): Plugin[];
/**
* Get a specific tool by name
* @param name Name of the tool to retrieve
* @returns Tool if found, undefined otherwise
*/
getTool(name: string): Plugin | undefined;
/**
* Register a tool with this instance
* Also registers the tool with the global registry
* @param tool Tool to register
* @throws Error if the tool is invalid
*/
registerTool(tool: Plugin): void;
/**
* Remove a tool from this instance
* Also removes the tool from the global registry
* @param name Name of the tool to remove
* @returns true if tool was found and removed, false otherwise
*/
removeTool(name: string): boolean;
/**
* Check if a tool is registered with this instance
* @param name Name of the tool to check
* @returns true if tool is registered, false otherwise
*/
hasTool(name: string): boolean;
/**
* Get the number of tools registered with this instance
* @returns Number of tools
*/
getToolCount(): number;
/**
* Register a plugin with the global registry
* @param plugin Plugin to register
* @throws Error if the plugin is invalid
*/
static register(plugin: Plugin): void;
/**
* Unregister a plugin from the global registry
* @param name Name of the plugin to unregister
* @returns true if plugin was found and removed, false otherwise
*/
static unregister(name: string): boolean;
/**
* Get a plugin by name from the global registry
* @param name Name of the plugin to retrieve
* @returns Plugin if found, undefined otherwise
*/
static get(name: string): Plugin | undefined;
/**
* Get all plugins from the global registry
* @returns Array of all registered plugins
*/
static getAll(): Plugin[];
/**
* Get all plugins for a specific agent
* @param agentId ID of the agent to get plugins for
* @returns Array of plugins for the specified agent
*/
static getByAgent(agentId: string): Plugin[];
/**
* Reset the global plugin registry
* Useful for testing or when reloading plugins
*/
static reset(): void;
/**
* Check if a plugin exists in the global registry
* @param name Name of the plugin to check
* @returns true if plugin exists, false otherwise
*/
static has(name: string): boolean;
/**
* Get the number of plugins in the global registry
* @returns Number of plugins
*/
static count(): number;
/**
* Load a plugin from a repository or object
* @param pluginOrPath Plugin object or path to a plugin module
* @returns Promise that resolves when the plugin is loaded and registered
* @throws Error if loading fails
*/
static load(pluginOrPath: string | Plugin): Promise<void>;
/**
* Load multiple plugins at once
* @param plugins Array of plugin objects or paths
* @returns Promise that resolves when all plugins are loaded
* @throws Error if loading any plugin fails
*/
static loadMany(plugins: Array<string | Plugin>): Promise<void>;
/**
* Create a new PluginManager instance
* @param config Configuration for the plugin manager
* @returns New PluginManager instance
*/
static create(config: PluginConfig): PluginInstance;
}
export { type AgentConfig, type AgentFactory, type AgentInstance, type ChatConfig, type ChatFactory, type ChatInstance, type ChatMessage, type ChatMetadata, type ChatSummary, type Chunk, type CompletionOptions, DEFAULT_AGENT_NAME, DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE, DEFAULT_DB_PATH, DEFAULT_MAX_RESULTS, DEFAULT_MAX_RETRIES, DEFAULT_MAX_TOKENS, DEFAULT_MEMORY_SIZE, DEFAULT_MODEL, DEFAULT_MODEL_CONFIGS, DEFAULT_OLLAMA_BASE_URL, DEFAULT_OPENAI_BASE_URL, DEFAULT_OPENAI_EMBEDDING_MODEL, DEFAULT_TASK_CONCURRENCY, DEFAULT_TEMPERATURE, DEFAULT_VECTOR_SIMILARITY_THRESHOLD, type DatabaseConfig, type DatabaseFactory, type DatabaseInstance, type DatabaseType, type Document, type DocumentRAGConfig, type DocumentRAGFactory, type DocumentRAGInstance, ERROR_MESSAGES, LogLevel, type MemoryConfig, type MemoryEntry, type MemoryFactory, type MemoryInstance, type ModelConfig, type OllamaModelConfig, type OpenAIModelConfig, PROVIDER_TYPES, type Plugin, type PluginConfig, type PluginFactory, type PluginInstance, PluginManager, type PluginWithTools, type ProviderConfig, type ProviderFactory, type ProviderInstance, type ProviderMessage, type ProviderModel, type ProviderModelConfig, type ProviderTool, type ProviderToolCall, type ProviderToolParameterSchema, type ProviderType, type RAGConfig, type RAGFactory, type RAGFactoryConfig, type RAGInstance, type RAGResult, RAGType, type SimilaritySearchResult, type StructuredCompletionResponse, TASK_STATUS, type TableNamesConfig, type TableOperations, Task, type TaskConfig, type TaskFactory, type TaskInstance, TaskManager, type TaskManagerConfig, type TaskManagerFactory, type TaskManagerInstance, type TaskResult, type TaskStatus, type ToolParameterSchema, VECTOR_DATABASE_TYPES, type VectorDatabaseConfig, VectorDatabaseType, type VectorRAGConfig, type VectorRAGFactory, type VectorRAGInstance, configure as configureLogger, createAgent, createChat, createDatabase, createMemory, createProvider, createRAG, createRAGTools, createTask, createTaskManager, createTaskSync, createVectorDatabaseConnector, loadVectorDatabaseConfigFromEnv, logger, parseDirectoryOfPDFs, parsePDF, printBanner, validateRequiredParam, validateRequiredParams };