Astreus - Docs
Guides

Quick Start Guide

Quick Start Guide

This guide will help you get started with Astreus by setting up your development environment and creating your first AI agent with hierarchical memory storage, adaptive context management, streaming capabilities, and intelligent task execution.

Installation

Install Astreus via npm:

npm install @astreus-ai/astreus

Or using yarn:

yarn add @astreus-ai/astreus

Environment Setup

Create a .env file in your project root with your configuration:

# 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  # For RAG and embeddings

# Provider API Keys
OPENAI_API_KEY=your_openai_api_key
ANTHROPIC_API_KEY=your_anthropic_api_key
GOOGLE_API_KEY=your_google_api_key

# Database Configuration (tables created automatically when needed)
DATABASE_TYPE=sqlite  # or postgresql
DATABASE_PATH=./astreus.db  # Only for SQLite
# DATABASE_URL=postgresql://user:password@localhost:5432/astreus  # For PostgreSQL

# Ollama Configuration (Optional for local models)
# OLLAMA_BASE_URL=http://localhost:11434

# Logging
LOG_LEVEL=info  # debug, info, warn, error

Creating Your First Agent

With Astreus, everything revolves around the Agent. Let's start with a simple example that demonstrates the basic functionality. Create a file named hello-agent.js (or .ts if using TypeScript):

import { 
  createAgent, 
  createProvider,
  createMemory,
  createDatabase,
  createPersonalityManager
} from '@astreus-ai/astreus';

async function main() {
  // Initialize the database
  const db = await createDatabase();
  
  // Create a simple memory instance
  const memory = await createMemory({
    database: db
  });

  // Configure your provider (uses MODEL_NAME from .env)
  const provider = createProvider({
    type: 'openai'  // Model automatically loaded from MODEL_NAME env var
  });

  // Create personality manager and get a helpful personality
  const personalityManager = await createPersonalityManager(db);
  const personality = await personalityManager.getByName('helpful-assistant');

  // Create an agent with personality
  const agent = await createAgent({
    name: 'HelloAgent',
    description: 'A simple AI assistant',
    provider: provider,
    memory: memory,
    personality: personality, // Agent will have a helpful personality
    systemPrompt: "You are a friendly and helpful AI assistant. Answer questions concisely."
  });

  // Have a simple conversation
  console.log('=== Simple Chat ===');
  const response = await agent.chat({
    message: "Hello! What's 2 + 2?",
    sessionId: "simple-session"
  });
  console.log('Agent:', response);

  // Ask a follow-up question
  const followUp = await agent.chat({
    message: "Can you multiply that result by 10?",
    sessionId: "simple-session"
  });
  console.log('Agent:', followUp);

  // Check the conversation history
  const history = await agent.getHistory("simple-session");
  console.log(`\nConversation history: ${history.length} messages`);
  history.forEach((msg, index) => {
    console.log(`${index + 1}. ${msg.role}: ${msg.content}`);
  });
}

main();

Run your first agent:

node hello-agent.js

Creating an Agent with Adaptive Context

Now let's create a more advanced agent with hierarchical memory storage, adaptive context management, streaming capabilities, and chat management. Create a file named advanced-agent.js:

import { 
  createAgent, 
  createProvider,
  createMemory,
  createDatabase,
  createChat,
  logger
} from '@astreus-ai/astreus';

