Astreus

Agent

Entité IA centrale avec des capacités modulaires et une composition basée sur des décorateurs

Entité IA centrale avec des capacités modulaires et une composition basée sur des décorateurs

Vue d'ensemble

Les agents sont les briques fondamentales d'Astreus. Ils offrent des capacités de conversation intelligente avec des fonctionnalités configurables comme la mémoire, les outils, les bases de connaissances et le traitement de la vision. Chaque agent fonctionne indépendamment avec son propre contexte, sa propre mémoire et ses capacités spécialisées.

Créer un agent

Créer un agent dans Astreus est simple :

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

const agent = await Agent.create({
  name: 'MyAssistant',                        // Unique name for the agent
  model: 'gpt-4o',                            // LLM model to use
  systemPrompt: 'You are a helpful assistant', // Custom instructions
  memory: true                                // Enable persistent memory
});

Choisir le modèle LLM

Astreus prend en charge plusieurs fournisseurs de LLM dès le départ :

const agent = await Agent.create({
  name: 'MyAssistant',
  model: 'gpt-4.5' // Set model here. Latest: 'gpt-4.5', 'claude-sonnet-4-20250514', 'gemini-2.5-pro', 'deepseek-r1'
});

Découvrez les fournisseurs et modèles LLM pris en charge →

Attributs de l'agent

Les agents peuvent être configurés avec divers attributs pour personnaliser leur comportement :

Attributs principaux

interface AgentConfig {
  name: string;                 // Unique identifier for the agent
  description?: string;         // Agent description
  model?: string;              // LLM model to use (default: 'gpt-4o-mini')
  embeddingModel?: string;     // Specific model for embeddings (auto-detected)
  visionModel?: string;        // Specific model for vision (auto-detected)
  temperature?: number;        // Control response randomness (0-1, default: 0.7)
  maxTokens?: number;          // Maximum response length (default: 2000)
  systemPrompt?: string;       // Custom system instructions
  memory?: boolean;            // Enable persistent memory (default: false)
  knowledge?: boolean;         // Enable knowledge base access (default: false)
  vision?: boolean;            // Enable image processing (default: false)
  useTools?: boolean;          // Enable tool/plugin usage (default: true)
  autoContextCompression?: boolean; // Enable smart context management (default: false)
  maxContextLength?: number;    // Token limit before compression (default: 8000)
  preserveLastN?: number;       // Recent messages to keep uncompressed (default: 3)
  compressionRatio?: number;    // Target compression ratio (default: 0.3)
  compressionStrategy?: 'summarize' | 'selective' | 'hybrid'; // Algorithm (default: 'hybrid')
  debug?: boolean;             // Enable debug logging (default: false)
  subAgents?: IAgent[];        // Sub-agents for delegation and coordination
}

RunOptions

Options pour la méthode run() :

interface RunOptions {
  model?: string;                    // Override the agent's model
  temperature?: number;              // Override temperature
  maxTokens?: number;                // Override max tokens
  stream?: boolean;                  // Enable streaming response
  useTools?: boolean;                // Enable/disable tools for this request
  onChunk?: (chunk: string) => void; // Callback for streaming chunks
}

AskOptions

Options pour la méthode ask() (étend RunOptions avec des capacités supplémentaires) :

interface AskOptions {
  model?: string;                    // Override the agent's model
  temperature?: number;              // Override temperature
  maxTokens?: number;                // Override max tokens
  stream?: boolean;                  // Enable streaming response
  useTools?: boolean;                // Enable/disable tools for this request
  onChunk?: (chunk: string) => void; // Callback for streaming chunks
  timeout?: number;                  // Timeout in milliseconds for sub-agent execution

  // Sub-agent options
  useSubAgents?: boolean;            // Enable sub-agent delegation
  delegation?: 'auto' | 'manual' | 'sequential';  // Delegation strategy
  taskAssignment?: Record<string, string>;        // agentId -> task mapping
  coordination?: 'parallel' | 'sequential';       // Sub-agent coordination mode
  contextIsolation?: 'isolated' | 'shared' | 'merge'; // Context handling between agents

  // Attachments
  attachments?: Array<{
    type: 'image' | 'pdf' | 'text' | 'markdown' | 'code' | 'json' | 'file';
    path: string;
    name?: string;
    language?: string;               // For code files
  }>;

  // Temporary MCP servers for this request
  mcpServers?: Array<{
    name: string;
    command?: string;
    args?: string[];
    url?: string;
    cwd?: string;
  }>;

  // Temporary plugins for this request
  plugins?: Array<{
    plugin: {
      name: string;
      version: string;
      description?: string;
      tools?: Array<{
        name: string;
        description: string;
        parameters: Record<string, {
          name: string;
          type: 'string' | 'number' | 'boolean' | 'object' | 'array';
          description: string;
          required?: boolean;
        }>;
        handler: (params: Record<string, unknown>) => Promise<{
          success: boolean;
          data?: unknown;
          error?: string;
        }>;
      }>;
    };
    config?: Record<string, string | number | boolean | null>;
  }>;
}

Exemple avec tous les attributs

// Create sub-agents first
const researcher = await Agent.create({
  name: 'ResearchAgent',
  systemPrompt: 'You are an expert researcher who gathers comprehensive information.'
});

const writer = await Agent.create({
  name: 'WriterAgent',
  systemPrompt: 'You create engaging, well-structured content.'
});

