Astreus

Task

Esecuzione strutturata dei task con tracciamento dello stato e integrazione degli strumenti

Esecuzione strutturata dei task con tracciamento dello stato e integrazione degli strumenti

Panoramica

I Task offrono un modo per organizzare ed eseguire operazioni complesse con i tuoi agent. Supportano il tracciamento dello stato, l'utilizzo di strumenti e possono essere composti in workflow più ampi. Ogni task può avere dipendenze, eseguire azioni specifiche e mantenere il proprio stato durante l'intera esecuzione.

Creare i Task

I task vengono creati tramite gli agent usando un approccio semplice basato su prompt:

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

Attributi del Task

I task possono essere configurati con i seguenti attributi:

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

Dettagli degli attributi

  • prompt: l'istruzione o la richiesta principale per il task. È l'unico campo obbligatorio.
  • graphId: UUID del grafo a cui appartiene questo task. Usato quando i task fanno parte di un workflow a grafo.
  • graphNodeId: UUID del nodo del grafo che ha creato questo task. Usato per tracciare l'origine del task nei workflow a grafo.
  • useTools: controlla se il task può usare strumenti/plugin. Il valore predefinito è true (eredita dall'agent se non specificato).
  • mcpServers: server MCP (Model Context Protocol) specifici del task da abilitare per questo task.
  • plugins: plugin specifici del task da registrare per questa esecuzione.
  • attachments: array di file da allegare al task. Supporta immagini, PDF, file di testo, file di codice e altro.
  • schedule: stringa di pianificazione semplice per l'esecuzione basata sul tempo (ad es. 'daily@07:00', 'weekly@monday@09:00'). Campo opzionale che abilita la pianificazione automatica quando usato con i grafi.
  • metadata: coppie chiave-valore personalizzate per organizzare e tracciare i task (ad es. categoria, priorità, tag).
  • executionContext: metadati di esecuzione aggiuntivi come record di coppie chiave-valore. Utile per passare informazioni di contesto a runtime.

Integrazione con i Sub-Agent

  • useSubAgents: abilita la delega ai sub-agent per questo specifico task. Quando è true, l'agent principale delegherà in modo intelligente parti del task ai suoi sub-agent registrati.
  • subAgentDelegation: strategia per la delega dei task:
    • 'auto': distribuzione intelligente dei task basata sull'AI, in base alle capacità dei sub-agent
    • 'manual': assegnazione esplicita dei task tramite la mappatura taskAssignment
    • 'sequential': i sub-agent lavorano in sequenza, costruendo sui risultati precedenti
  • subAgentCoordination: pattern di coordinamento per l'esecuzione dei sub-agent:
    • 'parallel': i sub-agent lavorano simultaneamente per la massima efficienza
    • 'sequential': i sub-agent lavorano in ordine con passaggio del contesto tra loro
  • taskAssignment: mappatura per l'assegnazione manuale dei task (usata solo con subAgentDelegation: 'manual'). Mappa gli ID degli agent a istruzioni di task specifiche.

Ciclo di vita del Task

I task attraversano diversi stati durante l'esecuzione:

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

Pending

Il task è stato creato ma non ancora avviato. In attesa di esecuzione o di dipendenze.

2

In Progress

Il task è in fase di esecuzione attiva da parte dell'agent. Gli strumenti possono essere usati durante questa fase.

3

Completed

Il task è terminato con successo e i risultati sono disponibili.

4

Failed

Il task ha riscontrato un errore durante l'esecuzione. I dettagli dell'errore sono disponibili.

Esempio con allegati e strumenti

Ecco un esempio completo che mostra task con allegati di file e integrazione degli strumenti:

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

Delega dei Task ai Sub-Agent

I task ora supportano la delega ai sub-agent direttamente tramite la creazione e l'esecuzione dei task:

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

Alternativa: metodi dell'Agent per l'esecuzione con Sub-Agent

Puoi anche sfruttare i sub-agent tramite i metodi dell'agent per un'esecuzione immediata:

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

Vantaggi della delega ai Sub-Agent a livello di Task

  • Configurazione persistente: le impostazioni dei sub-agent sono memorizzate con il task e persistono tra le sessioni
  • Workflow riproducibili: le definizioni dei task possono essere riutilizzate con un comportamento coerente dei sub-agent
  • Esecuzione flessibile: i task possono essere eseguiti immediatamente o pianificati per dopo con lo stesso coordinamento dei sub-agent
  • Audit trail: i metadati del task includono la cronologia della delega ai sub-agent per il tracciamento e il debug

Gestire i Task

I task possono essere gestiti e tracciati durante il loro intero ciclo di vita:

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

Tipi di risposta

Capire le risposte dei task ti aiuta a gestire i risultati di esecuzione e a tracciare il ciclo di vita del task.

Risposta dell'oggetto Task

Creare o recuperare un task restituisce un oggetto Task completo:

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
}

Risposta di esecuzione del Task

Eseguire un task restituisce un TaskResponse con i dettagli dell'esecuzione:

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

Risposta della lista dei Task

Elencare i task restituisce un array di oggetti 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(...)
  }
]

Risposta di aggiornamento del Task

Aggiornare un task restituisce l'oggetto Task aggiornato oppure null se non trovato:

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'),
  ...
}

Risposta di Get Task

Recuperare un task specifico restituisce l'oggetto Task oppure null:

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

// Returns: Task object or null if not found

Risposta di eliminazione del Task

Eliminare un task restituisce un booleano che indica il successo:

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

Risposta di Clear Tasks

Cancellare tutti i task restituisce il conteggio dei task eliminati:

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

Ultimo aggiornamento: 6 luglio 2026