작업
Astreus 문서에서 작업에 대해 알아보고, 에이전트 시스템을 구축하기 위한 설정 안내, API 패턴, 실용적인 예제를 확인하세요. 안정적인 Astreus 에이전트 시스템을 구축하는 데 필요한 설정 패턴, API, 실용적인 예제를 알아보세요.
상태 추적과 도구 통합을 갖춘 구조화된 작업 실행
Overview
작업(Task)은 에이전트를 통해 복잡한 작업을 구성하고 실행하는 방법을 제공합니다. 상태 추적, 도구 사용을 지원하며 더 큰 워크플로우로 구성할 수 있습니다. 각 작업은 종속성을 가질 수 있고, 특정 작업을 실행하며, 실행 전 과정에서 자체 상태를 유지합니다.
Creating Tasks
작업은 간단한 프롬프트 기반 방식으로 에이전트를 통해 생성됩니다.
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);Task Attributes
작업은 다음 속성으로 설정할 수 있습니다.
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)
}Attribute Details
- 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: 키-값 쌍 레코드 형태의 추가 실행 메타데이터입니다. 런타임 컨텍스트 정보를 전달할 때 유용합니다.
Sub-Agent Integration
- useSubAgents: 이 특정 작업에 대한 서브 에이전트 위임을 활성화합니다.
true인 경우, 메인 에이전트가 등록된 서브 에이전트들에게 작업의 일부를 지능적으로 위임합니다. - subAgentDelegation: 작업 위임 전략:
'auto': 서브 에이전트의 역량에 기반한 AI 기반 지능적 작업 분배'manual':taskAssignment매핑을 사용한 명시적 작업 할당'sequential': 서브 에이전트가 순서대로 작업하며 이전 결과를 기반으로 진행
- subAgentCoordination: 서브 에이전트 실행의 협업 패턴:
'parallel': 최대 효율을 위해 서브 에이전트가 동시에 작업'sequential': 서브 에이전트가 컨텍스트를 전달하며 순서대로 작업
- taskAssignment: 수동 작업 할당 매핑입니다 (
subAgentDelegation: 'manual'과 함께 사용될 때만 적용). 에이전트 ID를 특정 작업 지시사항에 매핑합니다.
Task Lifecycle
작업은 실행 중 여러 상태를 거칩니다.
type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'failed';Pending
작업이 생성되었지만 아직 시작되지 않았습니다. 실행 또는 종속성 대기 중입니다.
In Progress
작업이 에이전트에 의해 실제로 실행되고 있습니다. 이 단계에서 도구가 사용될 수 있습니다.
Completed
작업이 성공적으로 완료되었으며 결과를 사용할 수 있습니다.
Failed
작업 실행 중 오류가 발생했습니다. 오류 세부 정보를 확인할 수 있습니다.
Example with Attachments and Tools
파일 첨부와 도구 통합을 갖춘 작업의 완전한 예제입니다.
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()}`);
}
});Sub-Agent Task Delegation
이제 작업은 작업 생성과 실행을 통해 직접 서브 에이전트 위임을 지원합니다.
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);Alternative: Agent Methods for Sub-Agent Execution
즉시 실행을 위해 에이전트 메서드를 통해 서브 에이전트를 활용할 수도 있습니다.
// 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'
}
});Benefits of Task-Level Sub-Agent Delegation
- 영구적인 설정: 서브 에이전트 설정이 작업과 함께 저장되어 세션 간에 유지됩니다
- 재현 가능한 워크플로우: 작업 정의를 재사용해도 일관된 서브 에이전트 동작을 얻을 수 있습니다
- 유연한 실행: 작업을 즉시 실행하거나 동일한 서브 에이전트 협업으로 나중에 예약할 수 있습니다
- 감사 추적: 작업 메타데이터에 서브 에이전트 위임 이력이 포함되어 추적과 디버깅에 활용됩니다
Managing Tasks
작업은 생애주기 전반에 걸쳐 관리하고 추적할 수 있습니다.
// 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'
});Response Types
작업 응답을 이해하면 실행 결과를 처리하고 작업 생애주기를 추적하는 데 도움이 됩니다.
Task Object Response
작업을 생성하거나 조회하면 완전한 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
}Task Execution Response
작업을 실행하면 실행 세부 정보를 담은 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 List Response
작업 목록 조회는 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(...)
}
]Update Task Response
작업을 업데이트하면 업데이트된 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'),
...
}Get Task Response
특정 작업을 조회하면 Task 객체 또는 null을 반환합니다.
const task = await agent.getTask("task-uuid");
// Returns: Task object or null if not foundDelete Task Response
작업을 삭제하면 성공 여부를 나타내는 불리언 값을 반환합니다.
const deleted = await agent.deleteTask("task-uuid");
// Returns: true or falseClear Tasks Response
모든 작업을 삭제하면 삭제된 작업 수를 반환합니다.
const deletedCount = await agent.clearTasks();
// Returns: 25 (number of tasks deleted)마지막 업데이트: 2026년 7월 6일
이 섹션에서
소개
실제 작업을 효과적으로 해결하는 자율 시스템을 구축하기 위한 오픈소스 AI 에이전트 프레임워크입니다. 안정적인 Astreus 에이전트 시스템을 구축하는 데 필요한 설정 패턴, API, 실용적인 예제를 알아보세요.
설치
npm, yarn, pnpm을 사용해 Astreus를 설치하고, 필요한 Node.js 버전을 확인한 다음 프레임워크로 AI 에이전트를 구축할 로컬 프로젝트를 준비합니다.
빠른 시작
Astreus 문서에서 빠른 시작에 대해 알아보고, 에이전트 시스템을 구축하기 위한 설정 안내, API 패턴, 실용적인 예제를 확인하세요. 안정적인 Astreus 에이전트 시스템을 구축하는 데 필요한 설정 패턴, API, 실용적인 예제를 알아보세요.
에이전트
Astreus 문서에서 에이전트에 대해 알아보고, 에이전트 시스템을 구축하기 위한 설정 안내, API 패턴, 실용적인 예제를 확인하세요. 안정적인 Astreus 에이전트 시스템을 구축하는 데 필요한 설정 패턴, API, 실용적인 예제를 알아보세요.