Astreus

任务

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

具备状态跟踪和工具集成能力的结构化任务执行

概述

任务(Task)提供了一种组织和执行代理复杂操作的方式。它们支持状态跟踪、工具调用,并可组合成更大的工作流。每个任务都可以有依赖关系,执行特定操作,并在整个执行过程中维护自身状态。

创建任务

任务通过代理以简单的基于提示词的方式创建:

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

const agent = await Agent.create({
  name: 'TaskAgent',
  model: 'gpt-4o'
});

// Create a task
const task = await agent.createTask({
  prompt: 'Analyze the TypeScript code and suggest performance improvements'
});

// Execute the task
const result = await agent.executeTask(task.id);
console.log(result.response);

任务属性

任务可以通过以下属性进行配置:

interface TaskRequest {
  prompt: string;              // The task instruction or query
  graphId?: string;            // UUID - Graph this task belongs to
  graphNodeId?: string;        // UUID - Graph node creating this task
  useTools?: boolean;          // Enable/disable tool usage (default: true)
  mcpServers?: MCPServerDefinition[]; // Task-level MCP servers
  plugins?: Array<{            // Task-level plugins
    plugin: Plugin;
    config?: PluginConfig;
  }>;
  attachments?: Array<{        // Files to attach to the task
    type: 'image' | 'pdf' | 'text' | 'markdown' | 'code' | 'json' | 'file';
    path: string;              // File path
    name?: string;             // Display name
    language?: string;         // Programming language (for code files)
  }>;
  schedule?: string;           // Simple schedule string (e.g., 'daily@07:00', 'weekly@monday@09:00')
  metadata?: MetadataObject;   // Custom metadata for tracking
  executionContext?: Record<string, unknown>; // Additional execution metadata
  useSubAgents?: boolean;                        // Enable sub-agent delegation for this task
  subAgentDelegation?: 'auto' | 'manual' | 'sequential'; // Delegation strategy
  subAgentCoordination?: 'parallel' | 'sequential';      // How sub-agents coordinate
  taskAssignment?: Record<string, string>;               // Manual task assignment (agentId UUID -> task)
}

属性详解

  • prompt:任务的主要指令或查询内容。这是唯一必填字段。
  • graphId:该任务所属图的 UUID。当任务是图工作流的一部分时使用。
  • graphNodeId:创建此任务的图节点的 UUID。用于在图工作流中追踪任务来源。
  • useTools:控制该任务是否可以使用工具/插件。默认为 true(若未指定则继承自代理)。
  • mcpServers:该任务专属启用的 MCP(Model Context Protocol)服务器。
  • plugins:该任务执行时注册的专属插件。
  • attachments:附加到任务的文件数组。支持图片、PDF、文本文件、代码文件等。
  • schedule:用于基于时间执行的简单调度字符串(例如 'daily@07:00''weekly@monday@09:00')。可选字段,与图搭配使用时可启用自动调度。
  • metadata:用于组织和跟踪任务的自定义键值对(例如类别、优先级、标签)。
  • executionContext:附加的执行元数据,以键值对记录形式存在。可用于传递运行时上下文信息。

子代理集成

  • useSubAgents:为此特定任务启用子代理委派。设为 true 时,主代理会智能地将任务的部分内容委派给已注册的子代理。
  • subAgentDelegation:任务委派策略:
    • 'auto':基于子代理能力的 AI 智能任务分配
    • 'manual':使用 taskAssignment 映射进行明确的任务分配
    • 'sequential':子代理按顺序工作,基于前一个结果进行处理
  • subAgentCoordination:子代理执行的协作方式:
    • 'parallel':子代理同时工作以获得最高效率
    • 'sequential':子代理按顺序工作,并在彼此之间传递上下文
  • taskAssignment:手动任务分配映射(仅在 subAgentDelegation: 'manual' 时使用)。将代理 ID 映射到具体的任务指令。

任务生命周期

任务在执行过程中会经历多个状态:

type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'failed';
1

待处理(Pending)

任务已创建但尚未开始。等待执行或等待依赖项完成。

2

进行中(In Progress)

任务正由代理主动执行。此阶段可能会用到工具。

3

已完成(Completed)

任务已成功完成,结果可用。

4

失败(Failed)

任务执行过程中遇到错误。可以查看错误详情。

附件与工具示例

以下是一个完整示例,展示带有文件附件和工具集成的任务:

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

// Create an agent
const agent = await Agent.create({
  name: 'CodeReviewAssistant',
  model: 'gpt-4o',
  vision: true // Enable vision for screenshots
});

