UNPKG

@robota-sdk/team

Version:

Multi-agent teamwork functionality for Robota SDK - dynamic agent coordination and task delegation

783 lines (766 loc) 38.4 kB
import { ExecutionAnalyticsPlugin, Robota, createZodFunctionTool } from '@robota-sdk/agents'; import { v4 } from 'uuid'; import { z } from 'zod'; // src/team-container.ts var assignTaskSchema = z.object({ jobDescription: z.string().describe( "Clear, specific description of the job to be completed. Should provide enough detail for the specialist agent to understand the scope and deliverables expected." ), context: z.string().optional().describe( "Additional context, constraints, or requirements for the job. Helps the specialist agent understand the broader context and any specific limitations or guidelines to follow." ), requiredTools: z.array(z.string()).optional().describe( "List of tools the specialist agent might need for this task. If specified, the system will attempt to configure the agent with access to these tools." ), priority: z.enum(["low", "medium", "high", "urgent"]).default("medium").describe( "Priority level for the task, affecting resource allocation and urgency. Higher priority tasks may receive more resources or faster processing." ), agentTemplate: z.string().optional().describe( "Name of the agent template to use for this task. If not specified, a dynamic agent will be created based on the job description." ), allowFurtherDelegation: z.boolean().default(false).describe( "Whether the assigned agent can delegate parts of the task to other specialists if needed. Set true ONLY for very complex tasks requiring multiple specialized areas of expertise, false for focused execution." ) }); function createDynamicAssignTaskSchema(availableTemplates) { const templateDescriptions = availableTemplates.map( (template) => `${template.id}: ${template.description}` ).join(", "); return assignTaskSchema.extend({ agentTemplate: z.string().optional().describe( `Name of the agent template to use for this task. Available templates: ${templateDescriptions}. If not specified, a dynamic agent will be created based on the job description.` ) }); } // src/task-assignment/tool-factory.ts function createAssignTaskTool(availableTemplates, executor) { const toolParametersSchema = createDynamicAssignTaskSchema(availableTemplates); const toolInstance = createZodFunctionTool( "assignTask", createToolDescription(availableTemplates), toolParametersSchema, async (parameters) => { const validatedParams = toolParametersSchema.parse(parameters); const result = await executor(convertToAssignTaskParams(validatedParams)); return formatResultForLLM(result); } ); return toolInstance; } function convertToAssignTaskParams(validated) { const params = { jobDescription: validated.jobDescription }; if (validated.context !== void 0) { params.context = validated.context; } if (validated.requiredTools !== void 0) { params.requiredTools = validated.requiredTools; } if (validated.priority !== void 0) { params.priority = validated.priority; } if (validated.agentTemplate !== void 0) { params.agentTemplate = validated.agentTemplate; } if (validated.allowFurtherDelegation !== void 0) { params.allowFurtherDelegation = validated.allowFurtherDelegation; } return params; } function createToolDescription(availableTemplates) { const baseDescription = `Assign a specialized task to a temporary expert agent. Use this when the task requires specific expertise, complex analysis, or when breaking down work into specialized components would be beneficial. The expert agent will be created, complete the task, and be automatically cleaned up.`; const delegationGuidance = `Set allowFurtherDelegation=true ONLY for extremely complex tasks requiring multiple different areas of expertise, otherwise keep false for direct execution.`; const templateGuidance = availableTemplates.length > 0 ? `Choose appropriate agentTemplate based on the nature of the work. Available templates: ${availableTemplates.map((t) => t.id).join(", ")}.` : `A dynamic agent will be created based on the job description.`; return `${baseDescription} ${delegationGuidance} ${templateGuidance}`; } function formatResultForLLM(result) { const baseResult = `Task completed successfully by ${result.agentId}. Result: ${result.result}`; const metadata = ` Execution time: ${result.metadata.executionTime}ms`; const additionalInfo = []; if (result.metadata.tokensUsed) { additionalInfo.push(`Tokens used: ${result.metadata.tokensUsed}`); } if (result.metadata.agentExecutions) { additionalInfo.push(`Agent executions: ${result.metadata.agentExecutions}`); } if (result.metadata.agentSuccessRate !== void 0) { additionalInfo.push(`Success rate: ${(result.metadata.agentSuccessRate * 100).toFixed(1)}%`); } const additionalInfoStr = additionalInfo.length > 0 ? ` ${additionalInfo.join(", ")}` : ""; return `${baseResult}${metadata}${additionalInfoStr}`; } function validateTaskParams(parameters, availableTemplates) { const schema = createDynamicAssignTaskSchema(availableTemplates); const validated = schema.parse(parameters); return convertToAssignTaskParams(validated); } // src/task-assignment/index.ts function createTaskAssignmentFacade(availableTemplates, executor) { const tool = createAssignTaskTool(availableTemplates, executor); const validateParams = (parameters) => validateTaskParams(parameters, availableTemplates); const safeValidateParams = (parameters) => { const schema = createDynamicAssignTaskSchema(availableTemplates); const result = schema.safeParse(parameters); return { success: result.success, data: result.success ? result.data : void 0, error: result.success ? void 0 : result.error.message }; }; return { tool, validateParams, safeValidateParams, availableTemplates: [...availableTemplates] // Immutable copy }; } // src/team-container.ts var TeamContainer = class { teamAgent; options; logger; availableTemplates; delegationHistory = []; activeAgentsCount = 0; // Track currently active agents totalAgentsCreated = 0; // Track total agents created tasksCompleted = 0; // Track completed tasks totalExecutionTime = 0; // Track total execution time in ms constructor(options) { this.options = options; this.logger = options.logger; this.availableTemplates = this.getBuiltinTemplates(); const teamAnalyticsPlugin = new ExecutionAnalyticsPlugin({ maxEntries: 1e3, trackErrors: true, performanceThreshold: 5e3, // 5 seconds enableWarnings: true }); const assignTaskTool = this.createAssignTaskTool(); const leaderTemplateName = this.options.leaderTemplate || "task_coordinator"; const leaderTemplate = this.getTemplate(leaderTemplateName); if (!leaderTemplate) { throw new Error(`Leader template '${leaderTemplateName}' not found. Available templates: ${this.availableTemplates.map((t) => t.id).join(", ")}`); } const availableProviders = this.options.baseRobotaOptions.aiProviders.map((p) => p.name); if (!availableProviders.includes(leaderTemplate.config.provider)) { throw new Error(`Leader template requires provider '${leaderTemplate.config.provider}' but it's not available. Available providers: ${availableProviders.join(", ")}`); } const teamConfig = { name: "team-leader", aiProviders: this.options.baseRobotaOptions.aiProviders, defaultModel: { provider: leaderTemplate.config.provider, model: leaderTemplate.config.model, temperature: leaderTemplate.config.temperature, systemMessage: leaderTemplate.config.systemMessage, ...leaderTemplate.config.maxTokens && { maxTokens: leaderTemplate.config.maxTokens } }, plugins: [ ...this.options.baseRobotaOptions.plugins || [], teamAnalyticsPlugin ], tools: [ ...this.options.baseRobotaOptions.tools || [], assignTaskTool ] }; this.teamAgent = new Robota(teamConfig); this.logger?.info(`Team created with leader template: ${leaderTemplateName} (${leaderTemplate.config.provider}/${leaderTemplate.config.model})`); } /** * Execute a task using the team approach * @param userPrompt - The task to execute * @returns Promise<string> - The result of the task execution */ async execute(userPrompt) { const startTime = Date.now(); try { this.logger?.info(`\u{1F680} Starting team execution`); const result = await this.teamAgent.run(userPrompt); const executionTime = Date.now() - startTime; this.tasksCompleted++; this.totalExecutionTime += executionTime; this.logger?.info(`\u2705 Team execution completed in ${executionTime}ms`); return result; } catch (error) { const executionTime = Date.now() - startTime; this.totalExecutionTime += executionTime; const errorMessage = error instanceof Error ? error.message : String(error); this.logger?.error(`\u274C Team execution failed after ${executionTime}ms: ${errorMessage}`); throw error; } } /** * 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 */ async assignTask(params) { let temporaryAgent = null; let counterIncremented = false; const agentId = `agent-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`; const startTime = Date.now(); console.log("assignTask params:", JSON.stringify(params, null, 2)); try { if (this.options.maxMembers && this.totalAgentsCreated >= this.options.maxMembers) { const errorMessage = `Maximum number of team members (${this.options.maxMembers}) reached. Total created: ${this.totalAgentsCreated}, Currently active: ${this.activeAgentsCount}`; this.logger?.warn(errorMessage); return { result: `Task assignment failed: ${errorMessage}`, agentId, metadata: { executionTime: 0, errors: [errorMessage] } }; } this.activeAgentsCount++; this.totalAgentsCreated++; counterIncremented = true; this.logger?.info(`\u{1F4CA} Agent slot reserved - Active: ${this.activeAgentsCount}, Total: ${this.totalAgentsCreated}, Max: ${this.options.maxMembers || "unlimited"}`); const taskAnalyticsPlugin = new ExecutionAnalyticsPlugin({ maxEntries: 100, trackErrors: true, performanceThreshold: 1e4, // 10 seconds for specialized tasks enableWarnings: true }); const shouldAllowDelegation = params.allowFurtherDelegation === true; const delegationTools = shouldAllowDelegation ? [this.createAssignTaskTool()] : []; if (params.agentTemplate) { const template = this.getTemplate(params.agentTemplate); if (!template) { throw new Error(`Template '${params.agentTemplate}' not found. Available templates: ${this.availableTemplates.map((t) => t.id).join(", ")}`); } const availableProviders = this.options.baseRobotaOptions.aiProviders.map((p) => p.name); if (!availableProviders.includes(template.config.provider)) { throw new Error(`Template requires provider '${template.config.provider}' but it's not available. Available providers: ${availableProviders.join(", ")}`); } let systemMessage = template.config.systemMessage; if (shouldAllowDelegation) { systemMessage += "\n\nDELEGATION GUIDANCE: You can use assignTask to delegate parts of this work to other specialists if the task would benefit from specialized expertise outside your primary domain. Focus on your expertise but delegate when it would significantly improve quality."; } else { systemMessage += "\n\nDIRECT EXECUTION: Handle this task directly using your specialized knowledge and skills. Do not delegate - focus on completing the work within your expertise."; } temporaryAgent = new Robota({ name: `temp-agent-${agentId}`, aiProviders: this.options.baseRobotaOptions.aiProviders, defaultModel: { provider: template.config.provider, model: template.config.model, temperature: template.config.temperature, systemMessage, ...template.config.maxTokens && { maxTokens: template.config.maxTokens } }, plugins: [taskAnalyticsPlugin], // Add analytics to temporary agent tools: [...delegationTools, ...this.options.baseRobotaOptions.tools || []] }); } else { let systemMessage = `You are a specialist agent created to handle this specific task: ${params.jobDescription}. ${params.context || ""}`; if (shouldAllowDelegation) { systemMessage += "\n\nDELEGATION GUIDANCE: You can use assignTask to delegate parts of this work to other specialists if the task would benefit from specialized expertise outside your capabilities."; } else { systemMessage += "\n\nDIRECT EXECUTION: Handle this task directly using your knowledge and skills. Do not delegate - focus on completing the work yourself."; } temporaryAgent = new Robota({ name: `temp-agent-${agentId}`, aiProviders: this.options.baseRobotaOptions.aiProviders, defaultModel: { provider: this.options.baseRobotaOptions.aiProviders[0]?.name || "openai", model: "gpt-4o-mini", systemMessage }, plugins: [taskAnalyticsPlugin], // Add analytics to temporary agent tools: [...delegationTools, ...this.options.baseRobotaOptions.tools || []] }); } this.logger?.info(`\u{1F4CA} Agent created - Active: ${this.activeAgentsCount}, Total: ${this.totalAgentsCreated}`); const taskPrompt = this.buildTaskPrompt(params); const result = await temporaryAgent.run(taskPrompt); const agentAnalyticsPlugin = temporaryAgent.getPlugin("ExecutionAnalyticsPlugin"); const executionStats = agentAnalyticsPlugin?.getAggregatedStats(); const taskDuration = Date.now() - startTime; this.logger?.info(`\u2705 Task completed by agent ${agentId} (${taskDuration}ms)`); const delegationRecord = { id: v4(), originalTask: params.jobDescription, delegatedTask: taskPrompt, ...params.agentTemplate && { agentTemplate: params.agentTemplate }, agentId, priority: params.priority || "medium", startTime: new Date(startTime), endTime: new Date(Date.now()), duration: taskDuration, result, success: true, tokensUsed: this.estimateTokenUsage(taskPrompt, result), executionStats: { agentExecutions: executionStats && "totalExecutions" in executionStats ? Number(executionStats.totalExecutions) : 0, agentAverageDuration: executionStats && "averageDuration" in executionStats ? Number(executionStats.averageDuration) : 0, agentSuccessRate: executionStats && "successRate" in executionStats ? Number(executionStats.successRate) : 0 } }; this.delegationHistory.push(delegationRecord); return { result, agentId, metadata: { executionTime: taskDuration, tokensUsed: this.estimateTokenUsage(taskPrompt, result), agentExecutions: executionStats && "totalExecutions" in executionStats ? Number(executionStats.totalExecutions) : 0, agentAverageDuration: executionStats && "averageDuration" in executionStats ? Number(executionStats.averageDuration) : 0, agentSuccessRate: executionStats && "successRate" in executionStats ? Number(executionStats.successRate) : 0, errors: [] } }; } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error); const taskDuration = Date.now() - startTime; if (counterIncremented && this.activeAgentsCount > 0) { this.activeAgentsCount--; counterIncremented = false; this.logger?.info(`\u{1F4CA} Agent failed, slot released - Active: ${this.activeAgentsCount}`); } this.logger?.error(`\u274C Task failed for agent ${agentId} (${taskDuration}ms): ${errorMessage}`); const delegationRecord = { id: v4(), originalTask: params.jobDescription, delegatedTask: params.jobDescription, ...params.agentTemplate && { agentTemplate: params.agentTemplate }, agentId, priority: params.priority || "medium", startTime: new Date(startTime), endTime: new Date(Date.now()), duration: taskDuration, result: `Task failed: ${errorMessage}`, success: false, tokensUsed: this.estimateTokenUsage(params.jobDescription, `Task failed: ${errorMessage}`), executionStats: { agentExecutions: 0, agentAverageDuration: 0, agentSuccessRate: 0 } }; this.delegationHistory.push(delegationRecord); return { result: `Task failed: ${errorMessage}`, agentId, metadata: { executionTime: taskDuration, errors: [errorMessage] } }; } finally { if (counterIncremented && temporaryAgent && this.activeAgentsCount > 0) { this.activeAgentsCount--; this.logger?.info(`\u{1F4CA} Agent completed successfully - Active agents now: ${this.activeAgentsCount}`); } temporaryAgent = null; } } /** * Get team analytics from ExecutionAnalyticsPlugin */ getAnalytics() { const analyticsPlugin = this.teamAgent.getPlugin("ExecutionAnalyticsPlugin"); if (analyticsPlugin && "getStats" in analyticsPlugin && typeof analyticsPlugin.getStats === "function") { return analyticsPlugin.getStats(); } return void 0; } /** * Get execution statistics by operation type */ getExecutionStats(operation) { const analyticsPlugin = this.teamAgent.getPlugin("ExecutionAnalyticsPlugin"); if (analyticsPlugin && typeof analyticsPlugin.getExecutionStats === "function") { return analyticsPlugin.getExecutionStats(operation); } return []; } /** * Get detailed plugin status and memory usage */ getStatus() { const analyticsPlugin = this.teamAgent.getPlugin("ExecutionAnalyticsPlugin"); if (analyticsPlugin && "getStatus" in analyticsPlugin && typeof analyticsPlugin.getStatus === "function") { return analyticsPlugin.getStatus(); } return void 0; } /** * Clear analytics data */ clearAnalytics() { const analyticsPlugin = this.teamAgent.getPlugin("ExecutionAnalyticsPlugin"); if (analyticsPlugin && "clearData" in analyticsPlugin && typeof analyticsPlugin.clearData === "function") { analyticsPlugin.clearData(); } } /** * Get raw analytics data */ getAnalyticsData() { const analyticsPlugin = this.teamAgent.getPlugin("ExecutionAnalyticsPlugin"); if (analyticsPlugin && "getData" in analyticsPlugin && typeof analyticsPlugin.getData === "function") { return analyticsPlugin.getData(); } return void 0; } /** * Get all plugin statuses */ getPluginStatuses() { const plugins = this.teamAgent.getPlugins(); return plugins.map((plugin) => { if ("getStatus" in plugin && typeof plugin.getStatus === "function") { return plugin.getStatus(); } return { name: plugin.name, version: plugin.version, enabled: plugin.isEnabled(), initialized: true }; }); } /** * Get delegation history * * Returns raw delegation records for detailed analysis */ getDelegationHistory() { return [...this.delegationHistory]; } /** * Get team execution analysis * * Provides comprehensive analysis of how the team handled tasks, * including delegation patterns and performance metrics */ getTeamExecutionAnalysis() { const analytics = this.getAnalytics(); const totalExecutions = analytics && "totalExecutions" in analytics ? Number(analytics["totalExecutions"]) : 0; const delegatedTasks = this.delegationHistory.length; const directlyHandledTasks = Math.max(0, totalExecutions - delegatedTasks); const templateStats = /* @__PURE__ */ new Map(); this.delegationHistory.forEach((record) => { const template = record.agentTemplate || "dynamic"; const stats = templateStats.get(template) || { count: 0, totalDuration: 0, successes: 0 }; stats.count++; stats.totalDuration += record.duration || 0; if (record.success) stats.successes++; templateStats.set(template, stats); }); const delegationBreakdown = Array.from(templateStats.entries()).map(([template, stats]) => ({ template, count: stats.count, averageDuration: stats.count > 0 ? stats.totalDuration / stats.count : 0, successRate: stats.count > 0 ? stats.successes / stats.count : 0 })); const delegationTimes = this.delegationHistory.map((r) => r.duration || 0); const averageDelegationTime = delegationTimes.length > 0 ? delegationTimes.reduce((a, b) => a + b, 0) / delegationTimes.length : 0; const averageDirectHandlingTime = analytics && "averageDuration" in analytics ? Number(analytics["averageDuration"]) : 0; const totalExecutionTime = delegationTimes.reduce((a, b) => a + b, 0); return { totalTasks: totalExecutions, directlyHandledTasks, delegatedTasks, delegationRate: totalExecutions > 0 ? delegatedTasks / totalExecutions : 0, delegationBreakdown, taskComplexityAnalysis: { simple: directlyHandledTasks, complex: delegatedTasks }, performanceMetrics: { averageDirectHandlingTime, averageDelegationTime, totalExecutionTime } }; } /** * Clear delegation history */ clearDelegationHistory() { this.delegationHistory = []; this.logger?.debug("Delegation history cleared"); } /** * 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() { return { tasksCompleted: this.tasksCompleted, totalAgentsCreated: this.totalAgentsCreated, totalExecutionTime: this.totalExecutionTime }; } getTeamStats() { return { activeAgentsCount: this.activeAgentsCount, totalAgentsCreated: this.totalAgentsCreated, maxMembers: this.options.maxMembers || "unlimited", delegationHistoryLength: this.delegationHistory.length, successfulTasks: this.delegationHistory.filter((d) => d.success).length, failedTasks: this.delegationHistory.filter((d) => !d.success).length, tasksCompleted: this.tasksCompleted, totalExecutionTime: this.totalExecutionTime }; } /** * Reset team statistics */ resetTeamStats() { this.activeAgentsCount = 0; this.totalAgentsCreated = 0; this.tasksCompleted = 0; this.totalExecutionTime = 0; this.delegationHistory = []; } /** * Get available templates */ getTemplates() { return [...this.availableTemplates]; } /** * Get template by ID */ getTemplate(templateId) { return this.availableTemplates.find((template) => template.id === templateId); } /** * Build task prompt for delegation */ buildTaskPrompt(params) { let prompt = `Task: ${params.jobDescription} `; if (params.context) { prompt += `Context: ${params.context} `; } if (params.requiredTools && params.requiredTools.length > 0) { prompt += `Available tools: ${params.requiredTools.join(", ")} `; } prompt += `Priority: ${params.priority || "medium"} Please complete this task thoroughly and provide a comprehensive response.`; return prompt; } /** * Estimate token usage for a prompt and response */ estimateTokenUsage(prompt, response) { return Math.ceil((prompt.length + response.length) / 4); } /** * Create AssignTask tool using facade pattern with dynamic schema based on available templates */ createAssignTaskTool() { const templateInfo = this.availableTemplates.map((template) => ({ id: template.id, description: template.description })); const taskAssignment = createTaskAssignmentFacade( templateInfo, async (params) => { return await this.assignTask(params); } ); console.log("assignTask schema:", JSON.stringify(taskAssignment.tool.schema, null, 2)); return taskAssignment.tool; } /** * Get built-in agent templates */ getBuiltinTemplates() { const defaultModel = this.options.baseRobotaOptions.defaultModel.model || "gpt-4o-mini"; const defaultProvider = this.options.baseRobotaOptions.defaultModel.provider || "openai"; return [ { id: "general", name: "General Purpose Agent", description: "Basic general-purpose agent with no specific specialization. Use only when no other specialized template fits the task requirements or when task scope is too broad and unclear for specialist agents. This is the fallback option when specialized expertise is not needed.", category: "general", tags: ["general", "default", "versatile", "specialist"], config: { model: defaultModel, provider: defaultProvider, systemMessage: "You are a helpful and capable AI assistant with broad knowledge and skills. You can adapt to various tasks and requirements while maintaining high quality and accuracy. Your strengths include:\n\n\u2022 General problem-solving and analysis\n\u2022 Clear communication and explanation\n\u2022 Flexible task adaptation\n\u2022 Balanced approach to different types of work\n\u2022 Reliable execution of varied requests\n\nWhen handling tasks:\n1. Analyze the request to understand requirements\n2. Apply appropriate methods and knowledge\n3. Provide clear, useful, and accurate responses\n4. Ask for clarification when needed\n5. Adapt your approach to the specific context\n6. Ensure completeness and quality in your work\n\nProvide helpful, accurate, and well-structured responses that meet the user's needs effectively.", temperature: 0.5 } }, { id: "summarizer", name: "Content Summarizer", description: "Analysis specialist expert in document summarization, data extraction, and distilling complex information. Use for: summarizing documents, extracting key insights, creating executive summaries, condensing reports, highlighting main points, creating meeting notes, and comprehensive content analysis.", category: "analysis", tags: ["analysis", "summarization", "extraction", "specialist"], config: { model: defaultModel, provider: defaultProvider, systemMessage: "You are an expert summarization specialist with advanced capabilities in analyzing and distilling complex information. Your expertise includes:\n\n\u2022 Extracting key points and main ideas from lengthy documents\n\u2022 Creating concise summaries while preserving essential information\n\u2022 Identifying critical insights and actionable items\n\u2022 Structuring information in clear, digestible formats\n\u2022 Adapting summary length and style to audience needs\n\nWhen summarizing, focus on:\n1. Main themes and central arguments\n2. Supporting evidence and key data points\n3. Conclusions and recommendations\n4. Action items and next steps\n5. Critical dependencies and risks\n\nDELEGATION GUIDELINES:\n- Handle summarization and analysis tasks directly within your expertise\n- Consider delegating if the task requires specialized domain research, creative ideation, or ethical review beyond summarization\n- Only delegate when it would significantly improve quality or when the task clearly falls outside summarization expertise\n- For pure summarization requests, always handle directly\n\nProvide summaries that are accurate, comprehensive, and immediately useful for decision-making.", temperature: 0.3 } }, { id: "ethical_reviewer", name: "Ethical Reviewer", description: "Ethics and compliance specialist expert in comprehensive review processes. Use for: ethical evaluation, compliance checking, bias detection, privacy assessment, content moderation, legal review, risk analysis, safety evaluation, and responsible AI practices.", category: "analysis", tags: ["ethics", "review", "compliance", "specialist"], config: { model: defaultModel, provider: defaultProvider, systemMessage: "You are an ethical review specialist focused on responsible AI practices and content compliance. Your expertise covers:\n\n\u2022 AI ethics and responsible technology development\n\u2022 Privacy protection and data governance\n\u2022 Bias detection and fairness assessment\n\u2022 Legal compliance and regulatory requirements\n\u2022 Content moderation and safety guidelines\n\u2022 Transparency and accountability standards\n\nWhen reviewing content or proposals, evaluate:\n1. Potential ethical implications and risks\n2. Privacy and data protection concerns\n3. Bias, fairness, and inclusivity issues\n4. Legal and regulatory compliance\n5. Transparency and explainability requirements\n6. Potential unintended consequences\n\nProvide balanced assessments with specific recommendations for addressing identified concerns while supporting innovation and progress.", temperature: 0.2 } }, { id: "creative_ideator", name: "Creative Ideator", description: "Creativity and innovation specialist expert in brainstorming and imaginative problem solving. Use for: brainstorming sessions, innovative product concepts, creative problem solving, design thinking, artistic projects, marketing campaigns, breakthrough ideas, imaginative solutions, and out-of-the-box thinking.", category: "creative", tags: ["creativity", "brainstorming", "innovation", "specialist"], config: { model: defaultModel, provider: defaultProvider, systemMessage: 'You are a creative ideation expert specializing in innovative thinking and breakthrough idea generation. Your strengths include:\n\n\u2022 Divergent thinking and brainstorming techniques\n\u2022 Cross-industry innovation and pattern recognition\n\u2022 Creative problem-solving methodologies\n\u2022 Design thinking and user-centered innovation\n\u2022 Future-oriented scenario planning\n\u2022 Connecting disparate concepts and ideas\n\nWhen generating ideas, apply:\n1. Multiple perspective-taking and reframing\n2. "What if" scenarios and possibility thinking\n3. Combination and recombination of existing concepts\n4. Challenge assumptions and conventional wisdom\n5. Explore edge cases and unconventional approaches\n6. Consider both incremental and radical innovations\n\nDeliver creative solutions that are imaginative yet practical, pushing boundaries while remaining grounded in feasibility.', temperature: 0.8 } }, { id: "fast_executor", name: "Fast Executor", description: "Speed and accuracy specialist expert in rapid task execution. Use for: quick tasks, urgent requests, simple implementations, straightforward analysis, routine operations, time-sensitive work, efficient problem solving, rapid prototyping, and immediate action items requiring fast, accurate execution.", category: "execution", tags: ["execution", "speed", "accuracy", "specialist"], config: { model: defaultModel, provider: defaultProvider, systemMessage: "You are a fast and accurate task executor focused on efficiency and precision. Your core competencies include:\n\n\u2022 Rapid task analysis and prioritization\n\u2022 Efficient workflow optimization\n\u2022 Quick decision-making with available information\n\u2022 Streamlined communication and reporting\n\u2022 Resource optimization and time management\n\u2022 Quality control under time constraints\n\nWhen executing tasks, prioritize:\n1. Speed without compromising accuracy\n2. Clear, concise deliverables\n3. Essential information over comprehensive detail\n4. Actionable outputs and next steps\n5. Efficient use of available resources\n6. Quick validation and error checking\n\nDeliver results that meet requirements efficiently, focusing on what matters most for immediate progress and decision-making.", temperature: 0.1, maxTokens: 1e3 } }, { id: "domain_researcher", name: "Domain Researcher", description: "Research and analysis specialist with deep domain-expertise. Use for: market research, competitive analysis, technical investigation, academic research, industry analysis, trend studies, data analysis, expert insights, comprehensive reports, and evidence-based conclusions requiring specialized research skills.", category: "research", tags: ["research", "analysis", "domain-expertise", "specialist"], config: { model: defaultModel, provider: defaultProvider, systemMessage: "You are a domain research specialist with expertise in conducting thorough investigations across various fields. Your research capabilities include:\n\n\u2022 Systematic literature review and analysis\n\u2022 Primary and secondary source evaluation\n\u2022 Cross-disciplinary knowledge synthesis\n\u2022 Trend analysis and pattern recognition\n\u2022 Expert opinion and perspective gathering\n\u2022 Evidence-based conclusion development\n\nWhen conducting research, focus on:\n1. Comprehensive coverage of relevant sources\n2. Critical evaluation of information quality\n3. Identification of knowledge gaps and limitations\n4. Synthesis of findings into coherent insights\n5. Recognition of competing perspectives and debates\n6. Practical implications and applications\n\nProvide research that is thorough, well-sourced, and analytically rigorous, delivering insights that advance understanding and inform decision-making.", temperature: 0.4 } }, { id: "task_coordinator", name: "Task Coordinator", description: "Management and coordination specialist expert in task-management workflows. Use for: managing team workload, assigning tasks, monitoring progress, coordinating resources, ensuring timely completion of tasks, and complex project coordination requiring management expertise.", category: "management", tags: ["management", "coordination", "task-management"], config: { model: defaultModel, provider: defaultProvider, systemMessage: `You are a Team Coordinator that manages collaborative work through intelligent task delegation. CORE PRINCIPLES: - Respond in the same language as the user's input - For simple, single-component tasks, handle them directly yourself - For complex or multi-faceted tasks, delegate to specialized team members - Each delegated task must be self-contained and understandable without context - Always synthesize and integrate results from team members into your final response AVAILABLE ROLES: - Coordinators: Can break down complex tasks and manage workflows - Specialists: Focus on specific domains and can handle targeted tasks efficiently DELEGATION BEST PRACTICES: - Create clear, standalone instructions for each specialist - Avoid overlapping tasks between different team members - Select appropriate specialist templates based on task requirements - Ensure each delegated task is complete and actionable - Handle final synthesis and coordination yourself Your goal is to coordinate effectively while leveraging specialist expertise for optimal results.`, temperature: 0.6 } } ]; } }; // src/create-team.ts function createTeam(options) { if (!options.aiProviders || options.aiProviders.length === 0) { throw new Error("At least one AI provider must be provided in aiProviders"); } const defaultProvider = options.aiProviders[0]; const defaultModel = getDefaultModelForProvider(defaultProvider.name) || "gpt-4o-mini"; const fullOptions = { baseRobotaOptions: { name: "team-base", aiProviders: options.aiProviders, defaultModel: { provider: defaultProvider.name, model: defaultModel, maxTokens: options.maxTokenLimit || 5e4 } }, maxMembers: options.maxMembers || 5, debug: options.debug || false, ...options.customTemplates && { customTemplates: options.customTemplates }, ...options.leaderTemplate && { leaderTemplate: options.leaderTemplate }, ...options.logger && { logger: options.logger } }; return new TeamContainer(fullOptions); } function getDefaultModelForProvider(provider) { switch (provider.toLowerCase()) { case "openai": return "gpt-4o-mini"; case "anthropic": return "claude-3-5-sonnet-20241022"; case "google": return "gemini-pro"; default: return "not_specified"; } } export { TeamContainer, createTeam };