Spaces:
Build error
Build error
Update app.py
Browse files1064 unmodified lines10651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192147 unmodified lines13401341134213431344134513461 unmodified line13481349135013511352135313545 unmodified lines1360136113621363136413651366146 unmodified lines15131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154899 unmodified lines164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671107 unmodified lines1779178017811782178317841785657 unmodified lines2443244424452446244724482449245024512452245324542455245617 unmodified lines247424752476247724782479248024812482248324842485248624871064 unmodified linesself.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 descriptionReturns:str: A formatted prompt for the boss agent"""# Get historical performance if availabletask_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 formatRemember:- 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 taskPlease 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_promptdef _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 responseReturns:Tuple[List[Dict], int]: A tuple containing the list of agent specifications and recommended rounds"""try:# Extract agent specificationsagent_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 innext(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 roundsrounds_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 agentsif len(agent_specs) != 3:raise ValueError("Boss must specify exactly 3 agents")return agent_specs, roundsexcept Exception as e:print(f"Error parsing boss response: {str(e)}")# Return default specifications if parsing failsreturn [{"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"]}], 3class DynamicLLM:_instance = None147 unmodified linesvalidation_result = Nonetry:pattern_analysis = mas.execute_agent_query(task_description,agent_specs[0],context={"phase": "analysis", "trial": trial}1 unmodified lineif not pattern_analysis:raise ValueError("Pattern analysis failed")transformation_result = mas.execute_agent_query(task_description,agent_specs[1],context={5 unmodified linesif not transformation_result:raise ValueError("Transformation failed")validation_result = mas.execute_agent_query(task_description,agent_specs[2],context={146 unmodified linesreturn order[::-1] # Reverse for correct execution orderclass DynamicMultiAgentSystem:"""Coordinates a single LLM that switches between agent roles."""def __init__(self):self.llm = DynamicLLM() # Single LLM instanceself.g_designer = GDesigner(num_roles=3) # Still track 3 role positionsself.task_adapter = TaskAdapter()self.protocol = CommunicationProtocol()# Role definitionsself.roles = {'analyst': {'name': 'Pattern Analyst','state': {},'memory': {},'performance_history': []},'transformer': {'name': 'Grid Transformer','state': {},'memory': {},'performance_history': []},'validator': {'name': 'Validator','state': {},'memory': {},'performance_history': []}}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 staterole['state'] = result# Update memory if successfulif 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 sizeif len(role['memory'][task_type]) > 100:role['memory'][task_type] = role['memory'][task_type][-100:]except Exception as e:print(f"Error updating role memory: {str(e)}")107 unmodified lines# Initialize the multi-agent systemg_designer = GDesigner()llm = DynamicLLM(g_designer)mas = MultiAgentSystem(g_designer)# Execute the prediction pipeline# 1. Pattern Analysis657 unmodified linesprint(f"Error reading input: {str(e)}")return ""def main():try:# Get user input for query or use the dataset queryuse_dataset_query = False # Set this to False to use user inputif use_dataset_query:evaluator = ARCEvaluator()interface = create_gradio_interface()interface.launch(share=True)"""Main execution function."""# Setup pathstask_dir = "evaluation/tasks"17 unmodified lineselse:print("Evaluation failed!")else:# Get user input for queryquery = get_user_input()if not query:print("No input provided. Exiting...")returnexcept Exception as e:print(f"Error in main execution: {str(e)}")if __name__ == "__main__":main()1064 unmodified lines1065106610671068106910701071147 unmodified lines12191220122112221223122412251 unmodified line12271228122912301231123212335 unmodified lines1239124012411242124312441245146 unmodified lines1392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147499 unmodified lines157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603107 unmodified lines1711171217131714171517161717657 unmodified lines237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269317 unmodified lines271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727781064 unmodified linesself.experience_buffer = []self.performance_history = {}class DynamicLLM:_instance = None147 unmodified linesvalidation_result = Nonetry:pattern_analysis = dynamic_mas.execute_agent_query(task_description,agent_specs[0],context={"phase": "analysis", "trial": trial}1 unmodified lineif not pattern_analysis:raise ValueError("Pattern analysis failed")transformation_result = dynamic_mas.execute_agent_query(task_description,agent_specs[1],context={5 unmodified linesif not transformation_result:raise ValueError("Transformation failed")validation_result = dynamic_mas.execute_agent_query(task_description,agent_specs[2],context={146 unmodified linesreturn order[::-1] # Reverse for correct execution orderclass DynamicMultiAgentSystem ():"""Coordinates a single LLM that switches between agent roles."""def __init__(self):self.llm = DynamicLLM() # Single LLM instanceself.g_designer = GDesigner(num_roles=3) # Still track 3 role positionsself.task_adapter = TaskAdapter()self.protocol = CommunicationProtocol()self.is_string_response = Falsedef 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_responseself.is_string_response = Trueelse:# 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 = Falsedef _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 rolerole_state = self.llm.switch_role(role_info['name'],{'task': task,'current_state': current_state,'role_memory': role_info['memory']})# Process with current roleresult = self._process_role(role_id, task, messages, role_state)# Store resultmessages[role_id] = resultcurrent_state[role_id] = result# Update role's memoryself._update_role_memory(role_id, task, result)# Aggregate string responsesfinal_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 Nonedef 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]role['state'] = resultif 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 sizefor 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 systemg_designer = GDesigner()llm = DynamicLLM(g_designer)mas = DynamicMultiAgentSystem(g_designer)# Execute the prediction pipeline# 1. Pattern Analysis657 unmodified linesprint(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 = llmdef 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 formatRemember:- 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 taskPlease 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 specificationsagent_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 innext(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 agentsif len(agent_specs) != 3:raise ValueError("Boss must specify exactly 3 agents")return agent_specs, #roundsexcept Exception as e:print(f"Error parsing boss response: {str(e)}")# Return default specifications if parsing failsreturn [{"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"]}], 3def 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 descriptionReturns:str: A formatted prompt for the boss agent"""# Get historical performance if availabletask_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 formatRemember:- 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 taskPlease 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_promptdef _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 responseReturns:Tuple[List[Dict], int]: A tuple containing the list of agent specifications and recommended rounds"""try:# Extract agent specificationsagent_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 innext(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 roundsrounds_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 agentsif len(agent_specs) != 3:raise ValueError("Boss must specify exactly 3 agents")return agent_specs, roundsexcept Exception as e:print(f"Error parsing boss response: {str(e)}")# Return default specifications if parsing failsreturn [{"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 recommendationsNote: 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 queryuse_dataset_query = True # Set this to False to use user inputif use_dataset_query:evaluator = ARCEvaluator()interface = create_gradio_interface()interface.launch()"""Main execution function."""# Setup pathstask_dir = "evaluation/tasks"17 unmodified lineselse:print("Evaluation failed!")else:# Create the Gradio interface for user input modedemo = 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 demodemo.launch(enable_queue=True)"""Main execution function."""llm = DynamicLLM()# Get user input for queryquery = get_user_input()# Initialize componentsquery_handler = QueryHandler.process_query()# Access each valueprompt = 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 responseboss_agent = BossAgent(llm) #Activate BossAgent llm functionsagent_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.aisystem = 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...")returnexcept Exception as e:print(f"Error in main execution: {str(e)}")if __name__ == "__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