| 1 | import importlib |
| 2 | import json |
| 3 | import os |
| 4 | from configs.prompts import TRIAGE_MESSAGE_PROMPT, TRIAGE_SYSTEM_PROMPT, EVAL_GROUNDTRUTH_PROMPT, EVAL_PLANNING_PROMPT, ITERATE_PROMPT |
| 5 | from src.utils import get_completion, is_dict_empty |
| 6 | from configs.general import Colors, max_iterations |
| 7 | from src.swarm.assistants import Assistant |
| 8 | from src.swarm.tool import Tool |
| 9 | from src.tasks.task import EvaluationTask |
| 10 | from src.runs.run import Run |
| 11 | |
| 12 | |
| 13 | |
| 14 | class LocalEngine: |
| 15 | def __init__(self, client, tasks, persist=False): |
| 16 | self.client = client |
| 17 | self.assistants = [] |
| 18 | self.last_assistant = None |
| 19 | self.persist = persist |
| 20 | self.tasks = tasks |
| 21 | self.tool_functions = [] |
| 22 | self.global_context = {} |
| 23 | |
| 24 | def load_tools(self): |
| 25 | tools_path = 'configs/tools' |
| 26 | |
| 27 | self.tool_functions = [] |
| 28 | for tool_dir in os.listdir(tools_path): |
| 29 | dir_path = os.path.join(tools_path, tool_dir) |
| 30 | if os.path.isdir(dir_path): |
| 31 | for tool_name in os.listdir(dir_path): |
| 32 | if tool_name.endswith('.json'): |
| 33 | with open(os.path.join(dir_path, tool_name), 'r') as file: |
| 34 | try: |
| 35 | tool_def = json.load(file) |
| 36 | tool = Tool(type=tool_def['type'], function=tool_def['function'], human_input=tool_def.get('human_input', False)) |
| 37 | self.tool_functions.append(tool) |
| 38 | except json.JSONDecodeError as e: |
| 39 | print(f"Error decoding JSON for tool {tool_name}: {e}") |
| 40 | |
| 41 | def load_all_assistants(self): |
| 42 | base_path = 'configs/assistants' |
| 43 | self.load_tools() |
| 44 | tool_defs = {tool.function.name: tool.function.dict() for tool in self.tool_functions} |
| 45 | |
| 46 | for assistant_dir in os.listdir(base_path): |
| 47 | if '__pycache__' in assistant_dir: |
| 48 | continue |
| 49 | assistant_config_path = os.path.join(base_path, assistant_dir, "assistant.json") |
| 50 | if os.path.exists(assistant_config_path): |
| 51 | try: |
| 52 | with open(assistant_config_path, "r") as file: |
| 53 | assistant_config = json.load(file)[0] |
| 54 | assistant_tools_names = assistant_config.get('tools', []) |
| 55 | assistant_name = assistant_config.get('name', assistant_dir) |
| 56 | assistant_tools = [tool for tool in self.tool_functions if tool.function.name in assistant_tools_names] |
| 57 | |
| 58 | log_flag = assistant_config.pop('log_flag', False) |
| 59 | sub_assistants = assistant_config.get('assistants', None) |
| 60 | planner = assistant_config.get('planner', 'sequential') #default is sequential |
| 61 | print(f"Assistant '{assistant_name}' created.\n") |
| 62 | asst_object = Assistant(name=assistant_name, log_flag=log_flag, instance=None, tools=assistant_tools, sub_assistants=sub_assistants, planner=planner) |
| 63 | asst_object.initialize_history() |
| 64 | self.assistants.append(asst_object) |
| 65 | except (IOError, json.JSONDecodeError) as e: |
| 66 | print(f"Error loading assistant configuration from {assistant_config_path}: {e}") |
| 67 | |
| 68 | |
| 69 | def initialize_and_display_assistants(self): |
| 70 | """ |
| 71 | Loads all assistants and displays their information. |
| 72 | """ |
| 73 | self.load_all_assistants() |
| 74 | self.initialize_global_history() |
| 75 | |
| 76 | for asst in self.assistants: |
| 77 | print(f'\n{Colors.HEADER}Initializing assistant:{Colors.ENDC}') |
| 78 | print(f'{Colors.OKBLUE}Assistant name:{Colors.ENDC} {Colors.BOLD}{asst.name}{Colors.ENDC}') |
| 79 | if asst.tools: |
| 80 | print(f'{Colors.OKGREEN}Tools:{Colors.ENDC} {[tool.function.name for tool in asst.tools]} \n') |
| 81 | else: |
| 82 | print(f"{Colors.OKGREEN}Tools:{Colors.ENDC} No tools \n") |
| 83 | |
| 84 | |
| 85 | def get_assistant(self, assistant_name): |
| 86 | |
| 87 | for assistant in self.assistants: |
| 88 | if assistant.name == assistant_name: |
| 89 | return assistant |
| 90 | print('No assistant found') |
| 91 | return None |
| 92 | |
| 93 | def triage_request(self, assistant, message): |
| 94 | """ |
| 95 | Analyze the user message and delegate it to the appropriate assistant. |
| 96 | """ |
| 97 | assistant_name = None |
| 98 | |
| 99 | # Determine the appropriate assistant for the message |
| 100 | if assistant.sub_assistants is not None: |
| 101 | assistant_name = self.determine_appropriate_assistant(assistant, message) |
| 102 | if not assistant_name: |
| 103 | print('No appropriate assistant determined') |
| 104 | return None |
| 105 | |
| 106 | assistant_new = self.get_assistant(assistant_name) |
| 107 | if not assistant_new: |
| 108 | print(f'No assistant found with name: {assistant_name}') |
| 109 | return None |
| 110 | |
| 111 | assistant.pass_context(assistant_new) |
| 112 | # Pass along context: if the assistant is a sub-assistant, pass along the context of the parent assistant |
| 113 | else: |
| 114 | assistant_new = assistant |
| 115 | |
| 116 | |
| 117 | # If it's a new assistant, so a sub assistant |
| 118 | if assistant_name and assistant_name != assistant.name: |
| 119 | print( |
| 120 | f"{Colors.OKGREEN}Selecting sub-assistant:{Colors.ENDC} {Colors.BOLD}{assistant_new.name}{Colors.ENDC}" |
| 121 | ) |
| 122 | assistant.add_assistant_message(f"Selecting sub-assistant: {assistant_new.name}") |
| 123 | else: |
| 124 | print( |
| 125 | f"{Colors.OKGREEN}Assistant:{Colors.ENDC} {Colors.BOLD}{assistant_new.name}{Colors.ENDC}" |
| 126 | ) |
| 127 | return assistant_new |
| 128 | |
| 129 | |
| 130 | def determine_appropriate_assistant(self, assistant, message): |
| 131 | triage_message = [{"role": "system", "content": TRIAGE_SYSTEM_PROMPT}] |
| 132 | triage_message.append( |
| 133 | { |
| 134 | "role": "user", |
| 135 | "content": TRIAGE_MESSAGE_PROMPT.format( |
| 136 | message, |
| 137 | [(asst.name, asst.tools) for asst in [assistant] + [asst for asst in self.assistants if asst.name in assistant.sub_assistants]] ), |
| 138 | } |
| 139 | ) |
| 140 | response = get_completion(self.client, triage_message) |
| 141 | return response.content |
| 142 | |
| 143 | def initiate_run(self, task, assistant,test_mode): |
| 144 | """ |
| 145 | Run the request with the selected assistant and monitor its status. |
| 146 | """ |
| 147 | run = Run(assistant, task.description, self.client) |
| 148 | |
| 149 | #Update assistant with current task and run |
| 150 | assistant.current_task_id = task.id |
| 151 | assistant.runs.append(run) |
| 152 | |
| 153 | |
| 154 | #Get planner |
| 155 | planner = assistant.planner |
| 156 | plan = run.initiate(planner) |
| 157 | plan_log = {'step': [], 'step_output': []} |
| 158 | if not isinstance(plan, list): |
| 159 | plan_log['step'].append('response') |
| 160 | plan_log['step'].append(plan) |
| 161 | assistant.add_assistant_message(f"Response to user: {plan}") |
| 162 | print(f"{Colors.HEADER}Response:{Colors.ENDC} {plan}") |
| 163 | |
| 164 | #add global context |
| 165 | self.store_context_globally(assistant) |
| 166 | return plan_log, plan_log |
| 167 | |
| 168 | original_plan = plan.copy() |
| 169 | iterations = 0 |
| 170 | |
| 171 | while plan and iterations< max_iterations: |
| 172 | if isinstance(plan,list): |
| 173 | step = plan.pop(0) |
| 174 | else: |
| 175 | return "Error generating plan", "Error generating plan" |
| 176 | assistant.add_tool_message(step) |
| 177 | human_input_flag = next((tool.human_input for tool in assistant.tools if tool.function.name == step['tool']), False) |
| 178 | if step['tool']: |
| 179 | print(f"{Colors.HEADER}Running Tool:{Colors.ENDC} {step['tool']}") |
| 180 | if human_input_flag: |
| 181 | print(f"\n{Colors.HEADER}Tool {step['tool']} requires human input:{Colors.HEADER}") |
| 182 | print(f"{Colors.GREY}Tool arguments:{Colors.ENDC} {step['args']}\n") |
| 183 | |
| 184 | user_confirmation = input(f"Type 'yes' to execute tool, anything else to skip: ") |
| 185 | if user_confirmation.lower() != 'yes': |
| 186 | assistant.add_assistant_message(f"Tool {step['tool']} execution skipped by user.") |
| 187 | print(f"{Colors.GREY}Skipping tool execution.{Colors.ENDC}") |
| 188 | plan_log['step'].append('tool_skipped') |
| 189 | plan_log['step_output'].append(f'Tool {step["tool"]} execution skipped by user! Task not completed.') |
| 190 | continue |
| 191 | assistant.add_assistant_message(f"Tool {step['tool']} execution approved by user.") |
| 192 | tool_output = self.handle_tool_call(assistant, step, test_mode) |
| 193 | plan_log['step'].append(step) |
| 194 | plan_log['step_output'].append(tool_output) |
| 195 | |
| 196 | if task.iterate and not is_dict_empty(plan_log) and plan: |
| 197 | iterations += 1 |
| 198 | new_task = ITERATE_PROMPT.format(task.description, original_plan, plan_log) |
| 199 | plan = run.generate_plan(new_task) |
| 200 | # Store the output for the next iteration |
| 201 | |
| 202 | self.store_context_globally(assistant) |
| 203 | |
| 204 | return original_plan, plan_log |
| 205 | |
| 206 | def handle_tool_call(self,assistant, tool_call, test_mode=False): |
| 207 | tool_name = tool_call['tool'] |
| 208 | tool_dir = os.path.join(os.getcwd(), 'configs/tools', tool_name) |
| 209 | handler_path = os.path.join(tool_dir, 'handler.py') |
| 210 | |
| 211 | # Dynamically import the handler function from the handler.py file |
| 212 | if os.path.isfile(handler_path): |
| 213 | spec = importlib.util.spec_from_file_location(f"{tool_name}_handler", handler_path) |
| 214 | tool_module = importlib.util.module_from_spec(spec) |
| 215 | spec.loader.exec_module(tool_module) |
| 216 | tool_handler = getattr(tool_module, tool_name) |
| 217 | # Call the handler function with arguments |
| 218 | try: |
| 219 | tool_response = tool_handler(**tool_call['args']) |
| 220 | except: |
| 221 | return 'Failed to execute tool' |
| 222 | |
| 223 | try: |
| 224 | # assistant.add_assistant_message(tool_response.content) |
| 225 | return tool_response.content |
| 226 | except: |
| 227 | # assistant.add_assistant_message(tool_response) |
| 228 | return tool_response |
| 229 | |
| 230 | print('No tool file found') |
| 231 | return 'No tool file found' |
| 232 | |
| 233 | def run_task(self, task, test_mode): |
| 234 | """ |
| 235 | Processes a given task. |
| 236 | """ |
| 237 | |
| 238 | if not test_mode: |
| 239 | print( |
| 240 | f"{Colors.OKCYAN}User Query:{Colors.ENDC} {Colors.BOLD}{task.description}{Colors.ENDC}" |
| 241 | ) |
| 242 | else: |
| 243 | print( |
| 244 | f"{Colors.OKCYAN}Test:{Colors.ENDC} {Colors.BOLD}{task.description}{Colors.ENDC}" |
| 245 | ) |
| 246 | #Maintain assistant if persist flag is true |
| 247 | if self.persist and self.last_assistant is not None: |
| 248 | assistant = self.last_assistant |
| 249 | else: |
| 250 | assistant = self.get_assistant(task.assistant) |
| 251 | assistant.current_task_id = task.id |
| 252 | assistant.add_user_message(task.description) |
| 253 | |
| 254 | #triage based on current assistant |
| 255 | selected_assistant = self.triage_request(assistant, task.description) |
| 256 | if test_mode: |
| 257 | task.assistant = selected_assistant.name if selected_assistant else "None" |
| 258 | if not selected_assistant: |
| 259 | if not test_mode: |
| 260 | print(f"No suitable assistant found for the task: {task.description}") |
| 261 | return None |
| 262 | |
| 263 | # Run the request with the determined or specified assistant |
| 264 | original_plan, plan_log = self.initiate_run(task, selected_assistant,test_mode) |
| 265 | |
| 266 | #set last assistant |
| 267 | self.last_assistant = selected_assistant |
| 268 | |
| 269 | #if evaluating the task |
| 270 | if task.evaluate: |
| 271 | output = assistant.evaluate(self.client,task, plan_log) |
| 272 | if output is not None: |
| 273 | success_flag = False |
| 274 | if not isinstance(output[0],bool): |
| 275 | success_flag = False if output[0].lower() == 'false' else bool(output[0]) |
| 276 | message = output[1] |
| 277 | if success_flag: |
| 278 | print(f'\n\033[93m{message}\033[0m') |
| 279 | else: |
| 280 | print(f"{Colors.RED}{message}{Colors.ENDC}") |
| 281 | #log |
| 282 | assistant.add_assistant_message(message) |
| 283 | else: |
| 284 | message = "Error evaluating output" |
| 285 | print(f"{Colors.RED}{message}{Colors.ENDC}") |
| 286 | assistant.add_assistant_message(message) |
| 287 | |
| 288 | return original_plan, plan_log |
| 289 | |
| 290 | |
| 291 | def run_tests(self): |
| 292 | total_groundtruth = 0 |
| 293 | total_planning = 0 |
| 294 | total_assistant = 0 |
| 295 | groundtruth_pass = 0 |
| 296 | planning_pass = 0 |
| 297 | assistant_pass = 0 |
| 298 | for task in self.tasks: |
| 299 | original_plan, plan_log = self.run_task(task, test_mode=True) |
| 300 | |
| 301 | if task.groundtruth: |
| 302 | total_groundtruth += 1 |
| 303 | # Assuming get_completion returns a response object with a content attribute |
| 304 | response = get_completion(self.client, [{"role": "user", "content": EVAL_GROUNDTRUTH_PROMPT.format(original_plan, task.groundtruth)}]) |
| 305 | if response.content.lower() == 'true': |
| 306 | groundtruth_pass += 1 |
| 307 | print(f"{Colors.OKGREEN}✔ Groundtruth test passed for: {Colors.ENDC}{task.description}{Colors.OKBLUE}. Expected: {Colors.ENDC}{task.groundtruth}{Colors.OKBLUE}, Got: {Colors.ENDC}{original_plan}{Colors.ENDC}") |
| 308 | else: |
| 309 | print(f"{Colors.RED}✘ Test failed for: {Colors.ENDC}{task.description}{Colors.OKBLUE}. Expected: {Colors.ENDC}{task.groundtruth}{Colors.OKBLUE}, Got: {Colors.ENDC}{original_plan}{Colors.ENDC}") |
| 310 | |
| 311 | total_assistant += 1 |
| 312 | if task.assistant == task.expected_assistant: |
| 313 | assistant_pass += 1 |
| 314 | print(f"{Colors.OKGREEN}✔ Correct assistant assigned. {Colors.ENDC}{Colors.OKBLUE} Expected: {Colors.ENDC}{task.expected_assistant}{Colors.OKBLUE}, Got: {Colors.ENDC}{task.assistant}{Colors.ENDC}\n") |
| 315 | else: |
| 316 | print(f"{Colors.RED}✘ Incorrect assistant assigned. {Colors.ENDC}{Colors.OKBLUE} Expected: {Colors.ENDC}{task.expected_assistant}{Colors.OKBLUE}, Got: {Colors.ENDC}{task.assistant}{Colors.ENDC}\n") |
| 317 | |
| 318 | |
| 319 | elif task.expected_plan: |
| 320 | total_planning += 1 |
| 321 | # Assuming get_completion returns a response object with a content attribute |
| 322 | response = get_completion(self.client, [{"role": "user", "content": EVAL_PLANNING_PROMPT.format(original_plan, task.expected_plan)}]) |
| 323 | |
| 324 | if response.content.lower() == 'true': |
| 325 | planning_pass += 1 |
| 326 | print(f"{Colors.OKGREEN}✔ Planning test passed for: {Colors.ENDC}{task.description}{Colors.OKBLUE}. Expected: {Colors.ENDC}{task.expected_plan}{Colors.OKBLUE}, Got: {Colors.ENDC}{original_plan}{Colors.ENDC}") |
| 327 | else: |
| 328 | print(f"{Colors.RED}✘ Test failed for: {Colors.ENDC}{task.description}{Colors.OKBLUE}. Expected: {Colors.ENDC}{task.expected_plan}{Colors.OKBLUE}, Got: {Colors.ENDC}{original_plan}{Colors.ENDC}") |
| 329 | |
| 330 | total_assistant += 1 |
| 331 | if task.assistant == task.expected_assistant: |
| 332 | assistant_pass += 1 |
| 333 | print(f"{Colors.OKGREEN}✔ Correct assistant assigned. {Colors.ENDC}{Colors.OKBLUE}Expected: {Colors.ENDC}{task.expected_assistant}{Colors.OKBLUE}, Got: {Colors.ENDC}{task.assistant}{Colors.ENDC}\n") |
| 334 | else: |
| 335 | print(f"{Colors.RED}✘ Incorrect assistant assigned for. {Colors.ENDC}{Colors.OKBLUE} Expected: {Colors.ENDC}{task.expected_assistant}{Colors.OKBLUE}, Got: {Colors.ENDC}{task.assistant}{Colors.ENDC}\n") |
| 336 | |
| 337 | else: |
| 338 | total_assistant += 1 |
| 339 | if task.assistant == task.expected_assistant: |
| 340 | assistant_pass += 1 |
| 341 | print(f"{Colors.OKGREEN}✔ Correct assistant assigned for: {Colors.ENDC}{task.description}{Colors.OKBLUE}. Expected: {Colors.ENDC}{task.expected_assistant}{Colors.OKBLUE}, Got: {Colors.ENDC}{task.assistant}{Colors.ENDC}\n") |
| 342 | else: |
| 343 | print(f"{Colors.RED}✘ Incorrect assistant assigned for: {Colors.ENDC}{task.description}{Colors.OKBLUE}. Expected: {Colors.ENDC}{task.expected_assistant}{Colors.OKBLUE}, Got: {Colors.ENDC}{task.assistant}{Colors.ENDC}\n") |
| 344 | |
| 345 | if total_groundtruth > 0: |
| 346 | print(f"\n{Colors.OKGREEN}Passed {groundtruth_pass} groundtruth tests out of {total_groundtruth} tests. Success rate: {groundtruth_pass / total_groundtruth * 100}%{Colors.ENDC}\n") |
| 347 | if total_planning > 0: |
| 348 | print(f"{Colors.OKGREEN}Passed {planning_pass} planning tests out of {total_planning} tests. Success rate: {planning_pass / total_planning * 100}%{Colors.ENDC}\n") |
| 349 | if total_assistant > 0: |
| 350 | print(f"{Colors.OKGREEN}Passed {assistant_pass} assistant tests out of {total_assistant} tests. Success rate: {assistant_pass / total_assistant * 100}%{Colors.ENDC}\n") |
| 351 | print("Completed testing the swarm\n\n") |
| 352 | |
| 353 | def deploy(self, client, test_mode=False, test_file_path=None): |
| 354 | """ |
| 355 | Processes all tasks in the order they are listed in self.tasks. |
| 356 | """ |
| 357 | self.client = client |
| 358 | if test_mode and test_file_path: |
| 359 | print("\nTesting the swarm\n\n") |
| 360 | self.load_test_tasks(test_file_path) |
| 361 | self.initialize_and_display_assistants() |
| 362 | self.run_tests() |
| 363 | for assistant in self.assistants: |
| 364 | if assistant.name == 'user_interface': |
| 365 | assistant.save_conversation(test=True) |
| 366 | else: |
| 367 | print("\n🐝🐝🐝 Deploying the swarm 🐝🐝🐝\n\n") |
| 368 | self.initialize_and_display_assistants() |
| 369 | print("\n" + "-" * 100 + "\n") |
| 370 | for task in self.tasks: |
| 371 | print('Task',task.id) |
| 372 | print(f"{Colors.BOLD}Running task{Colors.ENDC}") |
| 373 | self.run_task(task, test_mode) |
| 374 | print("\n" + "-" * 100 + "\n") |
| 375 | #save the session |
| 376 | for assistant in self.assistants: |
| 377 | if assistant.name == 'user_interface': |
| 378 | assistant.save_conversation() |
| 379 | #assistant.print_conversation() |
| 380 | |
| 381 | def load_test_tasks(self, test_file_paths): |
| 382 | self.tasks = [] # Clear any existing tasks |
| 383 | for f in test_file_paths: |
| 384 | with open(f, 'r') as file: |
| 385 | for line in file: |
| 386 | test_case = json.loads(line) |
| 387 | task = EvaluationTask(description=test_case['text'], |
| 388 | assistant=test_case.get('assistant', 'user_interface'), |
| 389 | groundtruth=test_case.get('groundtruth',None), |
| 390 | expected_plan=test_case.get('expected_plan',None), |
| 391 | expected_assistant=test_case['expected_assistant'], |
| 392 | iterate=test_case.get('iterate', False), # Add this |
| 393 | evaluate=test_case.get('evaluate', False), |
| 394 | eval_function=test_case.get('eval_function', 'default') |
| 395 | ) |
| 396 | self.tasks.append(task) |
| 397 | |
| 398 | def store_context_globally(self, assistant): |
| 399 | self.global_context['history'].append({assistant.name:assistant.context['history']}) |
| 400 | |
| 401 | def initialize_global_history(self): |
| 402 | self.global_context['history'] = [] |