const fullyConfiguredAgent = await Agent.create({
  name: 'AdvancedAssistant',
  description: 'Multi-purpose AI assistant',
  model: 'gpt-4o',
  embeddingModel: 'text-embedding-3-small', // Optional: specific embedding model
  visionModel: 'gpt-4o',                    // Optional: specific vision model
  temperature: 0.7,
  maxTokens: 2000,
  systemPrompt: 'You are an expert software architect...',
  memory: true,
  knowledge: true,
  vision: true,
  useTools: true,
  autoContextCompression: true,
  maxContextLength: 6000,           // Compress at 6000 tokens
  preserveLastN: 4,                 // Keep last 4 messages
  compressionRatio: 0.4,            // 40% compression target
  compressionStrategy: 'hybrid',    // Use hybrid strategy
  debug: true,  // Enable debug logging
  subAgents: [researcher, writer]  // Add sub-agents for delegation
});

Méthodes de l'agent

Méthodes de conversation

// Simple conversation - returns response string
const response = await agent.ask('What is TypeScript?');

// With options
const response = await agent.ask('Analyze this image', {
  temperature: 0.5,
  attachments: [{ type: 'image', path: './screenshot.png' }],
  mcpServers: [{ name: 'search', command: 'npx', args: ['-y', '@anthropic/mcp-search'] }],
  useSubAgents: true,
  delegation: 'auto',
  coordination: 'sequential'
});

// Alternative: run() method (simpler, no sub-agent support)
const response = await agent.run('Hello world');

Méthodes statiques

// Find agent by ID
const agent = await Agent.findById('550e8400-e29b-41d4-a716-446655440000');

// Find agent by name
const agent = await Agent.findByName('MyAssistant');

// List all agents with pagination
const agents = await Agent.list({
  limit: 10,
  offset: 0,
  initialize: false  // Whether to initialize agents (default: false for performance)
});

Méthodes de cycle de vie

// Update agent configuration dynamically
await agent.update({
  temperature: 0.8,
  maxTokens: 3000
});

// Update model at runtime (synchronous)
agent.updateModel('gpt-4o');

// Clear all memory and context
const result = await agent.clearAll();
// Returns: { memoriesCleared: number, contextCleared: boolean }

// Clear session messages (free memory) - synchronous
agent.clearSessionMessages();

// Graceful cleanup and resource disposal
await agent.destroy();

// Delete agent from database
await agent.delete();

Méthodes de gestion du contexte

// Get all context messages
const messages = agent.getContext();
// Returns: ContextMessage[]

// Get context messages (alternative)
const messages = agent.getContextMessages();
// Returns: ContextMessage[]

// Get context window information
const window = agent.getContextWindow();
// Returns: ContextWindow { messages, totalTokens, maxTokens, utilizationPercent }

// Analyze current context
const analysis = agent.analyzeContext();
// Returns: ContextAnalysis { tokenCount, messageCount, roleDistribution, ... }

// Manually compress context
const result = await agent.compressContext();
// Returns: CompressionResult { originalMessageCount, compressedMessageCount, ... }

// Clear context (with optional memory sync)
await agent.clearContext({ syncWithMemory: true });

// Export context as JSON string
const exported = agent.exportContext();

// Import context from JSON string
agent.importContext(exported);

// Generate context summary
const summary = await agent.generateContextSummary();
// Returns: ContextSummary

// Update context model (synchronous)
agent.updateContextModel('gpt-4o');

// Search context messages with filters
const results = agent.searchContext({
  query: 'search term',
  graphId: 'graph-uuid',
  taskId: 'task-uuid',
  sessionId: 'session-uuid',
  role: 'user',  // 'user' | 'assistant' | 'system'
  limit: 10
});

// Load graph-specific context from memory
await agent.loadGraphContext(
  'graph-uuid',    // graphId
  100,             // limit (default: 100)
  false            // isolated - if true, only graph-specific memories (default: false)
);

Accesseurs utilitaires

agent.id          // Agent UUID
agent.name        // Agent name
agent.config      // Full configuration object

agent.hasMemory()     // Check if memory is enabled
agent.hasKnowledge()  // Check if knowledge base is enabled
agent.hasVision()     // Check if vision is enabled
agent.canUseTools()   // Check if tools are enabled

agent.getId()           // Get agent ID
agent.getName()         // Get agent name
agent.getDescription()  // Get agent description (returns string | null)
agent.getModel()        // Get current model
agent.getTemperature()  // Get temperature setting
agent.getMaxTokens()    // Get max tokens setting
agent.getSystemPrompt() // Get system prompt (returns string | null)

Types de réponse

Réponse de ask()

const response = await agent.ask('What is 2+2?');
// Returns: string - The agent's response text

// Example: "2 + 2 equals 4"

Réponse de Agent.list()

const agents = await Agent.list({ limit: 10 });

// Returns array of Agent objects:
[
  {
    id: "550e8400-e29b-41d4-a716-446655440000",
    name: "MyAssistant",
    description: "Helpful assistant",
    model: "gpt-4o",
    // ... other config properties
  }
]

Réponse de clearAll()

const result = await agent.clearAll();

// Returns:
{
  memoriesCleared: 25,    // Number of memories deleted
  contextCleared: true    // Whether context was cleared
}

Dernière mise à jour : 6 juillet 2026