グラフ
Astreusのドキュメントでグラフについて学び、エージェントシステムを構築するためのセットアップの手引き、APIのパターン、実践的な例を確認しましょう。 信頼性の高いAstreusエージェントシステムを構築するために必要なセットアップのパターン、API、実践的な例を学びましょう。
依存関係管理と並列実行を伴う、ワークフローオーケストレーション
概要
グラフシステムでは、タスクとエージェントを依存関係、条件、並列実行機能で接続することで、複雑なワークフローを作成できます。マルチステップのプロセスをオーケストレーションし、分岐ロジックを処理し、複数のエージェントが連携して動作するように調整するための、視覚的かつプログラム的な方法を提供します。
グラフの作成
グラフは、ノード(タスクまたはエージェント)とエッジ(それらの間の接続)で構成されます。
import { Graph } from '@astreus-ai/astreus';
// Create a workflow graph with agent reference
const agent = await Agent.create({
name: 'ContentAgent',
model: 'gpt-4o'
});
const graph = new Graph({
name: 'content-creation-pipeline',
description: 'Research and write technical content'
}, agent); // Pass agent as second parameter
// Add task nodes
const researchNodeId = graph.addTaskNode({
prompt: 'Research the latest TypeScript features and summarize key findings',
model: 'gpt-4o',
priority: 10,
metadata: { type: 'research' }
});
const writeNodeId = graph.addTaskNode({
prompt: 'Write a comprehensive blog post based on the research findings',
model: 'gpt-4o',
dependencies: [researchNodeId], // Depends on research completion
priority: 5,
metadata: { type: 'writing' }
});
// Execute the graph
const results = await graph.run();
console.log('Success:', results.success);
console.log('Completed nodes:', results.completedNodes);
console.log('Failed nodes:', results.failedNodes);
console.log('Duration:', results.duration, 'ms');
console.log('Results:', results.results);グラフ実行フロー
ノードの解決
グラフはすべてのノードとその依存関係を分析し、実行順序を決定します。
並列実行
独立したノードは、最適なパフォーマンスのために同時に実行されます。
依存関係の待機
依存関係のあるノードは、開始前に前提条件が完了するのを待ちます。
結果の収集
すべてのノードの出力が収集され、最終結果として利用可能になります。
応用例
依存関係、並列実行、エラー処理を伴う複雑なワークフローの例です。
import { Graph } from '@astreus-ai/astreus';
// Create workflow graph with default agent
const agent = await Agent.create({
name: 'OptimizationAgent',
model: 'gpt-4o'
});
const graph = new Graph({
name: 'code-optimization-pipeline',
description: 'Analyze and optimize codebase',
maxConcurrency: 3, // Allow 3 parallel nodes
timeout: 300000, // 5 minute timeout
retryAttempts: 2 // Retry failed nodes twice
}, agent); // Pass agent as second parameter
// Add task nodes with proper configuration
const analysisNodeId = graph.addTaskNode({
prompt: 'Analyze the codebase for performance issues and categorize them by severity',
model: 'gpt-4o',
priority: 10, // High priority
metadata: { step: 'analysis', category: 'review' }
});
const optimizationNodeId = graph.addTaskNode({
prompt: 'Based on the analysis, implement performance optimizations',
model: 'gpt-4o',
dependencies: [analysisNodeId], // Depends on analysis
priority: 8,
metadata: { step: 'optimization', category: 'implementation' }
});
const testNodeId = graph.addTaskNode({
prompt: 'Run performance tests and validate the optimizations',
model: 'gpt-4o',
dependencies: [optimizationNodeId], // Depends on optimization
priority: 6,
stream: true, // Enable streaming for real-time feedback
metadata: { step: 'testing', category: 'validation' }
});
const documentationNodeId = graph.addTaskNode({
prompt: 'Document all changes and performance improvements',
model: 'gpt-4o',
dependencies: [analysisNodeId], // Can run parallel to optimization
priority: 5, // Lower priority
metadata: { step: 'documentation', category: 'docs' }
});
// Add edges (optional, as dependencies already create edges)
graph.addEdge(analysisNodeId, optimizationNodeId);
graph.addEdge(analysisNodeId, documentationNodeId);
graph.addEdge(optimizationNodeId, testNodeId);
// Execute the graph
const results = await graph.run();
console.log('Pipeline results:', results);
console.log('Completed nodes:', results.completedNodes);
console.log('Failed nodes:', results.failedNodes);
console.log('Duration:', results.duration, 'ms');
// Access individual node results
Object.entries(results.results).forEach(([nodeId, result]) => {
console.log(`Node ${nodeId}:`, result);
});
// Check for errors
if (results.errors && Object.keys(results.errors).length > 0) {
console.log('Errors:', results.errors);
}グラフの設定
グラフはさまざまな設定オプションをサポートしています。
interface GraphConfig {
id?: string; // Optional graph ID (UUID)
name: string; // Graph name (required)
description?: string; // Graph description
maxConcurrency?: number; // Max parallel execution (default: 1)
timeout?: number; // Execution timeout in ms
retryAttempts?: number; // Retry attempts for failed nodes
autoLink?: boolean; // Automatically link nodes based on dependencies
maxContextTokens?: number; // Maximum context tokens for the graph
contextWarningThreshold?: number; // Warning threshold for context usage (0-1, e.g., 0.8 = 80%)
subAgentNodeTimeout?: number; // Extended timeout for sub-agent nodes (default: 5 minutes)
metadata?: MetadataObject; // Custom metadata
subAgentAware?: boolean; // Enable sub-agent awareness and optimization
optimizeSubAgentUsage?: boolean; // Optimize sub-agent delegation patterns
subAgentCoordination?: 'parallel' | 'sequential' | 'adaptive'; // Default sub-agent coordination
}
// Note: The default agent is passed as the second parameter to the constructor:
// new Graph(config, agent)
// The graph's defaultAgentId is automatically set from the agent's ID.
// Example with full configuration including sub-agent support
const graph = new Graph({
name: 'advanced-pipeline',
description: 'Complex workflow with error handling and sub-agent coordination',
maxConcurrency: 5,
timeout: 600000, // 10 minutes
retryAttempts: 3,
subAgentAware: true,
optimizeSubAgentUsage: true,
subAgentCoordination: 'adaptive',
metadata: { project: 'automation', version: '1.0' }
}, agent); // Agent passed as second parameterノードの種類とオプション
タスクノード
interface AddTaskNodeOptions {
name?: string; // Node name for easy referencing
prompt: string; // Task prompt (required)
model?: string; // Override model for this task
agentId?: string; // Override default agent (UUID)
stream?: boolean; // Enable streaming for this task
schedule?: string; // Simple schedule string (e.g., 'daily@09:00', 'after:5s')
dependencies?: string[]; // Node IDs this task depends on
dependsOn?: string[]; // Node names this task depends on (easier than IDs)
priority?: number; // Execution priority (higher = earlier)
metadata?: MetadataObject; // Custom metadata
useSubAgents?: boolean; // Force enable/disable sub-agent usage for this task
subAgentDelegation?: 'auto' | 'manual' | 'sequential'; // Sub-agent delegation strategy
subAgentCoordination?: 'parallel' | 'sequential'; // Sub-agent coordination pattern
}エージェントノード
interface AddAgentNodeOptions {
agentId: string; // Agent ID (required, UUID)
dependencies?: string[]; // Node IDs this agent depends on
priority?: number; // Execution priority
metadata?: MetadataObject; // Custom metadata
}サブエージェントの設定オプション
サブエージェントをサポートするグラフを設定する際、委任と連携を包括的に制御できます。
グラフレベルのサブエージェント設定
- subAgentAware: グラフ全体でサブエージェントを活用できる機会の自動検出と最適化を有効にします
- optimizeSubAgentUsage: リアルタイムのパフォーマンス監視と、より高い効率のための自動戦略調整を有効にします
- subAgentCoordination: デフォルトの連携パターンを設定します:
'parallel': 異なるノード間でサブエージェントが同時に動作'sequential': サブエージェントが依存関係の順序で動作し、実行間でコンテキストを引き継ぐ'adaptive': タスクの複雑さと依存関係に基づいて最適な連携パターンを動的に選択
ノードレベルのサブエージェント設定
各タスクノードは、特定のサブエージェントの挙動でグラフレベルの設定を上書きできます。
- useSubAgents: 特定のノードに対してサブエージェント委任を強制的に有効/無効にする
- subAgentDelegation: ノードレベルでタスクがサブエージェントにどのように分配されるかを制御する
- subAgentCoordination: 特定のノードに対して、グラフのデフォルト連携パターンを上書きする
サブエージェントを使った拡張グラフワークフロー
import { Graph, Agent } from '@astreus-ai/astreus';
// Create specialized sub-agents
const researcher = await Agent.create({
name: 'DataResearcher',
systemPrompt: 'You specialize in gathering and analyzing data from multiple sources.'
});
const analyst = await Agent.create({
name: 'TechnicalAnalyst',
systemPrompt: 'You provide technical insights and recommendations.'
});
const writer = await Agent.create({
name: 'TechnicalWriter',
systemPrompt: 'You create clear, comprehensive technical documentation.'
});
// Main coordinator with sub-agents
const coordinator = await Agent.create({
name: 'ProjectCoordinator',
systemPrompt: 'You orchestrate complex projects using specialized team members.',
subAgents: [researcher, analyst, writer]
});
// Create sub-agent optimized graph
// Note: defaultAgentId is automatically set from the coordinator agent passed as second parameter
const projectGraph = new Graph({
name: 'Technical Documentation Pipeline',
description: 'Automated technical documentation creation with specialized agents',
maxConcurrency: 3,
subAgentAware: true,
optimizeSubAgentUsage: true,
subAgentCoordination: 'adaptive'
}, coordinator); // The coordinator's ID becomes the graph's defaultAgentId
// Research phase with automatic sub-agent delegation
const researchNode = projectGraph.addTaskNode({
name: 'Market Research',
prompt: 'Research current trends in cloud computing and serverless architecture',
useSubAgents: true,
subAgentDelegation: 'auto',
priority: 10,
metadata: { phase: 'research', category: 'data-gathering' }
});
// Analysis phase with sequential sub-agent coordination
const analysisNode = projectGraph.addTaskNode({
name: 'Technical Analysis',
prompt: 'Analyze research findings and identify key technical patterns',
dependencies: [researchNode],
useSubAgents: true,
subAgentDelegation: 'auto',
subAgentCoordination: 'sequential',
priority: 8,
metadata: { phase: 'analysis', category: 'insights' }
});
// Documentation phase with parallel sub-agent work
const docNode = projectGraph.addTaskNode({
name: 'Documentation Creation',
prompt: 'Create comprehensive technical documentation and executive summary',
dependencies: [analysisNode],
useSubAgents: true,
subAgentDelegation: 'manual',
subAgentCoordination: 'parallel',
priority: 6,
metadata: { phase: 'documentation', category: 'deliverables' }
});
// Execute the graph
const result = await projectGraph.run();
console.log('Pipeline completed:', result.success);
console.log('Node results:', result.results);レスポンスの型
グラフの実行は、ノードの結果、使用状況の統計、パフォーマンスメトリクスを含む包括的な結果を返します。
グラフ実行結果
graph.run()メソッドは、詳細なGraphExecutionResultを返します。
const result = await graph.run({ timeout: 60000 });
// Response structure:
{
graph: {
id: "graph-uuid-123",
defaultAgentId: "agent-uuid", // Set from the agent passed to constructor
config: {
name: "code-optimization-pipeline",
description: "Analyze and optimize codebase",
maxConcurrency: 3,
timeout: 300000,
retryAttempts: 2
},
nodes: [ /* GraphNode[] */ ],
edges: [ /* GraphEdge[] */ ],
status: "completed", // 'idle' | 'running' | 'completed' | 'failed' | 'paused'
startedAt: Date('2024-01-15T10:00:00Z'),
completedAt: Date('2024-01-15T10:12:30Z'),
executionLog: [ /* GraphExecutionLogEntry[] */ ],
usage: { /* GraphUsage */ },
createdAt: Date('2024-01-15T09:55:00Z'),
updatedAt: Date('2024-01-15T10:12:30Z')
},
success: true, // Overall success status
completedNodes: 5, // Number of successfully completed nodes
failedNodes: 0, // Number of failed nodes
duration: 12500, // Total execution time in milliseconds
results: {
"node_abc12345-...": "Analysis complete: Found 15 performance issues categorized by severity...",
"node_def67890-...": "Optimization implemented: 40% performance improvement...",
"node_ghi11111-...": "Tests passed: All optimizations validated...",
"node_jkl22222-...": "Documentation updated with all changes...",
"node_mno33333-...": "Final review completed..."
},
errors: {}, // Empty if all nodes succeeded
usage: {
totalPromptTokens: 1500,
totalCompletionTokens: 3000,
totalTokens: 4500,
totalContextTokens: 500,
totalCost: 0.045,
nodeUsages: {
"node_abc12345-...": {
promptTokens: 200,
completionTokens: 400,
totalTokens: 600,
contextTokens: 100,
model: "gpt-4",
cost: 0.012
},
"node_def67890-...": {
promptTokens: 300,
completionTokens: 600,
totalTokens: 900,
contextTokens: 150,
model: "gpt-4",
cost: 0.018
}
// ... more node usages
},
modelsUsed: ["gpt-4", "gpt-3.5-turbo"]
}
}エラーを伴うグラフ実行
ノードが失敗した場合、レスポンスにエラーが含まれます。
const result = await graph.run();
// Response with failures:
{
graph: { /* ... */ },
success: false,
completedNodes: 3,
failedNodes: 2,
duration: 8500,
results: {
"node_abc12345-...": "Successfully completed...",
"node_def67890-...": "Partial completion...",
"node_ghi11111-...": "Task completed..."
},
errors: {
"node_jkl22222-...": "Error: Timeout exceeded after 5000ms",
"node_mno33333-...": "Error: Dependency node_jkl22222-... failed, skipping execution"
},
usage: { /* ... */ }
}ノード追加のレスポンス
ノードを追加すると、ノードID(形式: node_<uuid>)が返されます。
const nodeId = graph.addTaskNode({
name: "Analyze Data",
prompt: "Analyze the following data...",
model: "gpt-4",
priority: 10
});
// Response: "node_a1b2c3d4-e5f6-7890-abcd-ef1234567890" (node ID string)ノード使用状況の詳細
各ノードの使用状況は個別に追跡されます。
// Access individual node usage from result
const nodeUsage = result.usage.nodeUsages["node_abc12345-..."];
// Structure:
{
promptTokens: 200,
completionTokens: 400,
totalTokens: 600,
contextTokens: 100, // Optional: tokens from context/memory
model: "gpt-4",
cost: 0.012 // Optional: calculated cost
}グラフ使用状況のサマリー
すべてのノードにわたる合計使用状況です。
const totalUsage = result.usage;
// Structure:
{
totalPromptTokens: 1500, // Sum of all prompt tokens
totalCompletionTokens: 3000, // Sum of all completion tokens
totalTokens: 4500, // Total tokens used
totalContextTokens: 500, // Total context tokens loaded
totalCost: 0.045, // Total estimated cost
nodeUsages: { /* ... */ }, // Per-node breakdown
modelsUsed: ["gpt-4", "gpt-3.5-turbo"] // All models used in execution
}最終更新日: 2026年7月6日
このセクション内
はじめに
実世界のタスクを効果的に解決する自律システムを構築するための、オープンソースAIエージェントフレームワーク。 信頼性の高いAstreusエージェントシステムを構築するために必要なセットアップのパターン、API、実践的な例を学びましょう。
インストール
npm、yarn、pnpmでAstreusをインストールし、必要なNode.jsのバージョンを確認して、フレームワークでAIエージェントを構築するためのローカルプロジェクトを準備します。
クイックスタート
Astreusのドキュメントでクイックスタートについて学び、エージェントシステムを構築するためのセットアップの手引き、APIのパターン、実践的な例を確認しましょう。 信頼性の高いAstreusエージェントシステムを構築するために必要なセットアップのパターン、API、実践的な例を学びましょう。
エージェント
Astreusのドキュメントでエージェントについて学び、エージェントシステムを構築するためのセットアップの手引き、APIのパターン、実践的な例を確認しましょう。 信頼性の高いAstreusエージェントシステムを構築するために必要なセットアップのパターン、API、実践的な例を学びましょう。