Research_AI_Assistant / agent_stubs.py
JatsTheAIGen's picture
cumulative upgrade - context + safety + response length v2
a5d9083
raw
history blame
21.4 kB
# 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