@robota-sdk/team
Version:
Multi-agent teamwork functionality for Robota SDK - dynamic agent coordination and task delegation
462 lines (457 loc) • 14.5 kB
TypeScript
import * as _robota_sdk_agents from '@robota-sdk/agents';
import { AgentConfig as AgentConfig$1, AgentTemplate as AgentTemplate$1, AIProvider } from '@robota-sdk/agents';
/**
* Team creation options for template-based teams
*
* @description
* Configuration interface for creating teams when using agent templates.
* Since templates define their own AI providers, models, and settings,
* you only need to provide the basic AI providers and optional configuration.
*
* @example
* ```typescript
* const team = createTeam({
* aiProviders: [openaiProvider, anthropicProvider],
* debug: true
* });
* ```
*/
interface TeamOptions {
/**
* AI providers available for templates to use.
* Each template specifies which provider it prefers.
*/
aiProviders: AIProvider[];
/**
* Maximum number of team members that can be created concurrently.
* Default: 5
*/
maxMembers?: number;
/**
* Enable debug mode for detailed logging of team operations.
* Default: false
*/
debug?: boolean;
/**
* Maximum token limit for the entire conversation history.
* Default: 50000
*/
maxTokenLimit?: number;
/**
* Logger for team operations. If not provided, no logging will be done.
*/
logger?: {
info: (message: string) => void;
warn: (message: string) => void;
error: (message: string) => void;
debug: (message: string) => void;
};
/**
* Custom agent templates to register in addition to built-in templates.
* Built-in templates are automatically available.
*/
customTemplates?: AgentTemplate$1[];
/**
* Name of the agent template to use for the team coordinator/leader role.
* This template should be specialized for task analysis, work distribution, and coordination.
* Default: "task_coordinator"
*/
leaderTemplate?: string;
}
/**
* Internal configuration options for TeamContainer (used internally)
* @internal
*/
interface TeamContainerOptions {
baseRobotaOptions: AgentConfig$1;
maxMembers?: number;
debug?: boolean;
customTemplates?: AgentTemplate$1[];
leaderTemplate?: string;
logger?: {
info: (message: string) => void;
warn: (message: string) => void;
error: (message: string) => void;
debug: (message: string) => void;
} | undefined;
}
/**
* Configuration for creating an agent
*/
interface AgentConfig {
/** AI provider to use (e.g., 'openai', 'anthropic', 'google') */
provider: string;
/** Model name to use */
model: string;
/** System prompt for the agent */
systemPrompt?: string;
/** Maximum tokens for responses */
maxTokens?: number;
/** Temperature for response generation */
temperature?: number;
}
/**
* Configuration for creating a task-specific agent
*/
interface TaskAgentConfig {
/** Description of the task the agent will perform */
taskDescription: string;
/** Required tools for the task */
requiredTools: string[];
/** Agent configuration overrides */
agentConfig?: Partial<AgentConfig>;
}
/**
* Task delegation record
*/
interface TaskDelegationRecord {
id: string;
originalTask: string;
delegatedTask: string;
agentTemplate?: string;
agentId: string;
priority: string;
startTime: Date;
endTime?: Date;
duration?: number;
result: string;
success: boolean;
tokensUsed?: number;
executionStats?: {
agentExecutions: number;
agentAverageDuration: number;
agentSuccessRate: number;
};
}
/**
* Team execution analysis
*/
interface TeamExecutionAnalysis {
totalTasks: number;
directlyHandledTasks: number;
delegatedTasks: number;
delegationRate: number;
delegationBreakdown: {
template: string;
count: number;
averageDuration: number;
successRate: number;
}[];
taskComplexityAnalysis: {
simple: number;
complex: number;
};
performanceMetrics: {
averageDirectHandlingTime: number;
averageDelegationTime: number;
totalExecutionTime: number;
};
}
/**
* Built-in agent template interface
*/
interface AgentTemplate {
id: string;
name: string;
description: string;
category: string;
tags: string[];
config: {
model: string;
provider: string;
systemMessage: string;
temperature: number;
maxTokens?: number;
};
}
/**
* TeamContainer - Multi-Agent Team Collaboration System
*
* @description
* The TeamContainer class implements an intelligent multi-agent collaboration system
* where a primary team coordinator can dynamically delegate specialized tasks to
* temporary expert agents. This enables solving complex, multi-faceted problems
* through coordinated teamwork.
*
* @features
* - **Intelligent Task Delegation**: Automatically breaks down complex requests into specialized components
* - **Dynamic Agent Creation**: Creates temporary expert agents tailored for specific tasks
* - **Collaborative Workflows**: Coordinates multiple agents to solve multi-faceted problems
* - **Result Integration**: Synthesizes outputs from multiple agents into cohesive responses
* - **Resource Management**: Automatic cleanup and resource management for temporary agents
* - **Performance Monitoring**: Comprehensive statistics and performance tracking via ExecutionAnalyticsPlugin
*
* @example Basic Usage
* ```typescript
* import { createTeam } from '@robota-sdk/team';
* import { OpenAIProvider } from '@robota-sdk/openai';
*
* const team = createTeam({
* provider: new OpenAIProvider({
* apiKey: process.env.OPENAI_API_KEY,
* model: 'gpt-4'
* }),
* maxTokenLimit: 50000,
* logger: console
* });
*
* const response = await team.execute(`
* Create a comprehensive business plan including:
* 1) Market analysis
* 2) Financial projections
* 3) Marketing strategy
* `);
* ```
*
* @example Advanced Configuration
* ```typescript
* const team = new TeamContainer({
* baseRobotaOptions: {
* aiProviders: { openai: openaiProvider },
* currentProvider: 'openai',
* currentModel: 'gpt-4',
* maxTokenLimit: 50000
* },
* maxMembers: 10,
* debug: true
* });
*
* // The team intelligently delegates work
* const result = await team.execute(
* 'Design a complete mobile app including UI/UX design, backend architecture, and deployment strategy'
* );
*
* // View team performance statistics from ExecutionAnalyticsPlugin
* const analyticsStats = team.getAnalytics();
* console.log(`Success rate: ${(analyticsStats.successRate * 100).toFixed(1)}%`);
* console.log(`Average execution time: ${analyticsStats.averageDuration.toFixed(0)}ms`);
* ```
*
* @see {@link createTeam} - Convenience function for creating teams
* @see {@link AssignTaskParams} - Parameters for task assignment
*/
declare class TeamContainer {
private teamAgent;
private options;
private logger;
private availableTemplates;
private delegationHistory;
private activeAgentsCount;
private totalAgentsCreated;
private tasksCompleted;
private totalExecutionTime;
constructor(options: TeamContainerOptions);
/**
* Execute a task using the team approach
* @param userPrompt - The task to execute
* @returns Promise<string> - The result of the task execution
*/
execute(userPrompt: string): Promise<string>;
/**
* Assign specialized tasks to a temporary expert agent
*
* @description
* This method creates a temporary specialized agent to handle a specific task.
* The agent is configured with appropriate tools and context for the task,
* executes the work, and is automatically cleaned up after completion.
*
* @param params - Task assignment parameters
* @param params.jobDescription - Clear description of the specific job to assign
* @param params.context - Additional context or constraints for the job
* @param params.requiredTools - List of tools the member might need
* @param params.priority - Priority level for the task ('low' | 'medium' | 'high' | 'urgent')
*
* @returns Promise resolving to the task result with metadata
*
* @throws {Error} When maximum number of team members is reached
* @throws {Error} When task execution fails
*/
private assignTask;
/**
* Get team analytics from ExecutionAnalyticsPlugin
*/
getAnalytics(): _robota_sdk_agents.PluginStats | undefined;
/**
* Get execution statistics by operation type
*/
getExecutionStats(operation?: string): _robota_sdk_agents.ExecutionStats[];
/**
* Get detailed plugin status and memory usage
*/
getStatus(): {
name: string;
version: string;
enabled: boolean;
initialized: boolean;
category: _robota_sdk_agents.PluginCategory;
priority: number;
subscribedEventsCount: number;
hasEventEmitter: boolean;
} | undefined;
/**
* Clear analytics data
*/
clearAnalytics(): void;
/**
* Get raw analytics data
*/
getAnalyticsData(): _robota_sdk_agents.PluginData | undefined;
/**
* Get all plugin statuses
*/
getPluginStatuses(): ({
name: string;
version: string;
enabled: boolean;
initialized: boolean;
category: _robota_sdk_agents.PluginCategory;
priority: number;
subscribedEventsCount: number;
hasEventEmitter: boolean;
} | {
name: string;
version: string;
enabled: boolean;
initialized: boolean;
})[];
/**
* Get delegation history
*
* Returns raw delegation records for detailed analysis
*/
getDelegationHistory(): TaskDelegationRecord[];
/**
* Get team execution analysis
*
* Provides comprehensive analysis of how the team handled tasks,
* including delegation patterns and performance metrics
*/
getTeamExecutionAnalysis(): TeamExecutionAnalysis;
/**
* Clear delegation history
*/
clearDelegationHistory(): void;
/**
* Get current team statistics
*/
/**
* Get statistics for team performance (alias for getTeamStats)
*
* @description
* Returns statistics about team performance including task completion,
* agent creation, and execution time. This method is used by examples
* to show team performance metrics.
*
* @returns Object containing team performance statistics
*/
getStats(): {
tasksCompleted: number;
totalAgentsCreated: number;
totalExecutionTime: number;
};
getTeamStats(): {
activeAgentsCount: number;
totalAgentsCreated: number;
maxMembers: string | number;
delegationHistoryLength: number;
successfulTasks: number;
failedTasks: number;
tasksCompleted: number;
totalExecutionTime: number;
};
/**
* Reset team statistics
*/
resetTeamStats(): void;
/**
* Get available templates
*/
getTemplates(): AgentTemplate[];
/**
* Get template by ID
*/
getTemplate(templateId: string): AgentTemplate | undefined;
/**
* Build task prompt for delegation
*/
private buildTaskPrompt;
/**
* Estimate token usage for a prompt and response
*/
private estimateTokenUsage;
/**
* Create AssignTask tool using facade pattern with dynamic schema based on available templates
*/
private createAssignTaskTool;
/**
* Get built-in agent templates
*/
private getBuiltinTemplates;
}
/**
* Create a Multi-Agent Team with Template-Based Configuration
*
* @description
* Creates a TeamContainer instance using a simplified configuration interface.
* Since agent templates define their own AI providers, models, and settings,
* you only need to provide the AI providers and basic configuration.
* The team automatically delegates complex tasks to specialized temporary agents,
* enabling sophisticated problem-solving through coordinated teamwork.
*
* @param options - Simplified configuration options for the team
* @param options.aiProviders - AI providers available for templates to use
* @param options.maxMembers - Maximum number of concurrent team members (optional)
* @param options.debug - Enable debug logging (optional)
* @param options.maxTokenLimit - Maximum token limit for conversations (optional)
* @param options.logger - Logger for team operations (optional)
* @param options.templateManager - Custom template manager (optional)
* @param options.leaderTemplate - Template for team coordinator (optional)
*
* @returns A new TeamContainer instance ready for multi-agent collaboration
*
* @example Simple Team Creation
* ```typescript
* import { createTeam } from '@robota-sdk/team';
* import { OpenAIProvider } from '@robota-sdk/openai';
* import { AnthropicProvider } from '@robota-sdk/anthropic';
*
* const team = createTeam({
* aiProviders: [openaiProvider, anthropicProvider],
* debug: true
* });
*
* // Templates automatically use their preferred providers and settings
* const response = await team.execute(`
* Create a comprehensive business plan with:
* 1) Market analysis
* 2) Financial projections
* 3) Marketing strategy
* `);
* ```
*
* @example Advanced Team Configuration
* ```typescript
* const team = createTeam({
* aiProviders: [openaiProvider, anthropicProvider, googleProvider],
* maxMembers: 10,
* maxTokenLimit: 100000,
* debug: true,
* logger: console,
* leaderTemplate: 'custom_coordinator'
* });
*
* // Team intelligently breaks down complex requests
* const result = await team.execute(
* 'Design a complete e-commerce platform including frontend, backend, database design, and deployment strategy'
* );
*
* // Monitor team performance
* const stats = team.getStats();
* console.log(`Created ${stats.totalAgentsCreated} specialized agents`);
* ```
*
* @see {@link TeamContainer} - The underlying team container class
* @see {@link TeamOptions} - Available configuration options
*/
declare function createTeam(options: TeamOptions): TeamContainer;
export { type AgentConfig, type TaskAgentConfig, TeamContainer, type TeamContainerOptions, type TeamOptions, createTeam };