Spaces:
Build error
Build error
Update app.py
Browse files1064 unmodified lines10651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110681093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189106910701071147 unmodified lines121912201221134312221223122412251 unmodified line122712281229135112301231123212335 unmodified lines12391240124113631242124312441245146 unmodified lines139213931394151613951396139713981399140014011402140314041405140614071408152315241525152615271528152915301531153215331534153515361537153815391540154115421409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466154415451467146814691470147114721473147499 unmodified lines157415751576165116521577157816551656165716581659166016611662166315791580158115821583158415851586158715881589159015911592159315941595166516661667166815961597159815991600160116021603107 unmodified lines17111712171317821714171517161717657 unmodified lines23752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685244926862687268826892453269026912692269317 unmodified lines2711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774248727752776277727781064 unmodified lines self.experience_buffer = [] self.performance_history = {}
def _create_boss_prompt(self, query: str) -> str: """ Creates a structured prompt for the boss agent to interpret tasks and define specialized agents. Args: query (str): The user's input query/task description Returns: str: A formatted prompt for the boss agent """ # Get historical performance if available task_history = self.g_designer.experience_buffer[-5:] if self.g_designer.experience_buffer else [] historical_insights = "\n".join([ f"- Previous task: {exp['task']}, Success: {exp['success']}, Time: {exp['execution_time']:.1f}s" for exp in task_history ]) boss_prompt = f"""You are the Boss AI responsible for managing a team of AI agents to solve complex tasks. CURRENT TASK: {query}
HISTORICAL CONTEXT:{historical_insights if task_history else 'No previous task history available.'}
YOUR RESPONSIBILITIES:1. Analyze the given task thoroughly2. Define exactly 3 specialized AI agents that would be best suited for solving this task3. Ensure the agents have complementary skills and clear responsibilities4. Consider any insights from previous similar tasks5. Provide structured response in the required format
Remember: - A dedicated summarizer agent will be added automatically- Focus on creating agents with distinct, complementary roles- Consider both general capabilities and specialized knowledge needed- Agents should collaborate effectively to solve the task
Please provide your response in the following format:
TASK ANALYSIS:[Provide a brief analysis of the task's requirements and complexity]
AGENT SPECIFICATIONS:1. [Role1] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed]
2. [Role2] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed]
3. [Role3] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed]
COLLABORATION STRATEGY:[Brief description of how these agents should work together]
EXECUTION PLAN:Recommended Rounds: [Number between 1-8]Rationale: [Brief explanation for the number of rounds]
Based on your analysis, provide the complete response following this format."""
return boss_prompt
def _parse_boss_response(self, response: str) -> Tuple[List[Dict], int]: """ Parses the boss's response to extract agent specifications and round count. Args: response (str): The boss agent's formatted response Returns: Tuple[List[Dict], int]: A tuple containing the list of agent specifications and recommended rounds """ try: # Extract agent specifications agent_specs = [] agent_sections = response.split('\n\n') for section in agent_sections: if 'Primary Function:' in section: lines = section.strip().split('\n') role = lines[0].strip().replace('1.', '').replace('2.', '').replace('3.', '').strip() plugins = [p.strip() for p in next(l for l in lines if 'Plugins:' in l) .replace('Plugins:', '') .strip() .split(',')] agent_specs.append({ "role": role, "base": self.llm.model_name, "plugins": plugins }) # Extract recommended rounds rounds_match = re.search(r'Recommended Rounds:\s*(\d+)', response) rounds = min(max(int(rounds_match.group(1)) if rounds_match else 3, 1), 8) # Ensure exactly 3 agents if len(agent_specs) != 3: raise ValueError("Boss must specify exactly 3 agents") return agent_specs, rounds except Exception as e: print(f"Error parsing boss response: {str(e)}") # Return default specifications if parsing fails return [ {"base": self.llm.model_name, "role": "Analyst", "plugins": ["analysis"]}, {"base": self.llm.model_name, "role": "Expert", "plugins": ["domain"]}, {"base": self.llm.model_name, "role": "Critic", "plugins": ["evaluation"]} ], 3 class DynamicLLM: _instance = None147 unmodified lines validation_result = None try: pattern_analysis = mas.execute_agent_query( pattern_analysis = dynamic_mas.execute_agent_query( task_description, agent_specs[0], context={"phase": "analysis", "trial": trial}1 unmodified line if not pattern_analysis: raise ValueError("Pattern analysis failed") transformation_result = mas.execute_agent_query( transformation_result = dynamic_mas.execute_agent_query( task_description, agent_specs[1], context={5 unmodified lines if not transformation_result: raise ValueError("Transformation failed") validation_result = mas.execute_agent_query( validation_result = dynamic_mas.execute_agent_query( task_description, agent_specs[2], context={146 unmodified lines return order[::-1] # Reverse for correct execution order class DynamicMultiAgentSystem:class DynamicMultiAgentSystem (): """Coordinates a single LLM that switches between agent roles.""" def __init__(self): self.llm = DynamicLLM() # Single LLM instance self.g_designer = GDesigner(num_roles=3) # Still track 3 role positions self.task_adapter = TaskAdapter() self.protocol = CommunicationProtocol() self.is_string_response = False def initialize_roles(self, boss_response=None): """Initialize roles based on boss response or default configuration.""" if boss_response and isinstance(boss_response, dict): self.roles = boss_response self.is_string_response = True # Role definitions self.roles = { 'analyst': { 'name': 'Pattern Analyst', 'state': {}, 'memory': {}, 'performance_history': [] }, 'transformer': { 'name': 'Grid Transformer', 'state': {}, 'memory': {}, 'performance_history': [] }, 'validator': { 'name': 'Validator', 'state': {}, 'memory': {}, 'performance_history': [] else: # Role definitions for evaluation dataset only. self.roles = { 'analyst': { 'name': 'Pattern Analyst', 'state': {}, 'memory': {}, 'performance_history': [] }, 'transformer': { 'name': 'Grid Transformer', 'state': {}, 'memory': {}, 'performance_history': [] }, 'validator': { 'name': 'Validator', 'state': {}, 'memory': {}, 'performance_history': [] } } self.is_string_response = False
def _process_string_task(self, task: Dict) -> Dict: """Process tasks that require string responses.""" try: messages = {} current_state = {} for role_id, role_info in self.roles.items(): # Switch LLM to current role role_state = self.llm.switch_role( role_info['name'], { 'task': task, 'current_state': current_state, 'role_memory': role_info['memory'] } ) # Process with current role result = self._process_role(role_id, task, messages, role_state) # Store result messages[role_id] = result current_state[role_id] = result # Update role's memory self._update_role_memory(role_id, task, result) # Aggregate string responses final_response = self.protocol.aggregate_string_results(messages) return { 'result': final_response, 'messages': messages } } except Exception as e: print(f"Error in string task processing: {str(e)}") return None def process_task(self, task: Dict) -> Dict: """Process task using single LLM switching between roles.""" try:99 unmodified lines """Update role-specific memory with results.""" try: role = self.roles[role_id] # Update state role['state'] = result # Update memory if successful if result.get('confidence', 0) > 0.8: task_type = self._get_task_type(task) if task_type not in role['memory']: role['memory'][task_type] = [] role['memory'][task_type].append({ 'task_features': self._extract_task_features(task), 'solution_approach': result.get('approach'), 'success': True if self.is_string_response: if 'string_responses' not in role['memory']: role['memory']['string_responses'] = [] role['memory']['string_responses'].append({ 'task': task, 'response': result }) else: if result.get('confidence', 0) > 0.8: task_type = self._get_task_type(task) if task_type not in role['memory']: role['memory'][task_type] = [] role['memory'][task_type].append({ 'task_features': self._extract_task_features(task), 'solution_approach': result.get('approach'), 'success': True }) # Limit memory size if len(role['memory'][task_type]) > 100: role['memory'][task_type] = role['memory'][task_type][-100:] # Limit memory size for key in role['memory']: if len(role['memory'][key]) > 100: role['memory'][key] = role['memory'][key][-100:] except Exception as e: print(f"Error updating role memory: {str(e)}")107 unmodified lines # Initialize the multi-agent system g_designer = GDesigner() llm = DynamicLLM(g_designer) mas = MultiAgentSystem(g_designer) mas = DynamicMultiAgentSystem(g_designer)
# Execute the prediction pipeline # 1. Pattern Analysis657 unmodified lines print(f"Error reading input: {str(e)}") return ""
#This class is for the user query boss llm for creating agents to solve user query tasks. class BossAgent: def __init__(self, llm: DynamicLLM): self.llm = llm def create_prompt(self, query: str) -> str: """Creates structured prompt for boss agent.""" task_history = self.llm.g_designer.experience_buffer[-5:] if hasattr(self.llm, 'g_designer') else [] historical_insights = "\n".join([ f"- Previous task: {exp['task']}, Success: {exp['success']}, Time: {exp['execution_time']:.1f}s" for exp in task_history ]) return f"""You are the Boss AI responsible for managing a team of AI agents to solve complex tasks. CURRENT TASK: {query}
HISTORICAL CONTEXT:{historical_insights if task_history else 'No previous task history available.'}
YOUR RESPONSIBILITIES:1. Analyze the given task thoroughly2. Define exactly 3 specialized AI agents that would be best suited for solving this task3. Ensure the agents have complementary skills and clear responsibilities4. Consider any insights from previous similar tasks5. Provide structured response in the required format
Remember: - A dedicated summarizer agent will be added automatically- Focus on creating agents with distinct, complementary roles- Consider both general capabilities and specialized knowledge needed- Agents should collaborate effectively to solve the task
Please provide your response in the following format:
TASK ANALYSIS:[Provide a brief analysis of the task's requirements and complexity]
AGENT SPECIFICATIONS:1. [Role1] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed]
2. [Role2] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed]
3. [Role3] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed]
COLLABORATION STRATEGY:[Brief description of how these agents should work together]
EXECUTION PLAN:Recommended Rounds: [Number between 1-8]Rationale: [Brief explanation for the number of rounds]"""
def parse_response(self, response: str) -> Tuple[List[Dict], int]: """Parses boss response to extract agent specifications and round count.""" try: # Extract agent specifications agent_specs = [] agent_sections = response.split('\n\n') for section in agent_sections: if 'Primary Function:' in section: lines = section.strip().split('\n') role = lines[0].strip().replace('1.', '').replace('2.', '').replace('3.', '').strip() plugins = [p.strip() for p in next(l for l in lines if 'Plugins:' in l) .replace('Plugins:', '') .strip() .split(',')] agent_specs.append({ "role": role, "base": self.llm.model_name, "plugins": plugins }) # Extract recommended rounds #Rounds is turned off to save on memory but can be turned on and added easily to the program by adding it to the dynamic agent framework class. # rounds_match = re.search(r'Recommended Rounds:\s*(\d+)', response) # rounds = min(max(int(rounds_match.group(1)) if rounds_match else 3, 1), 8) # Ensure exactly 3 agents if len(agent_specs) != 3: raise ValueError("Boss must specify exactly 3 agents") return agent_specs, #rounds except Exception as e: print(f"Error parsing boss response: {str(e)}") # Return default specifications if parsing fails return [ {"base": self.llm.model_name, "role": "Analyst", "plugins": ["analysis"]}, {"base": self.llm.model_name, "role": "Expert", "plugins": ["domain"]}, {"base": self.llm.model_name, "role": "Critic", "plugins": ["evaluation"]} ], 3
def process_query(self, query: str) -> Tuple[List[Dict], int]: """Process user query and return agent specifications and rounds.""" prompt = self.create_prompt(query) response = self.llm.generate_response(prompt, role="boss") return self.parse_response(response)
#These (the 2 functions below) are for processing the queries for the Arc test. They currently are turned off and do not do anything but could be added in place of the pre-generated LLMs in the Dynamic Agent Framework. '''def _create_boss_prompt(self, query: str) -> str: """ Creates a structured prompt for the boss agent to interpret tasks and define specialized agents. Args: query (str): The user's input query/task description Returns: str: A formatted prompt for the boss agent """ # Get historical performance if available task_history = self.g_designer.experience_buffer[-5:] if self.g_designer.experience_buffer else [] historical_insights = "\n".join([ f"- Previous task: {exp['task']}, Success: {exp['success']}, Time: {exp['execution_time']:.1f}s" for exp in task_history ]) boss_prompt = f"""You are the Boss AI responsible for managing a team of AI agents to solve complex tasks. CURRENT TASK: {query}
HISTORICAL CONTEXT:{historical_insights if task_history else 'No previous task history available.'}
YOUR RESPONSIBILITIES:1. Analyze the given task thoroughly2. Define exactly 3 specialized AI agents that would be best suited for solving this task3. Ensure the agents have complementary skills and clear responsibilities4. Consider any insights from previous similar tasks5. Provide structured response in the required format
Remember: - A dedicated summarizer agent will be added automatically- Focus on creating agents with distinct, complementary roles- Consider both general capabilities and specialized knowledge needed- Agents should collaborate effectively to solve the task
Please provide your response in the following format:
TASK ANALYSIS:[Provide a brief analysis of the task's requirements and complexity]
AGENT SPECIFICATIONS:1. [Role1] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed]
2. [Role2] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed]
3. [Role3] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed]
COLLABORATION STRATEGY:[Brief description of how these agents should work together]
EXECUTION PLAN:Recommended Rounds: [Number between 1-8]Rationale: [Brief explanation for the number of rounds]
Based on your analysis, provide the complete response following this format."""
return boss_prompt
def _parse_boss_response(self, response: str) -> Tuple[List[Dict], int]: """ Parses the boss's response to extract agent specifications and round count. Args: response (str): The boss agent's formatted response Returns: Tuple[List[Dict], int]: A tuple containing the list of agent specifications and recommended rounds """ try: # Extract agent specifications agent_specs = [] agent_sections = response.split('\n\n') for section in agent_sections: if 'Primary Function:' in section: lines = section.strip().split('\n') role = lines[0].strip().replace('1.', '').replace('2.', '').replace('3.', '').strip() plugins = [p.strip() for p in next(l for l in lines if 'Plugins:' in l) .replace('Plugins:', '') .strip() .split(',')] agent_specs.append({ "role": role, "base": self.llm.model_name, "plugins": plugins }) # Extract recommended rounds rounds_match = re.search(r'Recommended Rounds:\s*(\d+)', response) rounds = min(max(int(rounds_match.group(1)) if rounds_match else 3, 1), 8) # Ensure exactly 3 agents if len(agent_specs) != 3: raise ValueError("Boss must specify exactly 3 agents") return agent_specs, rounds except Exception as e: print(f"Error parsing boss response: {str(e)}") # Return default specifications if parsing fails return [ {"base": self.llm.model_name, "role": "Analyst", "plugins": ["analysis"]}, {"base": self.llm.model_name, "role": "Expert", "plugins": ["domain"]}, {"base": self.llm.model_name, "role": "Critic", "plugins": ["evaluation"]} ], 3''' #Function below allows the Boss LLM to handle both grid (evaluation for Arc only) and user queries. Only the generic user query is used but the grid can be easily added in the main def function. class QueryHandler: """Handles different types of queries and generates appropriate prompts.""" def __init__(self): self.default_prompt = self._create_default_prompt #self.grid_prompt = self._create_grid_prompt
# def create_prompt(self, query: str, is_grid_query: bool = True) -> str: # """Create appropriate prompt based on query type.""" # if not is_grid_query: # return self._create_custom_prompt(query) #This is in case the user wants to use a dataset as this can be turned on by removing the comments to allow the user to use a dataset. # return self._create_grid_prompt(query) def _create_default_prompt(self, query: str) -> str: """Create a standard prompt for non-grid queries.""" return f"""Analyze and respond to the following query:
Query: {query}
Please provide a clear and concise response that addresses the query directly.Focus on providing practical, implementable solutions.
Your response should include:1. Direct answer to the query2. Any relevant explanations or context3. Specific recommendations or solutions"""
def _create_grid_prompt(self, query: str) -> str: """Create a prompt for grid-based ARC tasks.""" return f"""Analyze the following ARC task with grid patterns:
Task Description: {query}
Training Examples:[Grid examples will be formatted here]
Your analysis should include:1. Pattern identification2. Transformation rules3. Grid-based solution approach4. Step-by-step implementation5. Final output grid"""
def _create_custom_prompt(self, query: str) -> str: """Create a customized prompt for specific query types.""" return f"""Process the following specialized query:
Query: {query}
Please provide:1. Direct response2. Key insights3. Actionable recommendations
Note: This is a non-grid query that requires specific domain expertise."""
def process_query(self, query: str, is_grid_query: bool = True) -> Dict[str, Any]: """Process the query and return appropriate response format.""" prompt = self.create_prompt(query, is_grid_query) return { 'prompt': prompt, 'is_grid_query': is_grid_query, 'query_type': 'grid' if is_grid_query else 'standard', 'timestamp': time.time() } def main(): try: # Get user input for query or use the dataset query use_dataset_query = False # Set this to False to use user input use_dataset_query = True # Set this to False to use user input if use_dataset_query: evaluator = ARCEvaluator() interface = create_gradio_interface() interface.launch(share=True) interface.launch() """Main execution function.""" # Setup paths task_dir = "evaluation/tasks"17 unmodified lines else: print("Evaluation failed!") else: # Create the Gradio interface for user input mode demo = gr.Interface( fn=process_query, inputs=gr.Textbox( label="Enter your task", placeholder="Describe the task you want to process...", lines=3 ), outputs=gr.Textbox( label="System Response", lines=5 ), title="Dynamic Agent System", description="Enter a task and the system will process it using dynamic agents.", examples=[ ["Analyze the sentiment of this text"], ["Generate a summary of the following document"], ], cache_examples=True ) # Launch the demo demo.launch( enable_queue=True )
"""Main execution function.""" llm = DynamicLLM() # Get user input for query query = get_user_input() # Initialize components query_handler = QueryHandler.process_query() # Access each value prompt = query_handler['prompt'] is_grid_query = query_handler['is_grid_query'] query_type = query_handler['query_type'] timestamp = query_handler['timestamp'] # For string-based responses # Get boss agent response boss_agent = BossAgent(llm) #Activate BossAgent llm functions agent_specs, rounds = boss_agent.process_query(prompt) #boss_response variable in claude.ai refers to this prompt here.Retrieve agent roles and rounds for dynamic agent system.
# Initialize the dynamic multi-agent system - Need to change this function from claude.ai system = DynamicMultiAgentSystem() system.initialize_roles(agent_specs)
# Process the task with the defined agents #Need to add this. result = system.process_task({"query": query}) # evaluator = ARCEvaluator() Does nothing. if not query: print("No input provided. Exiting...") return
except Exception as e: print(f"Error in main execution: {str(e)}")
if __name__ == "__main__": main() main()
#Need to create a switch in the multiagent class so it will take the response from the bossllm class to set-up the agents. if this response is not recieved, then the #ai agent framework will just handle the dataset as before. This will need to be edited from claude's response. app.py+457-166