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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
# agent_stubs.py
"""
Agent implementations for the orchestrator

Core agents are fully implemented in src/agents/
Task-specific execution agents are implemented here
"""

import logging
from typing import Dict, Any, Optional
import asyncio

logger = logging.getLogger(__name__)

# Import the fully implemented core agents
from src.agents.intent_agent import IntentRecognitionAgent, create_intent_agent
from src.agents.synthesis_agent import EnhancedSynthesisAgent, create_synthesis_agent
from src.agents.safety_agent import SafetyCheckAgent, create_safety_agent
from src.agents.skills_identification_agent import SkillsIdentificationAgent, create_skills_identification_agent

# Compatibility wrappers for core agents
class IntentRecognitionAgentStub(IntentRecognitionAgent):
    """
    Wrapper for the fully implemented Intent Recognition Agent
    Maintains compatibility with orchestrator expectations
    """
    pass

class ResponseSynthesisAgentStub(EnhancedSynthesisAgent):
    """
    Wrapper for the fully implemented Enhanced Synthesis Agent
    Maintains compatibility with orchestrator expectations
    """
    pass

class SafetyCheckAgentStub(SafetyCheckAgent):
    """
    Wrapper for the fully implemented Safety Check Agent
    Maintains compatibility with orchestrator expectations
    """
    pass

class SkillsIdentificationAgentStub(SkillsIdentificationAgent):
    """
    Wrapper for the fully implemented Skills Identification Agent
    Maintains compatibility with orchestrator expectations
    """
    pass


# ============================================================================
# Task-Specific Execution Agents
# These agents handle specialized tasks in the execution plan
# ============================================================================

class TaskExecutionAgent:
    """
    Base class for task-specific execution agents
    Provides common functionality for all task agents
    """
    
    def __init__(self, llm_router, agent_id: str, task_name: str, specialization: str = ""):
        """
        Initialize task execution agent
        
        Args:
            llm_router: LLMRouter instance for making inference calls
            agent_id: Unique identifier for this agent
            task_name: Name of the task this agent handles
            specialization: Description of what this agent specializes in
        """
        self.llm_router = llm_router
        self.agent_id = agent_id
        self.task_name = task_name
        self.specialization = specialization or f"Specialized in {task_name} tasks"
        logger.info(f"Initialized {self.agent_id}: {self.specialization}")
    
    async def execute(self, user_input: str, context: Dict[str, Any] = None, 
                     previous_results: Dict[str, Any] = None, **kwargs) -> Dict[str, Any]:
        """
        Execute the agent's task
        
        Args:
            user_input: Original user query
            context: Conversation context
            previous_results: Results from previous sequential tasks
            **kwargs: Additional parameters
            
        Returns:
            Dict with task execution results
        """
        try:
            logger.info(f"{self.agent_id} executing task: {self.task_name}")
            
            # Build task-specific prompt
            prompt = self._build_execution_prompt(user_input, context, previous_results, **kwargs)
            
            # Execute via LLM router
            logger.debug(f"{self.agent_id} calling LLM router for {self.task_name}")
            result = await self.llm_router.route_inference(
                task_type="general_reasoning",
                prompt=prompt,
                max_tokens=kwargs.get('max_tokens', 2000),
                temperature=kwargs.get('temperature', 0.7)
            )
            
            if result:
                return {
                    "agent_id": self.agent_id,
                    "task": self.task_name,
                    "status": "completed",
                    "content": result,
                    "content_length": len(str(result)),
                    "method": "llm_enhanced"
                }
            else:
                logger.warning(f"{self.agent_id} returned empty result")
                return {
                    "agent_id": self.agent_id,
                    "task": self.task_name,
                    "status": "empty",
                    "content": "",
                    "content_length": 0,
                    "method": "llm_enhanced"
                }
                
        except Exception as e:
            logger.error(f"{self.agent_id} execution failed: {e}", exc_info=True)
            return {
                "agent_id": self.agent_id,
                "task": self.task_name,
                "status": "error",
                "error": str(e),
                "content": "",
                "method": "llm_enhanced"
            }
    
    def _build_execution_prompt(self, user_input: str, context: Dict[str, Any] = None,
                               previous_results: Dict[str, Any] = None, **kwargs) -> str:
        """
        Build task-specific execution prompt
        Override in subclasses for custom prompt building
        """
        # Build context summary
        context_summary = self._build_context_summary(context)
        
        # Base prompt structure
        prompt = f"""User Query: {user_input}

Context: {context_summary}
"""
        
        # Add previous results if sequential execution
        if previous_results:
            prompt += f"\nPrevious Task Results:\n{self._format_previous_results(previous_results)}\n"
        
        # Add task-specific instructions
        prompt += f"\n{self._get_task_instructions()}"
        
        return prompt
    
    def _build_context_summary(self, context: Dict[str, Any] = None) -> str:
        """Build concise context summary"""
        if not context:
            return "No prior context"
        
        summary_parts = []
        
        # Extract interaction contexts
        interaction_contexts = context.get('interaction_contexts', [])
        if interaction_contexts:
            recent_summaries = [ic.get('summary', '') for ic in interaction_contexts[-3:]]
            if recent_summaries:
                summary_parts.append(f"Recent topics: {', '.join(recent_summaries)}")
        
        # Extract user context
        user_context = context.get('user_context', '')
        if user_context:
            summary_parts.append(f"User background: {user_context[:200]}")
        
        return " | ".join(summary_parts) if summary_parts else "No prior context"
    
    def _format_previous_results(self, previous_results: Dict[str, Any]) -> str:
        """Format previous task results for inclusion in prompt"""
        formatted = []
        for task_name, result in previous_results.items():
            if isinstance(result, dict):
                content = result.get('content', result.get('result', ''))
                if content:
                    formatted.append(f"- {task_name}: {str(content)[:500]}")
        return "\n".join(formatted) if formatted else "No previous results"
    
    def _get_task_instructions(self) -> str:
        """
        Get task-specific instructions
        Override in subclasses
        """
        return f"Task: Execute {self.task_name} based on the user query and context."


