Astreus - Docs

Agents

Agents

Agents are the heart of the Astreus framework. An agent represents an AI assistant that provides a unified interface to all framework capabilities including streaming chat, advanced chat management, memory management, tool execution, and more.

Agent-Centric Architecture

With Astreus, everything revolves around the Agent with enhanced chat management. Instead of managing separate components, you access everything through the agent:

// ✅ Agent-Centric Approach with Chat Management
const agent = await createAgent({
  name: 'MyAgent',
  provider: myProvider,
  memory: myMemory,
  chat: myChatManager // Chat management system
});

// All operations through agent methods
await agent.chat({ message: "Hello!", sessionId: "chat-123", stream: true });
const chats = await agent.listChats({ status: 'active' });
const stats = await agent.getChatStats();
const history = await agent.getHistory("session-1");
const sessions = await agent.listSessions();
const provider = agent.getProvider();
const memory = agent.getMemory();
const database = agent.getDatabase();

Core Agent Capabilities

Each Astreus agent provides:

  • 🚀 Streaming Chat: Real-time responses with agent.chat({ stream: true })
  • 💬 Standard Chat: Non-streaming responses with agent.chat() and agent.chatWithId()
  • 📊 Chat Management: Create, organize, and manage chats with metadata
  • 🔍 Chat Analytics: Search chats, get statistics, and manage chat lifecycle
  • 🧠 Memory Management: Session-based conversation history
  • 📋 Session Tracking: List and manage conversation sessions
  • 🔌 Tool Integration: Add and use custom tools
  • 🗄️ Database Access: Direct access to underlying storage
  • 🎯 Provider Flexibility: Switch models and providers dynamically
  • 🎭 Personality System: Create and assign distinct AI personalities
  • 🖼️ Media Analysis: AI-powered image, document, and file analysis
  • 🤖 Intent Recognition: Smart tool selection based on task context
  • 📋 Enhanced Database: Custom table naming and flexible schema management

Creating an Agent

Use the createAgent function to create a fully-featured agent with chat management:

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

async function createMyAgent() {
  // Initialize the database
  const db = await createDatabase();
  
  // Create memory instance
  const memory = await createMemory({
    database: db,
    tableName: "conversations",
    maxEntries: 200
  });

  // Create chat manager instance
  const chatManager = await createChat({
    database: db,
    memory: memory,
    tableName: "chats",
    maxChats: 100,
    autoGenerateTitles: true
  });

  // Configure your provider
  const provider = createProvider({
    type: 'openai',
    model: 'gpt-4o-mini',
    apiKey: process.env.OPENAI_API_KEY
  });

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

  // Create an agent with all capabilities including chat management and personality
  const agent = await createAgent({
    name: 'MyAssistant',
    description: 'A helpful AI assistant with streaming and chat management capabilities',
    provider: provider,
    memory: memory,
    database: db,
    chat: chatManager, // Chat management system
    personality: personality, // AI personality
    systemPrompt: "You are a helpful AI assistant that provides detailed, accurate responses.",
    tools: [customTool1, customTool2] // Optional tools
  });

  return agent;
}

Chat Management

Create and manage structured chats with metadata and organization:

// Create a new chat with metadata
const chat = await agent.createChat({
  chatId: "consultation-123",
  userId: "user-456",
  title: "Export Regulation Consultation",
  metadata: {
    type: "business",
    priority: "high",
    department: "export",
    language: "en"
  }
});

// Get chat details
const chatDetails = await agent.getChat("consultation-123");
console.log('Chat:', chatDetails);

// Update chat metadata
await agent.updateChat("consultation-123", {
  title: "Updated Export Consultation",
  metadata: { ...chatDetails.metadata, status: "in-progress" }
});

// List chats with filtering
const activeChats = await agent.listChats({
  userId: "user-456",
  status: 'active',
  limit: 20,
  offset: 0
});

// Search chats
const searchResults = await agent.searchChats({
  query: "export regulation",
  userId: "user-456",
  limit: 10
});

// Get chat statistics
const stats = await agent.getChatStats({
  userId: "user-456"
});
console.log(`Total chats: ${stats.totalChats}`);
console.log(`Active chats: ${stats.activeChats}`);
console.log(`Total messages: ${stats.totalMessages}`);

// Archive a chat
await agent.archiveChat("old-chat-id");

// Delete a chat permanently
await agent.deleteChat("unwanted-chat-id");

Streaming Chat

The agent provides streaming capabilities for real-time responses:

// Real-time streaming chat
await agent.chat({
  message: "Explain quantum computing in simple terms",
  sessionId: "physics-chat-123",
  systemPrompt: "You are a physics teacher. Explain concepts clearly.",
  temperature: 0.7,
  maxTokens: 1000,
  metadata: { topic: 'physics', level: 'beginner' },
  stream: true,
  onChunk: (chunk) => {
    // Send chunk to frontend in real-time
    console.log('Chunk:', chunk);
    // websocket.send(JSON.stringify({ type: 'chunk', content: chunk }));
  }
});

