Configuration
Astreus provides flexible configuration with enhanced parameter validation, smart defaults, and environment-based setup. The framework automatically validates configurations and provides helpful error messages for quick troubleshooting.
Configuration Architecture
Astreus configuration features:
- Smart Defaults: Sensible defaults for most use cases
- Parameter Validation: Automatic validation with helpful error messages
- Environment Variables: Support for .env files and environment-based configuration
- Type Safety: Full TypeScript support with proper typing
- Hierarchical Configuration: Override defaults with specific configurations
- Runtime Validation: Configuration validation at runtime with clear error messages
Environment Variables
Configure Astreus using environment variables for different deployment scenarios:
Global Model Configuration
Astreus uses provider-agnostic environment variables for consistent configuration across all providers:
# Global Model Configuration (applies to all providers)
MODEL_NAME=gpt-4o-mini # Main model name
TEMPERATURE=0.7 # Model temperature (0.0 - 1.0)
MAX_TOKENS=2048 # Maximum tokens per response
EMBEDDING_MODEL=text-embedding-3-small # Embedding model for RAG
# Examples for different providers:
# MODEL_NAME=claude-3-haiku-20240307 # For Claude
# MODEL_NAME=gemini-1.5-flash # For Gemini
# MODEL_NAME=llama3.2 # For Ollama
Provider API Keys
# Provider API Keys
OPENAI_API_KEY=sk-your-openai-key
ANTHROPIC_API_KEY=sk-ant-your-anthropic-key
GOOGLE_API_KEY=your-google-api-key
# Optional Provider Base URLs
OPENAI_BASE_URL=https://api.openai.com/v1
ANTHROPIC_BASE_URL=https://api.anthropic.com
GOOGLE_BASE_URL=https://generativelanguage.googleapis.com
OLLAMA_BASE_URL=http://localhost:11434
Database Configuration
# Database Type Selection
DATABASE_TYPE=postgresql # or 'sqlite'
# SQLite Configuration
DATABASE_PATH=./data/astreus.db
# PostgreSQL Configuration
DATABASE_URL=postgresql://user:password@localhost:5432/astreus
# Alternative PostgreSQL Configuration
DB_HOST=localhost
DB_PORT=5432
DB_USER=astreus_user
DB_PASSWORD=secure_password
DB_NAME=astreus_db
System Configuration
# Logging Configuration
LOG_LEVEL=info # debug, info, warn, error
NO_COLOR=false # Disable colored output
STRUCTURED_LOGS=false # Enable JSON structured logs
# Performance Configuration
MAX_CONCURRENT_REQUESTS=10
REQUEST_TIMEOUT=30000 # 30 seconds
# Memory Configuration
MAX_MEMORY_ENTRIES=1000
ENABLE_EMBEDDINGS=true
Provider Configuration
Configure different LLM providers with validation and smart defaults:
OpenAI Configuration
import { createProvider } from '@astreus-ai/astreus';
// Basic configuration with defaults
const provider = createProvider({
type: 'openai',
model: 'gpt-4o-mini' // Simplified model specification
});
// Advanced configuration
const advancedProvider = createProvider({
type: 'openai',
model: 'gpt-4o-mini',
apiKey: process.env.OPENAI_API_KEY, // Optional if set in environment
baseUrl: 'https://api.openai.com/v1', // Optional custom base URL
temperature: 0.7,
maxTokens: 1000,
presencePenalty: 0.1,
frequencyPenalty: 0.1
});
// Embedding configuration
const embeddingProvider = createProvider({
type: 'openai',
model: 'text-embedding-3-small',
apiKey: process.env.OPENAI_EMBEDDING_API_KEY, // Falls back to OPENAI_API_KEY
dimensions: 1536 // Optional: reduce embedding dimensions
});
Claude (Anthropic) Configuration
// Claude configuration with validation
const claudeProvider = createProvider({
type: 'claude',
model: 'claude-3-5-sonnet-20241022',
apiKey: process.env.ANTHROPIC_API_KEY,
maxTokens: 4000,
temperature: 0.8
});
// Claude with system message constraints
const constrainedClaude = createProvider({
type: 'claude',
model: 'claude-3-5-haiku-20241022',
apiKey: process.env.ANTHROPIC_API_KEY,
systemMessage: "You are a helpful assistant specializing in technical documentation.",
maxTokens: 2000
});
Gemini Configuration
// Gemini configuration
const geminiProvider = createProvider({
type: 'gemini',
model: 'gemini-1.5-pro',
apiKey: process.env.GOOGLE_API_KEY,
temperature: 0.6,
maxTokens: 2000,
safetySettings: [
{
category: 'HARM_CATEGORY_HARASSMENT',
threshold: 'BLOCK_MEDIUM_AND_ABOVE'
}
]
});
// Gemini Flash for faster responses
const geminiFlash = createProvider({
type: 'gemini',
model: 'gemini-1.5-flash',
apiKey: process.env.GOOGLE_API_KEY,
temperature: 0.4
});
Ollama Configuration
// Ollama local models
const ollamaProvider = createProvider({
type: 'ollama',
baseUrl: "http://localhost:11434",
model: "llama3.1",
temperature: 0.7,
contextLength: 4096
});
// Ollama with custom configuration
const customOllama = createProvider({
type: 'ollama',
baseUrl: process.env.OLLAMA_BASE_URL || "http://localhost:11434",
model: "mixtral",
options: {
num_ctx: 8192,
num_gpu: 1,
num_thread: 8
}
});
Database Configuration
Configure database connections with automatic validation:
SQLite Configuration
import { createDatabase } from '@astreus-ai/astreus';
// Default SQLite configuration
const db = await createDatabase();
// Custom SQLite path
const customDb = await createDatabase({
type: 'sqlite',
path: './data/my-astreus.db'
});
// SQLite with performance options
const performanceDb = await createDatabase({
type: 'sqlite',
path: './data/astreus.db',
options: {
journal_mode: 'WAL',
synchronous: 'NORMAL',
cache_size: -64000 // 64MB cache
}
});
PostgreSQL Configuration
// PostgreSQL with connection string
const pgDb = await createDatabase({
type: 'postgresql',
connectionString: process.env.DATABASE_URL
});
// PostgreSQL with individual parameters
const configuredPgDb = await createDatabase({
type: 'postgresql',
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT) || 5432,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false
});
// PostgreSQL with connection pooling
const pooledDb = await createDatabase({
type: 'postgresql',
connectionString: process.env.DATABASE_URL,
pool: {
min: 2,
max: 10,
acquireTimeoutMillis: 30000,
idleTimeoutMillis: 30000,
reapIntervalMillis: 1000
}
});
Memory Configuration
Configure memory systems with validation and smart defaults:
import { createMemory } from '@astreus-ai/astreus';
// Basic memory configuration
const memory = await createMemory({
database: db,
tableName: "conversations", // Custom table name
maxEntries: 1000, // Maximum entries to store
enableEmbeddings: true // Enable semantic search
});
// Advanced memory configuration
const advancedMemory = await createMemory({
database: db,
tableName: "advanced_memories",
maxEntries: 5000,
enableEmbeddings: true,
embeddingConfig: {
provider: embeddingProvider,
chunkSize: 500,
chunkOverlap: 50,
dimensions: 1536
},
searchConfig: {
maxResults: 20,
similarityThreshold: 0.7,
enableHybridSearch: true
}
});
// Memory with retention policies
const retentionMemory = await createMemory({
database: db,
tableName: "temporary_memories",
maxEntries: 500,
retentionDays: 30, // Auto-delete entries older than 30 days
enableEmbeddings: false
});
Chat Configuration
Configure chat management with flexible options:
import { createChat } from '@astreus-ai/astreus';
// Basic chat configuration
const chatManager = await createChat({
database: db,
memory: memory,
tableName: "chats",
maxChats: 100,
autoGenerateTitles: true
});
// Advanced chat configuration
const advancedChat = await createChat({
database: db,
memory: memory,
tableName: "business_chats",
maxChats: 1000,
autoGenerateTitles: true,
titleGenerationConfig: {
provider: provider,
maxTitleLength: 50,
includeMetadata: true
},
retentionConfig: {
archiveAfterDays: 90,
deleteAfterDays: 365
},
metadataSchema: {
required: ['userId', 'type'],
optional: ['priority', 'department', 'tags']
}
});
Agent Configuration
Configure agents with comprehensive validation:
import { createAgent } from '@astreus-ai/astreus';
// Basic agent configuration
const agent = await createAgent({
name: 'CustomerSupport',
provider: provider,
memory: memory,
systemPrompt: "You are a helpful customer support agent."
});
// Comprehensive agent configuration
const comprehensiveAgent = await createAgent({
id: 'support-agent-v2', // Custom agent ID
name: 'AdvancedSupport',
description: 'Advanced customer support agent with specialized capabilities',
// Core components
provider: provider,
memory: memory,
database: db,
chat: chatManager,
// Behavior configuration
systemPrompt: `You are an advanced customer support agent with access to:
- Company knowledge base
- Order management system
- Technical documentation
Always be helpful, professional, and accurate.`,
// Tools and capabilities
tools: [orderTool, knowledgeTool],
plugins: [supportPlugin],
rag: ragSystem,
// Performance configuration
defaultTemperature: 0.7,
defaultMaxTokens: 1000,
streamingEnabled: true,
// Validation and constraints
allowedOperations: ['chat', 'search', 'analyze'],
rateLimiting: {
maxRequestsPerMinute: 60,
maxTokensPerHour: 100000
}
});
RAG Configuration
Configure RAG systems with flexible document processing:
import { createRAG, RAGType, VectorDatabaseType } from '@astreus-ai/astreus';
// Basic vector RAG configuration
const vectorRAG = await createRAG({
type: RAGType.VECTOR,
database: db,
provider: provider,
tableName: 'knowledge_base',
chunkSize: 1000,
chunkOverlap: 200,
maxResults: 10
});
// Advanced RAG with external vector database
const advancedRAG = await createRAG({
type: RAGType.VECTOR,
database: db,
provider: provider,
tableName: 'documents',
// Chunking configuration
chunkSize: 800,
chunkOverlap: 150,
chunkingStrategy: 'recursive',
// Search configuration
maxResults: 20,
similarityThreshold: 0.75,
enableHybridSearch: true,
// External vector database
vectorDatabase: {
type: VectorDatabaseType.QDRANT,
url: process.env.QDRANT_URL || 'http://localhost:6333',
collectionName: 'astreus_documents',
config: {
vectors: {
size: 1536,
distance: 'Cosine'
}
}
},
// Processing configuration
preprocessors: [
{ type: 'clean_text', config: { removeSpecialChars: true } },
{ type: 'normalize', config: { lowercase: true } }
],
// Metadata extraction
metadataExtractors: [
{ type: 'file_info', fields: ['filename', 'size', 'type'] },
{ type: 'content_analysis', fields: ['language', 'topics'] }
]
});
Plugin Configuration
Configure plugins with validation and error handling:
import { XPlugin } from '@astreus-ai/x-plugin';
import { ResendPlugin } from '@astreus-ai/resend-plugin';
// Plugin configuration with validation
async function configurePlugins() {
// X (Twitter) Plugin
const xPlugin = new XPlugin({
apiKey: process.env.X_API_KEY,
apiSecret: process.env.X_API_SECRET_KEY,
accessToken: process.env.X_ACCESS_TOKEN,
accessSecret: process.env.X_ACCESS_TOKEN_SECRET,
// Optional configuration
rateLimit: {
maxTweetsPerHour: 50,
maxFollowsPerDay: 100
},
defaultOptions: {
includeReplyCount: true,
includeRetweetCount: true
}
});
// Resend Email Plugin
const resendPlugin = new ResendPlugin({
apiKey: process.env.RESEND_API_KEY,
defaultFrom: process.env.DEFAULT_FROM_EMAIL || 'noreply@yourapp.com',
// Optional configuration
templates: {
welcome: 'template-id-1',
newsletter: 'template-id-2'
},
rateLimit: {
maxEmailsPerHour: 1000
}
});
// Initialize plugins with error handling
try {
await xPlugin.init();
await resendPlugin.init();
return [xPlugin, resendPlugin];
} catch (error) {
console.error('Plugin initialization failed:', error);
throw error;
}
}
Configuration Validation
Astreus provides automatic configuration validation with helpful error messages:
Parameter Validation
import { validateRequiredParam, validateRequiredParams } from '@astreus-ai/astreus';
// Validate single parameter
function setupProvider(config) {
validateRequiredParam(config.apiKey, 'apiKey', 'Provider configuration');
validateRequiredParam(config.model, 'model', 'Provider configuration');
return createProvider(config);
}
// Validate multiple parameters
function setupDatabase(config) {
validateRequiredParams(
[
{ value: config.type, name: 'type' },
{ value: config.connectionString || config.path, name: 'connectionString or path' }
],
'Database configuration'
);
return createDatabase(config);
}
Configuration Schema Validation
// Define configuration schemas
const agentConfigSchema = {
name: { type: 'string', required: true },
provider: { type: 'object', required: true },
memory: { type: 'object', required: true },
systemPrompt: { type: 'string', required: false, default: 'You are a helpful assistant.' },
temperature: { type: 'number', required: false, min: 0, max: 2, default: 0.7 },
maxTokens: { type: 'number', required: false, min: 1, max: 8000, default: 1000 }
};
// Validate configuration against schema
function validateAgentConfig(config) {
for (const [key, schema] of Object.entries(agentConfigSchema)) {
const value = config[key];
if (schema.required && (value === undefined || value === null)) {
throw new Error(`Required parameter '${key}' is missing in agent configuration`);
}
if (value !== undefined && schema.type && typeof value !== schema.type) {
throw new Error(`Parameter '${key}' must be of type ${schema.type}`);
}
if (schema.min !== undefined && value < schema.min) {
throw new Error(`Parameter '${key}' must be at least ${schema.min}`);
}
if (schema.max !== undefined && value > schema.max) {
throw new Error(`Parameter '${key}' must be at most ${schema.max}`);
}
// Apply defaults
if (value === undefined && schema.default !== undefined) {
config[key] = schema.default;
}
}
return config;
}
Environment-Based Configuration
Configure different environments with specific settings:
Development Configuration
// .env.development
const developmentConfig = {
database: {
type: 'sqlite',
path: './dev-astreus.db'
},
provider: {
type: 'openai' // Uses MODEL_NAME, TEMPERATURE, MAX_TOKENS from env
},
logging: {
level: 'debug',
structured: false
},
features: {
enableExperimentalFeatures: true,
verboseLogging: true
}
};
Production Configuration
// .env.production
const productionConfig = {
database: {
type: 'postgresql',
connectionString: process.env.DATABASE_URL,
pool: {
min: 5,
max: 20
}
},
provider: {
type: 'openai' // Uses global env vars for consistency
},
logging: {
level: 'warn',
structured: true
},
security: {
enableRateLimiting: true,
maxRequestsPerMinute: 100
}
};
Configuration Loading
import { config } from 'dotenv';
// Load environment-specific configuration
function loadConfig() {
const env = process.env.NODE_ENV || 'development';
// Load base .env file
config();
// Load environment-specific .env file
config({ path: `.env.${env}` });
return {
environment: env,
database: {
type: process.env.DATABASE_TYPE || 'sqlite',
path: process.env.DATABASE_PATH || './astreus.db',
connectionString: process.env.DATABASE_URL
},
provider: {
type: process.env.PROVIDER_TYPE || 'openai',
model: process.env.MODEL_NAME,
temperature: parseFloat(process.env.TEMPERATURE || '0.7'),
maxTokens: parseInt(process.env.MAX_TOKENS || '2048')
},
logging: {
level: process.env.LOG_LEVEL || 'info',
structured: process.env.STRUCTURED_LOGS === 'true'
}
};
}
Best Practices
1. Use Environment Variables for Secrets
// ✅ Good: Use environment variables for API keys
const provider = createProvider({
type: 'openai',
model: 'gpt-4o-mini',
apiKey: process.env.OPENAI_API_KEY
});
// ❌ Bad: Hardcode API keys
const provider = createProvider({
type: 'openai',
model: 'gpt-4o-mini',
apiKey: 'sk-hardcoded-key' // Never do this!
});
2. Validate Configuration Early
// ✅ Good: Validate configuration at startup
async function initializeApplication() {
validateRequiredParams([
{ value: process.env.OPENAI_API_KEY, name: 'OPENAI_API_KEY' },
{ value: process.env.DATABASE_URL, name: 'DATABASE_URL' }
], 'Application startup');
const provider = createProvider({ type: 'openai', model: 'gpt-4o-mini' });
const db = await createDatabase();
// ... rest of initialization
}
3. Use Smart Defaults
// ✅ Good: Provide sensible defaults
const memory = await createMemory({
database: db,
tableName: process.env.MEMORY_TABLE || "conversations",
maxEntries: parseInt(process.env.MAX_MEMORY_ENTRIES) || 1000,
enableEmbeddings: process.env.ENABLE_EMBEDDINGS !== 'false'
});
4. Document Configuration Options
// ✅ Good: Document all configuration options
/**
* Agent Configuration Options:
*
* @param name - Agent name (required)
* @param provider - LLM provider instance (required)
* @param memory - Memory instance (required)
* @param systemPrompt - System prompt (optional, default: "You are a helpful assistant")
* @param temperature - Model temperature 0.0-2.0 (optional, default: 0.7)
* @param maxTokens - Maximum tokens per response (optional, default: 1000)
* @param tools - Array of tool instances (optional)
* @param plugins - Array of plugin instances (optional)
*/
Next Steps
- Learn about Agents for complete agent configuration
- Explore Providers for LLM provider setup
- Check out Database for database configuration
- See Memory for memory system configuration
- Review Chat for chat management configuration
How is this guide?