Astreus

智能体

在 Astreus 文档中了解 智能体,获取用于构建智能体系统的设置指导、API 模式和实用示例。 了解构建可靠的 Astreus 智能体系统所需的设置模式、API 和实用示例。

具备模块化能力和基于装饰器组合方式的核心 AI 实体

概述

代理(Agent)是 Astreus 中的基本构建单元。它们提供智能对话能力,并可配置记忆、工具、知识库和视觉处理等功能。每个代理都独立运行,拥有各自的上下文、记忆和专属能力。

创建代理

在 Astreus 中创建代理非常简单:

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
});

选择 LLM 模型

Astreus 开箱即支持多个 LLM 提供方:

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

了解支持的 LLM 提供方与模型 →

代理属性

代理可以通过多种属性进行配置,以自定义其行为:

核心属性

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

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

ask() 方法可用的选项(在 RunOptions 基础上扩展了更多功能):

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>;
  }>;
}

包含所有属性的示例

// 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
});

代理方法

对话方法

// 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');

静态方法

// 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)
});

生命周期方法

// 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();

上下文管理方法

// 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)
);

实用 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)

响应类型

ask() 响应

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

// Example: "2 + 2 equals 4"

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
  }
]

clearAll() 响应

const result = await agent.clearAll();

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

最后更新时间:2026年7月6日