// Streaming with chat ID (creates chat if it doesn't exist)
await agent.chat({
  message: "Tell me about machine learning",
  sessionId: "ml-discussion",
  temperature: 0.6,
  stream: true,
  onChunk: (chunk) => {
    process.stdout.write(chunk);
  }
});

Standard Chat with Chat IDs

For non-streaming scenarios, use the enhanced chat methods:

// Standard chat with chat ID (recommended)
const response = await agent.chatWithId({
  message: "What's the weather like?",
  chatId: "weather-chat-123",
  userId: "user-456",
  temperature: 0.5,
  metadata: { location: "New York" }
});

// Standard chat with session ID
const sessionResponse = await agent.chat({
  message: "Hello!",
  sessionId: "simple-session",
  temperature: 0.7
});

Memory and Session Management

Access and manage conversation history through the agent:

// Get conversation history for a session/chat
const history = await agent.getHistory("chat-123", 20);
console.log(`Found ${history.length} messages`);

// Add custom memory entries
await agent.addToMemory({
  sessionId: "chat-123",
  role: 'system',
  content: "User prefers detailed technical explanations",
  metadata: { preference: 'technical', timestamp: new Date() }
});

// Clear conversation history
await agent.clearHistory("old-session");

// List all sessions with metadata
const sessions = await agent.listSessions(50);
sessions.forEach(session => {
  console.log(`Session: ${session.sessionId}`);
  console.log(`Messages: ${session.messageCount}`);
  console.log(`Last activity: ${session.lastActivity}`);
});

// Access memory directly for advanced operations
const memory = agent.getMemory();
const searchResults = await memory.searchByText("quantum", 10);
console.log('Quantum-related messages:', searchResults);

Tool Management

Add and manage tools through the 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);

// Get available tool names
const toolNames = agent.getAvailableTools();
console.log('Available tools:', toolNames);

// The agent will automatically use tools when appropriate
const response = await agent.chat({
  message: "What's the weather in London?",
  sessionId: "weather-session"
});

Plugin Integration

Use plugins to extend agent capabilities:

import { XPlugin } from '@astreus-ai/x-plugin';

// Initialize plugin with configuration
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
});

// Initialize the plugin
await xPlugin.init();

// Create agent with plugins
const agent = await createAgent({
  name: 'Social Media Agent',
  provider: provider,
  memory: memory,
  chat: chatManager,
  plugins: [xPlugin], // Plugins provide multiple tools
  systemPrompt: "You are a social media assistant with access to X (Twitter) tools."
});

// Plugin tools are automatically available
const response = await agent.chat({
  message: "Post a tweet about AI advancements",
  sessionId: "social-session"
});

RAG Integration

Add document search capabilities to your agent:

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

// Parse documents
const document = await parsePDF('technical-manual.pdf', {
  splitStrategy: 'section',
  chunkSize: 1000
});

// Create RAG system
const rag = await createRAG({
  type: 'vector',
  database: db,
  provider: provider,
  tableName: 'technical_docs'
});

// Add documents to RAG system
for (const doc of document.documents) {
  await rag.addDocument(doc);
}

// 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 technical assistant that can search through documentation.'
});

// Agent can now search documents
const response = await agent.chat({
  message: "How do I configure the SSL settings?",
  sessionId: "tech-support"
});

Media Analysis

Astreus agents include 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'
});

console.log('Image analysis:', imageAnalysis);

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

console.log('Document analysis:', documentAnalysis);

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

console.log('Media analysis:', mediaAnalysis);

// Analyze with additional context
const contextualAnalysis = await agent.analyzeWithContext({
  filePath: './chart.png',
  prompt: 'What trends are shown in this chart?',
  context: 'This chart shows sales data for Q1 2024',
  detail: 'auto'
});

Intent Recognition & Smart Tool Selection

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

import { IntentRecognizer } from '@astreus-ai/astreus';

// Create an intent recognizer
const intentRecognizer = new IntentRecognizer({
  provider: provider,
  tools: [weatherTool, emailTool, calculatorTool]
});

// Create agent with intent recognition
const agent = await createAgent({
  name: 'Smart Assistant',
  provider: provider,
  memory: memory,
  chat: chatManager,
  tools: [weatherTool, emailTool, calculatorTool],
  intentRecognizer: intentRecognizer,
  systemPrompt: 'You are a smart assistant that can automatically select the right tools for tasks.'
});

// The agent will automatically determine which tools to use based on the task
const task = agent.createTask({
  name: "Send Weather Report",
  description: "Check the weather in New York and send a summary email",
  input: { location: "New York", recipient: "team@company.com" }
});

// Intent recognition will automatically select weather and email 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 chatManager = await createChat({
  database: db,
  memory: memory,
  tableName: "custom_chats",     // Use your own table name
  maxChats: 100,
  autoGenerateTitles: true
});