# ============================================================================
# Specific Task Execution Agents
# ============================================================================

class InformationGatheringAgent(TaskExecutionAgent):
    """Agent specialized in gathering comprehensive information"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="INFO_GATH_001",
            task_name="information_gathering",
            specialization="Comprehensive information gathering and fact verification"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Gather comprehensive, accurate information relevant to the user's query.
- Focus on facts, definitions, explanations, and verified information
- Structure the information clearly with key points
- Cite important details and provide context
- Ensure accuracy and completeness"""


class ContentResearchAgent(TaskExecutionAgent):
    """Agent specialized in researching and compiling content"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="CONTENT_RESEARCH_001",
            task_name="content_research",
            specialization="Detailed content research and compilation"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Research and compile detailed content about the topic.
- Include multiple perspectives and viewpoints
- Gather current information and relevant examples
- Organize findings logically with clear sections
- Provide comprehensive coverage of the topic"""


class TaskPlanningAgent(TaskExecutionAgent):
    """Agent specialized in creating detailed execution plans"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="TASK_PLAN_001",
            task_name="task_planning",
            specialization="Detailed task planning and execution strategy"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Create a detailed execution plan for the requested task.
- Break down into clear, actionable steps
- Identify requirements and dependencies
- Outline expected outcomes and success criteria
- Consider potential challenges and solutions
- Provide timeline and resource estimates"""


class ExecutionStrategyAgent(TaskExecutionAgent):
    """Agent specialized in developing strategic approaches"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="EXEC_STRAT_001",
            task_name="execution_strategy",
            specialization="Strategic execution methodology development"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Develop a strategic approach for task execution.
- Define methodology and best practices
- Identify implementation considerations
- Provide actionable guidance with clear priorities
- Consider efficiency and effectiveness
- Address risk mitigation strategies"""


class CreativeBrainstormingAgent(TaskExecutionAgent):
    """Agent specialized in creative ideation"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="CREATIVE_BS_001",
            task_name="creative_brainstorming",
            specialization="Creative ideas generation and brainstorming"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Generate creative ideas and approaches for content creation.
- Explore different angles, styles, and formats
- Provide diverse creative options
- Include implementation suggestions
- Encourage innovative thinking
- Balance creativity with practicality"""


class ContentIdeationAgent(TaskExecutionAgent):
    """Agent specialized in content concept development"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="CONTENT_IDEATION_001",
            task_name="content_ideation",
            specialization="Content concepts and ideation development"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Develop content concepts and detailed ideation.
- Create outlines and structural frameworks
- Define themes and key messaging
- Suggest variations and refinement paths
- Provide detailed development paths
- Consider audience and purpose"""


class ResearchAnalysisAgent(TaskExecutionAgent):
    """Agent specialized in research analysis"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="RESEARCH_ANALYSIS_001",
            task_name="research_analysis",
            specialization="Thorough research analysis and insights"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Conduct thorough research analysis on the topic.
- Identify key findings, trends, and patterns
- Analyze different perspectives and methodologies
- Provide comprehensive insights
- Evaluate evidence and sources
- Synthesize complex information"""


class DataCollectionAgent(TaskExecutionAgent):
    """Agent specialized in data collection and organization"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="DATA_COLLECT_001",
            task_name="data_collection",
            specialization="Data point collection and evidence gathering"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Collect and organize relevant data points and evidence.
- Gather statistics, examples, and case studies
- Compile supporting information
- Structure data for easy analysis and reference
- Verify data quality and relevance
- Organize systematically"""


class PatternIdentificationAgent(TaskExecutionAgent):
    """Agent specialized in pattern recognition and analysis"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="PATTERN_ID_001",
            task_name="pattern_identification",
            specialization="Pattern recognition and correlation analysis"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Identify patterns, correlations, and significant relationships.
- Analyze trends and cause-effect relationships
- Discover underlying structures
- Provide insights based on pattern recognition
- Identify anomalies and exceptions
- Connect disparate information"""