// Code review task with multiple file types
const codeReviewTask = await agent.createTask({
  prompt: `Please perform a comprehensive code review:
    1. Check for security vulnerabilities
    2. Identify performance issues
    3. Suggest improvements for code quality
    4. Review the UI mockup for usability issues`,
  attachments: [
    { 
      type: 'code', 
      path: './src/auth/login.ts', 
      name: 'Login Controller',
      language: 'typescript' 
    },
    { 
      type: 'code', 
      path: './src/middleware/security.js', 
      name: 'Security Middleware',
      language: 'javascript' 
    },
    { 
      type: 'json', 
      path: './package.json', 
      name: 'Package Dependencies' 
    },
    { 
      type: 'image', 
      path: './designs/login-mockup.png', 
      name: 'Login UI Mockup' 
    },
    { 
      type: 'markdown', 
      path: './docs/security-requirements.md', 
      name: 'Security Requirements' 
    }
  ],
  metadata: {
    type: 'code-review',
    priority: 'high',
    reviewer: 'ai-assistant'
  }
});

// Execute task with streaming
const result = await agent.executeTask(codeReviewTask.id, {
  model: 'gpt-4o',  // Override model for this task
  stream: true      // Enable streaming response
});

console.log('Code review completed:', result.response);

// Documentation task with text files
const docTask = await agent.createTask({
  prompt: 'Update the API documentation based on the latest code changes',
  attachments: [
    { type: 'text', path: '/api/routes.txt', name: 'API Routes' },
    { type: 'markdown', path: '/README.md', name: 'Current Documentation' }
  ]
});

// List tasks with attachments
const tasksWithFiles = await agent.listTasks({
  orderBy: 'createdAt',
  order: 'desc'
});

tasksWithFiles.forEach(task => {
  console.log(`Task ${task.id}: ${task.status}`);
  if (task.metadata?.attachments) {
    console.log(`  - Has attachments`);
  }
  if (task.completedAt) {
    console.log(`  - Completed: ${task.completedAt.toISOString()}`);
  }
});

子代理任务委派

现在任务支持直接通过任务创建和执行来实现子代理委派:

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

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

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

const mainAgent = await Agent.create({
  name: 'ContentCoordinator',
  subAgents: [researcher, writer]
});

// Create task with automatic sub-agent delegation
const autoTask = await mainAgent.createTask({
  prompt: 'Research renewable energy trends and write a comprehensive report',
  useSubAgents: true,
  subAgentDelegation: 'auto',
  subAgentCoordination: 'sequential',
  metadata: { type: 'research-report', priority: 'high' }
});

// Create task with manual sub-agent assignment
const manualTask = await mainAgent.createTask({
  prompt: 'Create market analysis presentation',
  useSubAgents: true,
  subAgentDelegation: 'manual',
  subAgentCoordination: 'parallel',
  taskAssignment: {
    [researcher.id]: 'Research market data and competitor analysis',
    [writer.id]: 'Create presentation slides and executive summary'
  },
  metadata: { type: 'presentation', deadline: '2024-12-01' }
});

// Execute tasks - sub-agent coordination happens automatically
const autoResult = await mainAgent.executeTask(autoTask.id);
const manualResult = await mainAgent.executeTask(manualTask.id);

console.log('Auto-delegated result:', autoResult.response);
console.log('Manually-assigned result:', manualResult.response);

替代方案:通过代理方法执行子代理

你也可以通过代理方法即时使用子代理:

// Direct execution with sub-agent delegation via agent.ask()
const result = await mainAgent.ask('Research renewable energy trends and write report', {
  useSubAgents: true,
  delegation: 'auto',
  coordination: 'sequential'
});

// Manual delegation with specific task assignments
const manualResult = await mainAgent.ask('Create market analysis presentation', {
  useSubAgents: true,
  delegation: 'manual',
  coordination: 'parallel',
  taskAssignment: {
    [researcher.id]: 'Research market data and competitor analysis',
    [writer.id]: 'Create presentation slides and executive summary'
  }
});

任务级子代理委派的优势

  • 持久化配置:子代理设置随任务一起存储,并在多个会话之间持续保留
  • 可复用的工作流:任务定义可以复用,并保持一致的子代理行为
  • 灵活执行:任务可以立即执行,也可以安排在稍后以相同的子代理协作方式执行
  • 审计追踪:任务元数据包含子代理委派历史,便于追踪和调试

管理任务

任务可以在整个生命周期中被管理和跟踪:

// Update task with additional metadata
await agent.updateTask(task.id, {
  metadata: {
    ...task.metadata,
    progress: 50,
    estimatedCompletion: new Date()
  }
});

// Delete a specific task
await agent.deleteTask(task.id);

// Clear all tasks for an agent
const deletedCount = await agent.clearTasks();
console.log(`Deleted ${deletedCount} tasks`);

// Search tasks with filters
const pendingTasks = await agent.listTasks({
  status: 'pending',
  limit: 5
});