// Create agent with custom configuration
const agent = await createAgent({
  name: 'Custom Agent',
  provider: provider,
  memory: memory,
  chat: chatManager,
  database: db,
  systemPrompt: 'You are a customized assistant with enhanced database capabilities.'
});

Accessing Components

Get direct access to underlying components when needed:

// Access provider
const provider = agent.getProvider();
if (provider) {
  console.log('Available models:', provider.listModels());
  console.log('Current model:', agent.getModel().name);
}

// Access database
const database = agent.getDatabase();
if (database) {
  const customQuery = await database.knex('memories')
    .where('agentId', agent.id)
    .count('* as total');
  console.log('Total memories:', customQuery[0].total);
}

// Access memory
const memory = agent.getMemory();
const agentMemories = await memory.getByAgent(agent.id, 50);
console.log(`Agent has ${agentMemories.length} memories`);

// Access chat manager
const chatManager = agent.getChatManager();
if (chatManager) {
  const allChats = await chatManager.listChats({ agentId: agent.id });
  console.log(`Agent has ${allChats.length} chats`);
}

// Access task manager
const taskManager = agent.getTaskManager();
if (taskManager) {
  const tasks = taskManager.getAllTasks();
  console.log(`Agent has ${tasks.length} tasks`);
}

// Access RAG system
const rag = agent.getRAG();
if (rag) {
  const results = await rag.search("technical documentation", 5);
  console.log(`Found ${results.length} relevant documents`);
}

Agent Configuration

The agent configuration supports many options:

const agent = await createAgent({
  // Basic configuration
  id: 'custom-agent-id', // Optional: auto-generated if not provided
  name: 'MyAgent', // Optional: defaults to 'astreus-agent'
  description: 'A helpful AI assistant', // Optional
  
  // Required components
  memory: memory, // Required: memory instance
  
  // Provider configuration (either model or provider required)
  model: specificModel, // Option 1: Use specific model
  provider: provider, // Option 2: Use provider (model auto-selected)
  
  // Optional components
  database: db, // Optional: auto-created if not provided
  chat: chatManager, // Optional: enables chat management
  taskManager: taskManager, // Optional: enables task system
  rag: ragSystem, // Optional: enables document search
  
  // Behavior configuration
  systemPrompt: "You are a helpful assistant", // Optional
  
  // Tools and plugins
  tools: [tool1, tool2], // Optional: custom tools
  plugins: [plugin1, plugin2] // Optional: plugin instances
});

Best Practices

1. Use Chat IDs for Structured Conversations

// ✅ Good: Use chatWithId for structured conversations
await agent.chatWithId({
  message: "Help with my project",
  chatId: "project-consultation",
  userId: "user123"
});

// Session-based chat
await agent.chat({
  message: "Help with my project",
  sessionId: "project-session"
});

2. Leverage Chat Metadata

// ✅ Good: Use metadata for organization
await agent.createChat({
  chatId: "support-ticket-456",
  userId: "customer123",
  title: "Payment Issue",
  metadata: {
    category: "billing",
    priority: "high",
    department: "support",
    created: new Date()
  }
});

3. Use Streaming for Long Responses

// ✅ Good: Stream long responses
await agent.chat({
  message: "Write a detailed report on AI trends",
  sessionId: "report-session",
  stream: true,
  onChunk: (chunk) => updateUI(chunk)
});

4. Organize Tools by Purpose

// ✅ Good: Group related tools
const weatherTools = [weatherTool, forecastTool];
const calculationTools = [calculatorTool, converterTool];

const agent = await createAgent({
  name: 'Multi-Purpose Assistant',
  provider: provider,
  memory: memory,
  tools: [...weatherTools, ...calculationTools]
});

5. Use RAG for Knowledge-Based Tasks

// ✅ Good: Add RAG for document-based assistance
const agent = await createAgent({
  name: 'Knowledge Assistant',
  provider: provider,
  memory: memory,
  rag: ragSystem, // Automatically adds search tools
  systemPrompt: 'You are a knowledgeable assistant with access to company documentation.'
});

Error Handling

Implement proper error handling for agent operations:

try {
  const response = await agent.chat({
    message: "Complex query",
    sessionId: "error-test"
  });
} catch (error) {
  if (error.message.includes('ChatManager is required')) {
    console.error('Chat manager not configured');
    // Configure chat manager
  } else if (error.message.includes('No model could be determined')) {
    console.error('Provider or model not properly configured');
    // Check provider configuration
  } else {
    console.error('Unexpected error:', error);
  }
}

Next Steps

  • Learn about Chat Management for advanced conversation handling
  • Explore Memory for conversation storage and retrieval
  • Check out Providers for different LLM integrations
  • See Plugins for extending agent capabilities
  • Read about RAG for document search integration

How is this guide?