class ProblemAnalysisAgent(TaskExecutionAgent):
    """Agent specialized in problem analysis"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="PROBLEM_ANALYSIS_001",
            task_name="problem_analysis",
            specialization="Detailed problem analysis and root cause identification"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Analyze the problem in detail.
- Identify root causes and contributing factors
- Understand constraints and limitations
- Break down the problem into components
- Map problem relationships
- Prioritize issues for systematic resolution"""


class SolutionResearchAgent(TaskExecutionAgent):
    """Agent specialized in solution research and evaluation"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="SOLUTION_RESEARCH_001",
            task_name="solution_research",
            specialization="Solution research and evaluation"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Research and evaluate potential solutions.
- Compare different approaches and methodologies
- Assess pros and cons of each option
- Recommend best practices
- Consider implementation feasibility
- Evaluate effectiveness and efficiency"""


class CurriculumPlanningAgent(TaskExecutionAgent):
    """Agent specialized in educational curriculum design"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="CURRICULUM_PLAN_001",
            task_name="curriculum_planning",
            specialization="Educational curriculum and learning path design"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Design educational curriculum and learning path.
- Structure content progressively
- Define clear learning objectives
- Suggest appropriate resources
- Create comprehensive learning framework
- Ensure pedagogical effectiveness"""


class EducationalContentAgent(TaskExecutionAgent):
    """Agent specialized in educational content generation"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="EDUC_CONTENT_001",
            task_name="educational_content",
            specialization="Educational content with clear explanations"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Generate educational content with clear explanations.
- Use effective teaching methods
- Provide examples and analogies
- Manage progressive complexity
- Make content accessible and engaging
- Support learning objectives"""


class TechnicalResearchAgent(TaskExecutionAgent):
    """Agent specialized in technical research"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="TECH_RESEARCH_001",
            task_name="technical_research",
            specialization="Technical aspects and solutions research"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Research technical aspects and solutions.
- Gather technical documentation
- Identify best practices and standards
- Compile implementation details
- Structure technical information clearly
- Provide practical guidance"""


class GuidanceGenerationAgent(TaskExecutionAgent):
    """Agent specialized in step-by-step guidance"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="GUIDANCE_GEN_001",
            task_name="guidance_generation",
            specialization="Step-by-step guidance and instructions"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Generate step-by-step guidance and instructions.
- Create clear, actionable steps
- Provide detailed explanations
- Include troubleshooting tips
- Ensure comprehensiveness
- Make guidance easy to follow"""


class ContextEnrichmentAgent(TaskExecutionAgent):
    """Agent specialized in context enrichment"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="CONTEXT_ENRICH_001",
            task_name="context_enrichment",
            specialization="Conversation context enrichment"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Enrich the conversation with relevant context and insights.
- Add helpful background information
- Connect to previous topics
- Include engaging details
- Enhance understanding
- Maintain conversation flow"""


class GeneralResearchAgent(TaskExecutionAgent):
    """Agent for general research tasks"""
    
    def __init__(self, llm_router):
        super().__init__(
            llm_router,
            agent_id="GENERAL_RESEARCH_001",
            task_name="general_research",
            specialization="General research and information gathering"
        )
    
    def _get_task_instructions(self) -> str:
        return """Task: Conduct general research and information gathering.
- Compile relevant information
- Gather insights and useful details
- Organize findings clearly
- Provide comprehensive coverage
- Structure for easy reference"""


# ============================================================================
# Factory Functions for Task Execution Agents
# ============================================================================

def create_task_execution_agent(task_name: str, llm_router) -> TaskExecutionAgent:
    """
    Factory function to create task-specific execution agents
    
    Args:
        task_name: Name of the task to create an agent for
        llm_router: LLMRouter instance
        
    Returns:
        Appropriate TaskExecutionAgent instance
    """
    agent_map = {
        "information_gathering": InformationGatheringAgent,
        "content_research": ContentResearchAgent,
        "task_planning": TaskPlanningAgent,
        "execution_strategy": ExecutionStrategyAgent,
        "creative_brainstorming": CreativeBrainstormingAgent,
        "content_ideation": ContentIdeationAgent,
        "research_analysis": ResearchAnalysisAgent,
        "data_collection": DataCollectionAgent,
        "pattern_identification": PatternIdentificationAgent,
        "problem_analysis": ProblemAnalysisAgent,
        "solution_research": SolutionResearchAgent,
        "curriculum_planning": CurriculumPlanningAgent,
        "educational_content": EducationalContentAgent,
        "technical_research": TechnicalResearchAgent,
        "guidance_generation": GuidanceGenerationAgent,
        "context_enrichment": ContextEnrichmentAgent,
        "general_research": GeneralResearchAgent,
    }
    
    agent_class = agent_map.get(task_name, GeneralResearchAgent)
    return agent_class(llm_router)


def create_task_execution_agents(task_names: list, llm_router) -> Dict[str, TaskExecutionAgent]:
    """
    Factory function to create multiple task execution agents
    
    Args:
        task_names: List of task names to create agents for
        llm_router: LLMRouter instance
        
    Returns:
        Dictionary mapping task names to agent instances
    """
    agents = {}
    for task_name in task_names:
        agents[task_name] = create_task_execution_agent(task_name, llm_router)
    return agents