🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
Merge remote-tracking branch 'origin/dev' into dev_tool_selection
lidanyang3c8ef3e8480e
diff --cc metagpt/prompts/ml_engineer.pyindex 05d8db8e9,6420c3b7d..33eb9c40c--- a/metagpt/prompts/ml_engineer.py+++ b/metagpt/prompts/ml_engineer.py@@@ -299,6 -197,19 +299,17 @@@ ML_SPECIFIC_PROMPT =}ML_MODULE_MAP = {- "data_preprocess": "metagpt.tools.functions.libs.machine_learning.data_preprocess",- "feature_engineering": "metagpt.tools.functions.libs.machine_learning.feature_engineering",- "classification_model": "metagpt.tools.functions.libs.machine_learning.ml_model",- "regression_model": "metagpt.tools.functions.libs.machine_learning.ml_model",+ "data_preprocess": "metagpt.tools.functions.libs.data_preprocess",+ "feature_engineering": "metagpt.tools.functions.libs.feature_engineering",}++ STRUCTURAL_CONTEXT = """+ ## User Requirement+ {user_requirement}+ ## Data Description+ {data_desc}+ ## Current Plan+ {tasks}+ ## Current Task+ {current_task}+ """diff --cc metagpt/roles/ml_engineer.pyindex 6a2a9e2b0,e7fe38ff4..26dfdbc67--- a/metagpt/roles/ml_engineer.py+++ b/metagpt/roles/ml_engineer.py@@@ -1,111 -1,58 +1,85 @@@+ from typing import Listimport json- import refrom datetime import datetime- from typing import Listimport fire- import pandas as pd+ from metagpt.roles import Role+ from metagpt.schema import Message, Plan+ from metagpt.memory import Memory+ from metagpt.logs import logger+from metagpt.actions import Action- from metagpt.actions.execute_code import ExecutePyCode+ from metagpt.actions.write_plan import WritePlan, update_plan_from_rsp, precheck_update_plan_from_rspfrom metagpt.actions.write_analysis_code import WriteCodeByGenerate, WriteCodeWithTools+ from metagpt.actions.ml_da_action import AskReview, SummarizeAnalysis, Reflect, ReviewConst+ from metagpt.actions.execute_code import ExecutePyCode+ from metagpt.roles.kaggle_manager import DownloadData, SubmitResult+ from metagpt.prompts.ml_engineer import STRUCTURAL_CONTEXTfrom metagpt.actions.write_code_steps import WriteCodeSteps+from metagpt.actions.write_plan import WritePlan+from metagpt.const import DATA_PATH, PROJECT_ROOT+from metagpt.logs import logger+from metagpt.prompts.ml_engineer import (+ GEN_DATA_DESC_PROMPT,+ UPDATE_DATA_COLUMNS,+ PRINT_DATA_COLUMNS+)+from metagpt.roles import Role+from metagpt.schema import Message, Plan+from metagpt.utils.common import CodeParser, remove_comments, create_func_config+from metagpt.actions.debug_code import DebugCode-- STRUCTURAL_CONTEXT = """- ## User Requirement- {user_requirement}- ## Dataset Description- {data_desc}- ## Current Plan- {tasks}- ## Current Task- {current_task}- """--- def truncate(result: str, keep_len: int = 1000) -> str:- desc = "Truncated to show only the last 1000 characters\n"- if result.startswith(desc):- result = result[-len(desc):]-- if len(result) > keep_len:- result = result[-keep_len:]-- if not result.startswith(desc):- return desc + result- return desc--- def remove_escape_and_color_codes(input_str):- # 使用正则表达式去除转义字符和颜色代码- pattern = re.compile(r'\x1b\[[0-9;]*[mK]')- result = pattern.sub('', input_str)- return result--- class AskReview(Action):- async def run(self, context: List[Message], plan: Plan = None):- logger.info("Current overall plan:")- logger.info(- "\n".join([f"{task.task_id}: {task.instruction}, is_finished: {task.is_finished}" for task in plan.tasks])- )-- logger.info("most recent context:")- latest_action = context[-1].cause_by.__name__ if context[-1].cause_by else ""- prompt = f"\nPlease review output from {latest_action}:\n" \- "If you want to change a task in the plan, say 'change task task_id, ... (things to change)'\n" \- "If you confirm the output and wish to continue with the current process, type CONFIRM\n" \- "If you want to terminate the process, type exit:\n"- rsp = input(prompt)-- if rsp.lower() in ("exit"):- exit()-- confirmed = rsp.lower() in ("confirm", "yes", "y")-- return rsp, confirmed+ from metagpt.utils.save_code import save_code_file++class UpdateDataColumns(Action):+ async def run(self, plan: Plan = None) -> dict:+ finished_tasks = plan.get_finished_tasks()+ code_context = [remove_comments(task.code) for task in finished_tasks]+ code_context = "\n\n".join(code_context)+ prompt = UPDATE_DATA_COLUMNS.format(history_code=code_context)+ tool_config = create_func_config(PRINT_DATA_COLUMNS)+ rsp = await self.llm.aask_code(prompt, **tool_config)+ return rsp++class MLEngineer(Role):def __init__(- self, name="ABC", profile="MLEngineer", goal="", auto_run: bool = False,+ self, name="ABC", profile="MLEngineer", goal="", auto_run: bool = False):super().__init__(name=name, profile=profile, goal=goal)self._set_react_mode(react_mode="plan_and_act")+ self._watch([DownloadData, SubmitResult])+self.plan = Plan(goal=goal)- self.use_tools = True- self.use_code_steps = True+ self.use_tools = False+ self.use_code_steps = Falseself.execute_code = ExecutePyCode()self.auto_run = auto_run+ self.data_desc = {}-++ # memory for working on each task, discarded each time a task is done+ self.working_memory = Memory()+++async def _plan_and_act(self):++ ### Actions in a multi-agent multi-turn setting ###+ memories = self.get_memories()+ if memories:+ latest_event = memories[-1].cause_by+ if latest_event == DownloadData:+ self.plan.context = memories[-1].content+ elif latest_event == SubmitResult:+ # self reflect on previous plan outcomes and think about how to improve the plan, add to working memory+ await self._reflect()++ # get feedback for improvement from human, add to working memory+ await self._ask_review(trigger=ReviewConst.TASK_REVIEW_TRIGGER)++ ### Common Procedure in both single- and multi-agent setting #### create initial plan and update until confirmationawait self._update_plan()-+while self.plan.current_task:task = self.plan.current_tasklogger.info(f"ready to take on task {task}")@@@ -124,78 -76,62 +103,106 @@@self.plan.finish_current_task()self.working_memory.clear()+ success, new_code = await self._update_data_columns()+ if success:+ task.code = task.code + "\n\n" + new_code+++ confirmed_and_more = (ReviewConst.CONTINUE_WORD[0] in review.lower()+ and review.lower() not in ReviewConst.CONTINUE_WORD[0]) # "confirm, ... (more content, such as changing downstream tasks)"+ if confirmed_and_more:+ self.working_memory.add(Message(content=review, role="user", cause_by=AskReview))+ await self._update_plan(review)-+++ elif "redo" in review:+ # Ask the Role to redo this task with help of review feedback,+ # useful when the code run is successful but the procedure or result is not what we want+ continue+else:# update plan according to user's feedback and to take on changed tasks- await self._update_plan()+ await self._update_plan(review)++ completed_plan_memory = self.get_useful_memories() # completed plan as a outcome+ self._rc.memory.add(completed_plan_memory[0]) # add to persistent memory++ summary = await SummarizeAnalysis().run(self.plan)+ rsp = Message(content=summary, cause_by=SummarizeAnalysis)+ self._rc.memory.add(rsp)++ # save code using datetime.now or keywords related to the goal of your project (plan.goal).+ project_record = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")+ save_code_file(name=project_record, code_context=self.execute_code.nb, file_format="ipynb")+ return rsp+ time = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')+ self.execute_code.save_notebook(f"{DATA_PATH}/notebooks/ml_{time}.ipynb")++ async def _update_data_columns(self):+ rsp = await UpdateDataColumns().run(self.plan)+ is_update, code = rsp["is_update"], rsp["code"]+ success = False+ if is_update:+ result, success = await self.execute_code.run(code)+ if success:+ self.data_desc["column_info"] = result+ return success, code+async def _write_and_exec_code(self, max_retry: int = 3):code_steps = (await WriteCodeSteps().run(self.plan)if self.use_code_stepselse "")-+counter = 0+ improve_code = ""success = False+ debug_context = []-+++ finished_tasks = self.plan.get_finished_tasks()+ code_context = [task.code for task in finished_tasks]+ code_result = [task.result for task in finished_tasks]+ code_context = "\n\n".join(code_context)+ code_result = "\n\n".join(code_result)-++while not success and counter < max_retry:context = self.get_useful_memories()+ # print("*" * 10)+ # print(context)+ # print("*" * 10)+ # breakpoint()-- if not self.use_tools or self.plan.current_task.task_type == "other":- # code = "print('abc')"+ if counter > 0:+ improve_code = await DebugCode().run(plan=self.plan.current_task.instruction,+ # finished_code=code_context,+ # finished_code_result=code_result,+ code=code,+ runtime_result=self.working_memory.get(),+ context=debug_context)++ if improve_code != "":+ code = improve_code+ logger.info(f"new code \n{improve_code}")+ cause_by = DebugCode+ elif not self.use_tools or self.plan.current_task.task_type == "other":+ logger.info("Write code with pure generation")code = await WriteCodeByGenerate().run(context=context, plan=self.plan, code_steps=code_steps, temperature=0.0)+ debug_context = [self.get_useful_memories(task_exclude_field={'result', 'code_steps'})[0]]cause_by = WriteCodeByGenerateelse:- code = await WriteCodeWithTools().run(- context=context, plan=self.plan, code_steps=code_steps, data_desc=""+ logger.info("Write code with tools")+ schema_path = PROJECT_ROOT / "metagpt/tools/functions/schemas"+ tool_context, code = await WriteCodeWithTools(schema_path=schema_path).run(+ context=context,+ plan=self.plan,+ code_steps=code_steps,+ column_info=self.data_desc.get("column_info", ""),)+ debug_context = tool_contextcause_by = WriteCodeWithTools-+self.working_memory.add(Message(content=code, role="assistant", cause_by=cause_by))@@@ -239,39 -175,53 +246,53 @@@self.working_memory.add(Message(content=rsp, role="assistant", cause_by=WritePlan))- plan_confirmed = await self._ask_review()-- new_tasks = WritePlan.rsp_to_tasks(rsp)- logger.debug(len(self.plan.tasks))- logger.debug(len(new_tasks))- ## fixme: 能重复执行多轮重新plan,但应该有更优处理逻辑- ## fixme: do not overwrite original tasks- tasks = self.plan.tasks + new_tasks-- self.plan.add_tasks(tasks)++ # precheck plan before asking reviews+ is_plan_valid, error = precheck_update_plan_from_rsp(rsp, self.plan)+ if not is_plan_valid and max_retries > 0:+ error_msg = f"The generated plan is not valid with error: {error}, try regenerating, remember to generate either the whole plan or the single changed task only"+ logger.warning(error_msg)+ self.working_memory.add(Message(content=error_msg, role="assistant", cause_by=WritePlan))+ max_retries -= 1+ continue++ _, plan_confirmed = await self._ask_review(trigger=ReviewConst.TASK_REVIEW_TRIGGER)++ update_plan_from_rsp(rsp, self.plan)+self.working_memory.clear()--+++ async def _reflect(self):+ context = self.get_memories()+ context = "\n".join([str(msg) for msg in context])+ # print("*" * 10)+ # print(context)+ # print("*" * 10)+ reflection = await Reflect().run(context=context)+ self.working_memory.add(Message(content=reflection, role="assistant"))+ self.working_memory.add(Message(content=Reflect.REWRITE_PLAN_INSTRUCTION, role="user"))+- def get_useful_memories(self) -> List[Message]:+ def get_useful_memories(self, task_exclude_field: set = None) -> List[Message]:"""find useful memories only to reduce context length and improve performance"""# TODO dataset description , code stepsuser_requirement = self.plan.goal- tasks = json.dumps(- [task.dict(exclude=task_exclude_field) for task in self.plan.tasks], indent=4, ensure_ascii=False- )+ data_desc = self.plan.context- tasks = [task.dict() for task in self.plan.tasks]++ tasks = [task.dict(exclude=task_exclude_field) for task in self.plan.tasks]+ for task in tasks:+ # Shorten the context as we don't need code steps after we get the codes.+ # This doesn't affect current_task below, which should hold the code steps+ task.pop("code_steps")+ tasks = json.dumps(tasks, indent=4, ensure_ascii=False)current_task = self.plan.current_task.json() if self.plan.current_task else {}context = STRUCTURAL_CONTEXT.format(- user_requirement=user_requirement,- data_desc=self.data_desc,- tasks=tasks,- current_task=current_task+ user_requirement=user_requirement, data_desc=data_desc, tasks=tasks, current_task=current_task)context_msg = [Message(content=context, role="user")]-- return context_msg + self.working_memory.get()-- @property- def working_memory(self):- return self._rc.memory++ return context_msg + self.get_working_memories()-+++ def get_working_memories(self) -> List[Message]:+ return self.working_memory.get()if __name__ == "__main__":