async function main() {
  try {
    // Initialize the database
    const db = await createDatabase();
    
    // Create memory instance with adaptive context
    const memory = await createMemory({
      database: db,
      tableName: "conversations", // Custom table name
      enableAdaptiveContext: true, // Enable hierarchical memory layers
      tokenBudget: {
        total: 4000,
        immediate: 1600,    // 40% for recent messages
        summarized: 1400,   // 35% for summaries
        persistent: 1000    // 25% for persistent data
      }
    });

    // Create chat service instance
    const chatService = await createChat({
      database: db,
      memory: memory,
      tableName: "chats", // Custom table name
      maxChats: 100,
      autoGenerateTitles: true,
      enableAdaptiveContext: true // Enable adaptive context for chat sessions
    });

    // Configure your provider (uses global env vars)
    const provider = createProvider({
      type: 'openai'  // Model, temperature, and tokens from env vars
    });

    // Create an advanced agent
    const agent = await createAgent({
      name: 'AdvancedAgent',
      description: 'An AI assistant with adaptive context and intelligent memory',
      provider: provider,
      memory: memory,
      chat: chatService,
      systemPrompt: "You are a friendly and helpful AI assistant with advanced memory. Answer questions concisely and accurately."
    });

    // Create a structured chat with metadata
    console.log('=== Creating Chat ===');
    const chat = await agent.createChat({
      chatId: "advanced-chat-123",
      userId: "user-456",
      title: "Advanced Conversation",
      metadata: {
        type: "demo",
        priority: "normal",
        language: "en"
      }
    });
    console.log('Chat created:', chat);

    // Basic chat with chat ID
    console.log('\n=== Chat with ID ===');
    const response = await agent.chatWithId({
      message: "Explain quantum computing in simple terms",
      chatId: "advanced-chat-123",
      userId: "user-456"
    });
    console.log('Agent:', response);

    // Streaming chat (real-time responses)
    console.log('\n=== Streaming Chat ===');
    await agent.chat({
      message: "Tell me about the benefits of AI in 3 points",
      sessionId: "advanced-chat-123",
      stream: true,
      onChunk: (chunk) => {
        process.stdout.write(chunk); // Print each chunk as it arrives
      }
    });
    console.log('\n✅ Streaming complete!');

    // Chat management operations
    console.log('\n=== Chat Management ===');
    
    // List chats
    const chats = await agent.listChats({
      userId: "user-456",
      status: 'active',
      limit: 10
    });
    console.log(`Found ${chats.length} active chats`);

    // Get chat statistics
    const stats = await agent.getChatStats({
      userId: "user-456"
    });
    console.log(`Total chats: ${stats.totalChats}, Messages: ${stats.totalMessages}`);
    
  } catch (error) {
    logger.error('Error:', error);
  }
}

main();

Run the advanced agent:

node advanced-agent.js

Database Table Creation

One of the key improvements in Astreus is automatic table creation. Each module creates its required tables when first used:

// These operations automatically create their respective tables:

// Creates 'conversations' table when first called
const memory = await createMemory({
  database: db,
  tableName: "conversations"
});

// Creates 'chats' table when first called  
const chatManager = await createChat({
  database: db,
  memory: memory,
  tableName: "chats"
});

// Creates 'agents' table when agent is saved
const agent = await createAgent({
  name: 'MyAgent',
  provider: provider,
  memory: memory,
  chat: chatManager
});

Working with Tools and Plugins

Add custom functionality to your agent:

// Define a custom tool
const weatherTool = {
  name: "get_weather",
  description: "Get current weather for a location",
  parameters: [
    {
      name: "location",
      type: "string",
      description: "The city and state/country",
      required: true
    }
  ],
  execute: async (params) => {
    // Your weather API logic here
    return `The weather in ${params.location} is sunny and 72°F`;
  }
};

// Add tool to agent
agent.addTool(weatherTool);

// Now the agent can use the weather tool
const response = await agent.chat({
  message: "What's the weather like in New York?",
  sessionId: "weather-chat"
});

Using Plugins

Extend your agent with official plugins:

import { XPlugin } from 'astreus-x-plugin';

// Initialize plugin
const xPlugin = new XPlugin();
await xPlugin.init();

// Create agent with plugin
const agent = await createAgent({
  name: 'Social Media Agent',
  provider: provider,
  memory: memory,
  chat: chatManager,
  plugins: [xPlugin], // Add plugins here
  systemPrompt: "You are a social media assistant that can help with X (Twitter) interactions."
});

// The agent now has access to X plugin tools
const response = await agent.chat({
  message: "Post a tweet saying 'Hello from Astreus!'",
  sessionId: "social-session"
});

RAG (Retrieval Augmented Generation)

Add document search capabilities to your agent:

