harry85/multi-agent-ai-autogen-coding
9
1import base64, datetime, json, os2 3from autogen import ConversableAgent, AssistantAgent4from autogen.coding import LocalCommandLineCodeExecutor5 6def read_file(file_path: str) -> str:7 with open(file_path, "r", encoding="utf-8") as file:8 return file.read()9 10def read_image_file(image_file_path: str) -> str:11 with open(image_file_path, "rb") as image_file:12 image_data = image_file.read()13 return base64.b64encode(image_data).decode("utf-8")14 15def generate_markdown_image(image_data: str) -> str:16 return f""17 18def format_as_markdown(code: str) -> str:19 markdown_code = '```\n'20 markdown_code += code21 markdown_code += '\n```'22 return markdown_code23 24def get_latest_file(directory, file_extension):25 latest_file = None26 latest_date = datetime.datetime.min27 28 for file in os.listdir(directory):29 if file:30 _, file_ext = os.path.splitext(file)31 32 if file_ext == file_extension:33 file_path = os.path.join(directory, file)34 file_date = datetime.datetime.fromtimestamp(os.path.getmtime(file_path))35 36 if file_date > latest_date:37 latest_date = file_date38 latest_file = file39 40 return latest_file41 42def run_multi_agent(llm, task):43 llm_config = {"model": llm}44 45 executor = LocalCommandLineCodeExecutor(46 timeout=60,47 work_dir="coding",48 )49 50 code_executor_agent = ConversableAgent(51 name="code_executor_agent",52 llm_config=False,53 code_execution_config={"executor": executor},54 human_input_mode="NEVER",55 default_auto_reply="TERMINATE",56 )57 58 code_writer_agent = AssistantAgent(59 name="code_writer_agent",60 llm_config=llm_config,61 code_execution_config=False,62 human_input_mode="NEVER",63 )64 65 chat_result = code_executor_agent.initiate_chat(66 code_writer_agent,67 message=task,68 max_turns=1069 )70 71 chat = ""72 first_message = True73 74 for message in chat_result.chat_history:75 if not first_message:76 chat += f"**{message['role'].replace('assistant', 'Code Executor').replace('user', 'Code Writer')}**\n{message['content']}\n\n"77 first_message = False78 79 file_name_png = get_latest_file("coding", ".png")80 81 image_data = read_image_file(f"/home/user/app/coding/{file_name_png}")82 markdown_code_png = generate_markdown_image(image_data)83 84 result = f"{markdown_code_png}\n\n{chat}"85 86 print("===")87 print(result)88 print("===")89 90 return result