Agent
Zentrale KI-Entität mit modularen Fähigkeiten und dekoratorbasierter Komposition Lerne die Einrichtungsmuster, APIs und praktischen Beispiele kennen, die du...
Zentrale KI-Entität mit modularen Fähigkeiten und dekoratorbasierter Komposition
Übersicht
Agenten sind die grundlegenden Bausteine in Astreus. Sie bieten intelligente Konversationsfähigkeiten mit konfigurierbaren Funktionen wie Speicher, Tools, Wissensdatenbanken und Vision-Verarbeitung. Jeder Agent arbeitet unabhängig mit eigenem Kontext, Speicher und spezialisierten Fähigkeiten.
Einen Agenten erstellen
Einen Agenten in Astreus zu erstellen ist unkompliziert:
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
});Das LLM-Modell auswählen
Astreus unterstützt mehrere LLM-Provider von Haus aus:
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'
});Erfahre mehr über unterstützte LLM-Provider und Modelle →
Agent-Attribute
Agenten können mit verschiedenen Attributen konfiguriert werden, um ihr Verhalten anzupassen:
Kernattribute
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
Optionen für die run()-Methode:
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
Optionen für die ask()-Methode (erweitert RunOptions um zusätzliche Funktionen):
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>;
}>;
}Beispiel mit allen Attributen
// 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
});Agent-Methoden
Konversationsmethoden
// 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');Statische Methoden
// 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)
});Lifecycle-Methoden
// 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();Kontextverwaltungsmethoden
// 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)
);Utility-Getter
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)Antworttypen
ask()-Antwort
const response = await agent.ask('What is 2+2?');
// Returns: string - The agent's response text
// Example: "2 + 2 equals 4"Agent.list()-Antwort
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
}
]clearAll()-Antwort
const result = await agent.clearAll();
// Returns:
{
memoriesCleared: 25, // Number of memories deleted
contextCleared: true // Whether context was cleared
}Zuletzt aktualisiert: 6. Juli 2026
In diesem Abschnitt
Einführung
Open-Source-KI-Agent-Framework zum Erstellen autonomer Systeme, die reale Aufgaben effektiv lösen.
Installation
Installiere Astreus mit npm, yarn oder pnpm, überprüfe die erforderliche Node.js-Version und bereite ein lokales Projekt für die Entwicklung von KI-Agenten...
Gedächtnis
Persistenter Konversationsspeicher mit Vektorsuche und automatischer Kontextintegration Lerne die Einrichtungsmuster, APIs und praktischen Beispiele kennen,...
Kontext
Intelligente Kontextverwaltung für lange Konversationen mit automatischer Komprimierung Lerne die Einrichtungsmuster, APIs und praktischen Beispiele kennen,...