Astreus

タスク

Astreusのドキュメントでタスクについて学び、エージェントシステムを構築するためのセットアップの手引き、APIのパターン、実践的な例を確認しましょう。 信頼性の高いAstreusエージェントシステムを構築するために必要なセットアップのパターン、API、実践的な例を学びましょう。

ステータス追跡とツール統合を備えた、構造化されたタスク実行

概要

タスクは、エージェントで複雑な操作を整理し実行するための方法を提供します。ステータス追跡、ツールの使用をサポートし、より大きなワークフローに組み込むことができます。各タスクは依存関係を持ち、特定のアクションを実行し、実行を通じて独自の状態を維持できます。

タスクの作成

タスクは、シンプルなプロンプトベースのアプローチでエージェントを通じて作成されます。

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日