const recentTasks = await agent.listTasks({
  orderBy: 'completedAt',
  order: 'desc',
  limit: 10
});

// Filter tasks by graph
const graphTasks = await agent.listTasks({
  graphId: 'graph-uuid-123',
  orderBy: 'createdAt',
  order: 'asc'
});

响应类型

理解任务响应有助于处理执行结果并跟踪任务生命周期。

任务对象响应

创建或获取任务会返回一个完整的 Task 对象:

const task = await agent.createTask({
  prompt: "Analyze this data",
  useTools: true,
  metadata: { priority: "high" }
});

// Response structure (Task interface):
{
  id: "550e8400-e29b-41d4-a716-446655440000",  // UUID string
  agentId: "agent-uuid-123",                    // UUID string
  graphId?: "graph-uuid-456",                   // UUID string if part of a graph
  graphNodeId?: "node-uuid-789",                // UUID string if created by graph node
  prompt: "Analyze this data",
  response?: "Analysis result...",              // Filled after execution
  status: "pending",                            // 'pending' | 'in_progress' | 'completed' | 'failed'
  metadata?: {
    priority: "high"
  },
  executionContext?: {},                        // Additional execution metadata
  createdAt: Date('2024-01-15T10:30:00Z'),
  updatedAt: Date('2024-01-15T10:30:00Z'),
  completedAt?: Date('2024-01-15T10:35:00Z')   // Filled after completion
}

任务执行响应

执行任务会返回一个包含执行详情的 TaskResponse:

const result = await agent.executeTask("task-uuid-123", {
  model: "gpt-4",
  stream: false
});

// Response structure (TaskResponse interface):
{
  task: {
    id: "task-uuid-123",
    agentId: "agent-uuid",
    graphId?: "graph-uuid",           // If part of a graph
    graphNodeId?: "node-uuid",        // If created by graph node
    prompt: "Analyze this data",
    response: "Analysis complete: The data shows a 15% increase...",
    status: "completed",
    metadata?: { priority: "high" },
    executionContext?: {},            // Additional execution metadata
    createdAt: Date('2024-01-15T10:30:00Z'),
    updatedAt: Date('2024-01-15T10:35:00Z'),
    completedAt: Date('2024-01-15T10:35:00Z')
  },
  response: "Analysis complete: The data shows a 15% increase in user engagement...",
  model?: "gpt-4",
  usage?: {
    promptTokens: 150,
    completionTokens: 300,
    totalTokens: 450
  }
}

任务列表响应

列出任务会返回一个 Task 对象数组:

const tasks = await agent.listTasks({
  status: 'completed',
  orderBy: 'completedAt',
  order: 'desc',
  limit: 10,
  offset: 0,           // Pagination offset
  graphId: 'optional'  // Filter by graph ID (UUID)
});

// Response structure (Task[] array):
[
  {
    id: "task-uuid-1",
    agentId: "agent-uuid",
    graphId?: "graph-uuid",        // If part of a graph
    graphNodeId?: "node-uuid",     // If created by graph node
    prompt: "First task",
    response?: "First task completed",
    status: "completed",
    metadata?: {},
    executionContext?: {},
    createdAt: Date(...),
    updatedAt: Date(...),
    completedAt?: Date(...)
  },
  {
    id: "task-uuid-2",
    agentId: "agent-uuid",
    graphId?: "graph-uuid",
    graphNodeId?: "node-uuid",
    prompt: "Second task",
    response?: "Second task completed",
    status: "completed",
    metadata?: {},
    executionContext?: {},
    createdAt: Date(...),
    updatedAt: Date(...),
    completedAt?: Date(...)
  }
]

更新任务响应

更新任务会返回更新后的 Task 对象,若未找到则返回 null:

const updated = await agent.updateTask("task-uuid", {
  metadata: { progress: 50, estimatedCompletion: new Date() }
});

// Response: Task object with updated fields or null
{
  id: "task-uuid",
  agentId: "agent-uuid",
  prompt: "Original prompt",
  status: "in_progress",
  metadata: {
    priority: "high",
    progress: 50,
    estimatedCompletion: Date('2024-01-15T12:00:00Z')
  },
  updatedAt: Date('2024-01-15T10:40:00Z'),
  ...
}

获取任务响应

获取指定任务会返回 Task 对象,若未找到则返回 null:

const task = await agent.getTask("task-uuid");

// Returns: Task object or null if not found

删除任务响应

删除任务会返回一个布尔值,指示是否成功:

const deleted = await agent.deleteTask("task-uuid");
// Returns: true or false

清除任务响应

清除所有任务会返回被删除任务的数量:

const deletedCount = await agent.clearTasks();
// Returns: 25 (number of tasks deleted)

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