| 1 | import json |
| 2 | import os |
| 3 | from src.utils import get_completion |
| 4 | from configs.general import Colors |
| 5 | from configs.prompts import TRIAGE_SYSTEM_PROMPT, TRIAGE_MESSAGE_PROMPT, EVALUATE_TASK_PROMPT |
| 6 | import time |
| 7 | from src.swarm.assistants import Assistant |
| 8 | from src.tasks.task import EvaluationTask |
| 9 | from openai import OpenAI |
| 10 | import importlib |
| 11 | |
| 12 | |
| 13 | class AssistantsEngine: |
| 14 | def __init__(self,client,tasks): |
| 15 | self.client = client |
| 16 | self.assistants = [] |
| 17 | self.tasks = tasks |
| 18 | self.thread = self.initialize_thread() |
| 19 | |
| 20 | |
| 21 | def initialize_thread(self): |
| 22 | # Create a Thread for the user's conversation |
| 23 | thread = self.client.beta.threads.create() |
| 24 | return thread |
| 25 | |
| 26 | def reset_thread(self): |
| 27 | # Create a Thread for the user's conversation |
| 28 | self.thread = self.client.beta.threads.create() |
| 29 | |
| 30 | def load_all_assistants(self): |
| 31 | base_path = 'assistants' |
| 32 | tools_base_path = 'tools' |
| 33 | |
| 34 | # Load individual tool definitions from the tools directory |
| 35 | tool_defs = {} |
| 36 | for tool_dir in os.listdir(tools_base_path): |
| 37 | if '__pycache__' in tool_dir: |
| 38 | continue |
| 39 | tool_dir_path = os.path.join(tools_base_path, tool_dir) |
| 40 | if os.path.isdir(tool_dir_path): |
| 41 | tool_json_path = os.path.join(tool_dir_path, 'tool.json') |
| 42 | if os.path.isfile(tool_json_path): |
| 43 | with open(tool_json_path, 'r') as file: |
| 44 | # Assuming the JSON file contains a list of tool definitions |
| 45 | tool_def = json.load(file) |
| 46 | tool_defs[tool_def['function']['name']] = tool_def['function'] |
| 47 | # Load assistants and their tools |
| 48 | for assistant_dir in os.listdir(base_path): |
| 49 | if '__pycache__' in assistant_dir: |
| 50 | continue |
| 51 | assistant_config_path = os.path.join(base_path, assistant_dir, "assistant.json") |
| 52 | if os.path.exists(assistant_config_path): |
| 53 | with open(assistant_config_path, "r") as file: |
| 54 | assistant_config = json.load(file)[0] |
| 55 | |
| 56 | assistant_name = assistant_config.get('name', assistant_dir) |
| 57 | log_flag = assistant_config.pop('log_flag', False) |
| 58 | |
| 59 | # List of tool names from the assistant's config |
| 60 | assistant_tools_names = assistant_config.get('tools', []) |
| 61 | |
| 62 | # Build the list of tool definitions for this assistant |
| 63 | assistant_tools = [tool_defs[name] for name in assistant_tools_names if name in tool_defs] |
| 64 | |
| 65 | # Create or update the assistant instance |
| 66 | existing_assistants = self.client.beta.assistants.list() |
| 67 | loaded_assistant = next((a for a in existing_assistants if a.name == assistant_name), None) |
| 68 | |
| 69 | if loaded_assistant: |
| 70 | assistant_tools = [{'type': 'function', 'function': tool_defs[name]} for name in assistant_tools_names if name in tool_defs] |
| 71 | assistant_config['tools'] = assistant_tools |
| 72 | assistant_config['name']=assistant_name |
| 73 | |
| 74 | loaded_assistant = self.client.beta.assistants.create(**assistant_config) |
| 75 | print(f"Assistant '{assistant_name}' created.\n") |
| 76 | |
| 77 | asst_object = Assistant(name=assistant_name, log_flag=log_flag, instance=loaded_assistant, tools=assistant_tools) |
| 78 | self.assistants.append(asst_object) |
| 79 | |
| 80 | |
| 81 | def initialize_and_display_assistants(self): |
| 82 | """ |
| 83 | Loads all assistants and displays their information. |
| 84 | """ |
| 85 | self.load_all_assistants() |
| 86 | |
| 87 | for asst in self.assistants: |
| 88 | print(f'\n{Colors.HEADER}Initializing assistant:{Colors.ENDC}') |
| 89 | print(f'{Colors.OKBLUE}Assistant name:{Colors.ENDC} {Colors.BOLD}{asst.name}{Colors.ENDC}') |
| 90 | if asst.instance and hasattr(asst.instance, 'tools'): |
| 91 | print(f'{Colors.OKGREEN}Tools:{Colors.ENDC} {asst.instance.tools} \n') |
| 92 | else: |
| 93 | print(f"{Colors.OKGREEN}Tools:{Colors.ENDC} Not available \n") |
| 94 | |
| 95 | |
| 96 | def get_assistant(self, assistant_name): |
| 97 | |
| 98 | for assistant in self.assistants: |
| 99 | if assistant.name == assistant_name: |
| 100 | return assistant |
| 101 | print('No assistant found') |
| 102 | return None |
| 103 | |
| 104 | def triage_request(self, message, test_mode): |
| 105 | """ |
| 106 | Analyze the user message and delegate it to the appropriate assistant. |
| 107 | """ |
| 108 | #determine the appropriate assistant for the message |
| 109 | assistant_name = self.determine_appropriate_assistant(message) |
| 110 | assistant = self.get_assistant(assistant_name) |
| 111 | |
| 112 | if assistant: |
| 113 | print( |
| 114 | f"{Colors.OKGREEN}\nSelected Assistant:{Colors.ENDC} {Colors.BOLD}{assistant.name}{Colors.ENDC}" |
| 115 | ) |
| 116 | assistant.add_assistant_message('Selected Assistant: '+assistant.name) |
| 117 | return assistant |
| 118 | #else |
| 119 | if not test_mode: |
| 120 | print('No assistant found') |
| 121 | return None |
| 122 | |
| 123 | |
| 124 | def determine_appropriate_assistant(self, message): |
| 125 | triage_message = [{"role": "system", "content": TRIAGE_SYSTEM_PROMPT}] |
| 126 | triage_message.append( |
| 127 | { |
| 128 | "role": "user", |
| 129 | "content": TRIAGE_MESSAGE_PROMPT.format(message, [asst.instance for asst in self.assistants]), |
| 130 | } |
| 131 | ) |
| 132 | response = get_completion(self.client, triage_message) |
| 133 | return response.content |
| 134 | |
| 135 | |
| 136 | def run_request(self, request, assistant,test_mode): |
| 137 | """ |
| 138 | Run the request with the selected assistant and monitor its status. |
| 139 | """ |
| 140 | # Add message to thread |
| 141 | self.client.beta.threads.messages.create( |
| 142 | thread_id=self.thread.id, |
| 143 | role="user", |
| 144 | content=request |
| 145 | ) |
| 146 | |
| 147 | # Initialize run |
| 148 | run = self.client.beta.threads.runs.create( |
| 149 | thread_id=self.thread.id, |
| 150 | assistant_id=assistant.instance.id |
| 151 | ) |
| 152 | |
| 153 | # Monitor the run status in a loop |
| 154 | while True: |
| 155 | run = self.client.beta.threads.runs.retrieve( |
| 156 | thread_id=self.thread.id, |
| 157 | run_id=run.id |
| 158 | ) |
| 159 | |
| 160 | if run.status in ["queued", "in_progress"]: |
| 161 | time.sleep(2) # Wait before checking the status again |
| 162 | if not test_mode: |
| 163 | print('waiting for run') |
| 164 | elif run.status == "requires_action": |
| 165 | tool_call = run.required_action.submit_tool_outputs.tool_calls[0] |
| 166 | self.handle_tool_call(tool_call, run) |
| 167 | # Re-submitting the tool outputs and continue the loop |
| 168 | |
| 169 | elif run.status in ["completed","expired", "cancelling", "cancelled", "failed"]: |
| 170 | if not test_mode: |
| 171 | print(f'\nrun {run.status}') |
| 172 | break |
| 173 | |
| 174 | if assistant.log_flag: |
| 175 | self.store_messages() |
| 176 | # Retrieve and return the response (only if completed) |
| 177 | messages = self.client.beta.threads.messages.list(thread_id=self.thread.id) |
| 178 | assistant_response = next((msg for msg in messages.data if msg.role == 'assistant' and msg.content), None) |
| 179 | |
| 180 | |
| 181 | if assistant_response: |
| 182 | assistant_response_text = assistant_response.content[0].text.value |
| 183 | if not test_mode: |
| 184 | print(f"{Colors.RED}Response:{Colors.ENDC} {assistant_response_text}", "\n") |
| 185 | return assistant_response_text |
| 186 | return "No response from the assistant." |
| 187 | |
| 188 | |
| 189 | def handle_tool_call(self, tool_call, run): |
| 190 | tool_name = tool_call.function.name |
| 191 | tool_dir = os.path.join(os.getcwd(), 'tools', tool_name) |
| 192 | handler_path = os.path.join(tool_dir, 'handler.py') |
| 193 | |
| 194 | # Dynamically import the handler function from the handler.py file |
| 195 | if os.path.isfile(handler_path): |
| 196 | spec = importlib.util.spec_from_file_location(f"{tool_name}_handler", handler_path) |
| 197 | tool_module = importlib.util.module_from_spec(spec) |
| 198 | spec.loader.exec_module(tool_module) |
| 199 | tool_handler = getattr(tool_module, tool_name+ '_assistants') |
| 200 | |
| 201 | # Prepare the arguments for the handler function |
| 202 | handler_args = {'tool_id': tool_call.id} |
| 203 | tool_args = json.loads(tool_call.function.arguments) |
| 204 | for arg_name, arg_value in tool_args.items(): |
| 205 | if arg_value is not None: |
| 206 | handler_args[arg_name] = arg_value |
| 207 | |
| 208 | # Call the handler function with arguments |
| 209 | print(f"{Colors.HEADER}Running Tool:{Colors.ENDC} {tool_name}") |
| 210 | print(handler_args) |
| 211 | tool_response = tool_handler(**handler_args) |
| 212 | |
| 213 | # Submit the tool response back to the thread |
| 214 | self.client.beta.threads.runs.submit_tool_outputs( |
| 215 | thread_id=self.thread.id, |
| 216 | run_id=run.id, |
| 217 | tool_outputs=[ |
| 218 | { |
| 219 | "tool_call_id": tool_call.id, |
| 220 | "output": json.dumps({"result": tool_response}), |
| 221 | } |
| 222 | ], |
| 223 | ) |
| 224 | else: |
| 225 | print(f"No handler found for tool {tool_name}") |
| 226 | |
| 227 | def store_messages(self, filename="threads/thread_data.json"): |
| 228 | |
| 229 | thread = self.client.beta.threads.messages.list(thread_id=self.thread.id) |
| 230 | # Extract the required fields from each message in the thread |
| 231 | messages = [] |
| 232 | for message in thread.data: |
| 233 | role = message.role |
| 234 | run_id = message.run_id |
| 235 | assistant_id = message.assistant_id |
| 236 | thread_id = message.thread_id |
| 237 | created_at = message.created_at |
| 238 | content_value = message.content[0].text.value |
| 239 | messages.append({ |
| 240 | 'role': role, |
| 241 | 'run_id': run_id, |
| 242 | 'assistant_id': assistant_id, |
| 243 | 'thread_id': thread_id, |
| 244 | 'created_at': created_at, |
| 245 | 'content': content_value |
| 246 | }) |
| 247 | try: |
| 248 | with open(filename, 'r') as file: |
| 249 | existing_threads = json.load(file) |
| 250 | |
| 251 | except: |
| 252 | existing_threads = [] |
| 253 | |
| 254 | |
| 255 | # Convert the OpenAI object to a serializable format (e.g., a dictionary) |
| 256 | # Append new threads |
| 257 | existing_threads.append(messages) |
| 258 | # Save back to the file |
| 259 | try: |
| 260 | with open(filename, 'w') as file: |
| 261 | json.dump(existing_threads, file, indent=4) |
| 262 | except Exception as e: |
| 263 | print(f"Error while saving to file: {e}") |
| 264 | |
| 265 | |
| 266 | def run_task(self, task,test_mode): |
| 267 | """ |
| 268 | Processes a given task. If the assistant is set to 'auto', it determines the appropriate |
| 269 | assistant using triage_request. Otherwise, it uses the specified assistant. |
| 270 | """ |
| 271 | if not test_mode: |
| 272 | print( |
| 273 | f"{Colors.OKCYAN}User Query:{Colors.ENDC} {Colors.BOLD}{task.description}{Colors.ENDC}" |
| 274 | ) |
| 275 | else: |
| 276 | print( |
| 277 | f"{Colors.OKCYAN}Test:{Colors.ENDC} {Colors.BOLD}{task.description}{Colors.ENDC}" |
| 278 | ) |
| 279 | |
| 280 | if task.assistant == 'auto': |
| 281 | # Triage the request to determine the appropriate assistant |
| 282 | assistant = self.triage_request(task.description,test_mode) |
| 283 | else: |
| 284 | # Fetch the specified assistant |
| 285 | assistant = self.get_assistant(task.assistant) |
| 286 | print( |
| 287 | f"{Colors.OKGREEN}\nSelected Assistant:{Colors.ENDC} {Colors.BOLD}{assistant.name}{Colors.ENDC}" |
| 288 | ) |
| 289 | |
| 290 | if test_mode: |
| 291 | task.assistant = assistant.name if assistant else "None" |
| 292 | if not assistant: |
| 293 | if not test_mode: |
| 294 | print(f"No suitable assistant found for the task: {task.description}") |
| 295 | return None |
| 296 | |
| 297 | # Run the request with the determined or specified assistant |
| 298 | self.reset_thread() |
| 299 | return self.run_request(task.description, assistant,test_mode) |
| 300 | |
| 301 | def deploy(self, client,test_mode=False,test_file_path=None): |
| 302 | """ |
| 303 | Processes all tasks in the order they are listed in self.tasks. |
| 304 | """ |
| 305 | #Initialize swarm first |
| 306 | self.client = client |
| 307 | if test_mode and test_file_path: |
| 308 | print("\nTesting the swarm\n\n") |
| 309 | self.load_test_tasks(test_file_path) |
| 310 | else: |
| 311 | print("\n๐๐๐ Deploying the swarm ๐๐๐\n\n") |
| 312 | |
| 313 | self.initialize_and_display_assistants() |
| 314 | total_tests = 0 |
| 315 | groundtruth_tests = 0 |
| 316 | assistant_tests = 0 |
| 317 | for task in self.tasks: |
| 318 | output = self.run_task(task,test_mode) |
| 319 | |
| 320 | if test_mode and hasattr(task, 'groundtruth'): |
| 321 | total_tests += 1 |
| 322 | |
| 323 | response = get_completion(self.client,[{"role":"user","content":EVALUATE_TASK_PROMPT.format(output,task.groundtruth)}]) |
| 324 | |
| 325 | if response.content=='True': |
| 326 | groundtruth_tests += 1 |
| 327 | print(f"{Colors.OKGREEN}โ Groundtruth test passed for: {Colors.ENDC}{task.description}{Colors.OKBLUE}. Expected: {Colors.ENDC}{task.groundtruth}{Colors.OKBLUE}, Got: {Colors.ENDC}{output}{Colors.ENDC}") |
| 328 | else: |
| 329 | print(f"{Colors.RED}โ Test failed for: {Colors.ENDC}{task.description}{Colors.OKBLUE}. Expected: {Colors.ENDC}{task.groundtruth}{Colors.OKBLUE}, Got: {Colors.ENDC}{output}{Colors.ENDC}") |
| 330 | |
| 331 | if task.assistant==task.expected_assistant: |
| 332 | 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") |
| 333 | assistant_tests += 1 |
| 334 | else: |
| 335 | 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") |
| 336 | |
| 337 | if test_mode: |
| 338 | print(f"\n{Colors.OKGREEN}Passed {groundtruth_tests} groundtruth tests out of {total_tests} tests. Success rate: {groundtruth_tests/total_tests*100}%{Colors.ENDC}\n") |
| 339 | print(f"{Colors.OKGREEN}Passed {assistant_tests} assistant tests out of {total_tests} tests. Success rate: {groundtruth_tests/total_tests*100}%{Colors.ENDC}\n") |
| 340 | print("Completed testing the swarm\n\n") |
| 341 | else: |
| 342 | print("๐ฏ๐๐ฏ Swarm operations complete ๐ฏ๐๐ฏ\n\n") |
| 343 | |
| 344 | |
| 345 | |
| 346 | def load_test_tasks(self, test_file_path): |
| 347 | self.tasks = [] # Clear any existing tasks |
| 348 | with open(test_file_path, 'r') as file: |
| 349 | for line in file: |
| 350 | test_case = json.loads(line) |
| 351 | task = EvaluationTask(description=test_case['text'], |
| 352 | assistant=test_case.get('assistant', 'auto'), |
| 353 | groundtruth=test_case['groundtruth'], |
| 354 | expected_assistant=test_case['expected_assistant']) |
| 355 | self.tasks.append(task) |