import { createRAG, parsePDF } from '@astreus-ai/astreus';

// Parse a PDF document
const document = await parsePDF('path/to/document.pdf', {
  splitStrategy: 'section',
  chunkSize: 1000,
  includePageNumbers: true
});

// Create RAG system
const rag = await createRAG({
  type: 'vector',
  database: db,
  provider: provider, // For embeddings
  documents: document.documents
});

// Create agent with RAG
const agent = await createAgent({
  name: 'Document Assistant',
  provider: provider,
  memory: memory,
  chat: chatManager,
  rag: rag, // RAG tools are automatically added
  systemPrompt: 'You are a helpful assistant that can answer questions about documents.'
});

// The agent can now search through documents
const response = await agent.chat({
  message: "What does the document say about climate change?",
  sessionId: "doc-session"
});

Media Analysis

Astreus includes powerful AI-powered media analysis capabilities:

// Analyze images with custom prompts
const imageAnalysis = await agent.analyzeImage({
  imagePath: './screenshot.png',
  prompt: 'What UI elements are visible in this screenshot?',
  detail: 'high'
});

// Analyze documents (PDF, Word, etc.)
const documentAnalysis = await agent.analyzeDocument({
  filePath: './contract.pdf',
  prompt: 'Extract key terms and conditions from this contract'
});

// General media analysis with context
const mediaAnalysis = await agent.analyzeMedia({
  filePath: './presentation.pptx',
  analysisType: 'detailed',
  prompt: 'Summarize the main points of this presentation'
});

Intent Recognition & Smart Tool Selection

Astreus can automatically select the right tools for tasks using LLM-powered intent recognition:

// The agent will automatically determine which tools to use based on the task
const task = agent.createTask({
  name: "Send Email Report",
  description: "Generate a sales report and send it via email to the team",
  input: { period: "Q1 2024" }
});

// Intent recognition will automatically select email and reporting tools
const result = await agent.runTasks([task.id]);

Enhanced Database Features

Astreus provides flexible database management with custom table naming:

// Create memory with custom table name
const memory = await createMemory({
  database: db,
  tableName: "custom_memories",  // Use your own table name
  maxEntries: 1000,
  enableEmbeddings: true
});

// Create chat manager with custom table
const chat = await createChat({
  database: db,
  memory: memory,
  tableName: "custom_chats",     // Use your own table name
  maxChats: 100,
  autoGenerateTitles: true
});

Next Steps

Now that you have a basic agent running with chat management and streaming capabilities, explore these advanced features:

Common Patterns

Simple Chat Bot

const agent = await createAgent({
  provider: createProvider({ type: 'openai' }), // Uses MODEL_NAME from env
  memory: await createMemory({ database: await createDatabase() }),
  chat: await createChat({ database: db, memory: memory })
});

const response = await agent.chat({
  message: "Hello!",
  sessionId: "simple-chat"
});

Streaming Responses

await agent.chat({
  message: "Write a story about AI",
  sessionId: "story-session",
  stream: true,
  onChunk: (chunk) => console.log(chunk)
});

Chat with Metadata

await agent.chatWithId({
  message: "Help me with my project",
  chatId: "project-consultation",
  userId: "user123",
  metadata: { project: "ecommerce", urgency: "high" }
});

Tool-Enabled Agent

const agent = await createAgent({
  provider: provider,
  memory: memory,
  chat: chatManager,
  tools: [weatherTool, calculatorTool],
  systemPrompt: "You are a helpful assistant with access to weather and calculator tools."
});

WebSocket Integration for Real-time Chat

import WebSocket from 'ws';

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', async (ws) => {
  ws.on('message', async (data) => {
    const { message, sessionId } = JSON.parse(data.toString());
    
    // Stream response back to client
    await agent.chat({
      message,
      sessionId,
      stream: true,
      onChunk: (chunk) => {
        ws.send(JSON.stringify({ type: 'chunk', content: chunk }));
      }
    });
    
    // Send completion signal
    ws.send(JSON.stringify({ type: 'complete' }));
  });
});

How is this guide?