🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
Merge branch 'dev' into kaggle_team
yzlinbec0f0d7288f
diff --cc metagpt/roles/ml_engineer.pyindex 6e7331281,2990ed031..fe6f81841--- a/metagpt/roles/ml_engineer.py+++ b/metagpt/roles/ml_engineer.py@@@ -8,32 -8,74 +8,27 @@@ import rfrom metagpt.roles import Rolefrom metagpt.actions import Actionfrom metagpt.schema import Message, Task, Plan+from metagpt.memory import Memoryfrom metagpt.logs import logger-from metagpt.actions.write_plan import WritePlan+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, ReviewConstfrom metagpt.actions.execute_code import ExecutePyCode+from metagpt.roles.kaggle_manager import DownloadData, SubmitResult+from metagpt.prompts.ml_engineer import STRUCTURAL_CONTEXT--- class WriteTaskGuide(Action):- async def run(self, task_instruction: str, data_desc: str = "") -> str:- return ""-+ from metagpt.actions.write_code_steps import WriteCodeSteps-STRUCTURAL_CONTEXT = """-## User Requirement-{user_requirement}-## 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--class MLEngineer(Role):def __init__(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 = False- self.use_task_guide = False+ self.use_code_steps = Trueself.execute_code = ExecutePyCode()self.auto_run = auto_run@@@ -64,12 -88,12 +59,12 @@@logger.info(f"ready to take on task {task}")# take on current task- code, result, success = await self._write_and_exec_code()+ code, result, success, code_steps = await self._write_and_exec_code()# ask for acceptance, users can other refuse and change tasks in the plan- task_result_confirmed = await self._ask_review()+ review, task_result_confirmed = await self._ask_review(trigger=ReviewConst.TASK_REVIEW_TRIGGER)- if success and task_result_confirmed:+ if task_result_confirmed:# tick off this task and record progresstask.code = codetask.result = result@@@ -76,34 -101,14 +72,34 @@@self.plan.finish_current_task()self.working_memory.clear()+ 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)++ return rspasync def _write_and_exec_code(self, max_retry: int = 3):- task_guide = (- await WriteTaskGuide().run(self.plan.current_task.instruction)- if self.use_task_guide+ code_steps = (+ await WriteCodeSteps().run(self.plan)+ if self.use_code_stepselse "")@@@ -144,25 -153,20 +140,25 @@@counter += 1+ if not success and counter >= max_retry:+ logger.info("coding failed!")+ review, _ = await self._ask_review(auto_run=False, trigger=ReviewConst.CODE_REVIEW_TRIGGER)+ if ReviewConst.CHANGE_WORD in review:+ counter = 0 # redo the task again with help of human suggestions+- return code, result, success+ return code, result, success, code_steps- async def _ask_review(self):- if not self.auto_run:+ async def _ask_review(self, auto_run: bool = None, trigger: str = ReviewConst.TASK_REVIEW_TRIGGER):+ auto_run = auto_run or self.auto_run+ if not auto_run:context = self.get_useful_memories()- review, confirmed = await AskReview().run(context=context[-5:], plan=self.plan)+ review, confirmed = await AskReview().run(context=context[-5:], plan=self.plan, trigger=trigger)if not confirmed:self.working_memory.add(Message(content=review, role="user", cause_by=AskReview))- return confirmed- return True+ return review, confirmed+ return "", True- async def _update_plan(self, max_tasks: int = 3):+ async def _update_plan(self, review: str = "", max_tasks: int = 3, max_retries: int = 3):plan_confirmed = Falsewhile not plan_confirmed:context = self.get_useful_memories()@@@ -200,9 -184,8 +196,9 @@@def get_useful_memories(self) -> List[Message]:"""find useful memories only to reduce context length and improve performance"""-+ # TODO dataset description , code stepsuser_requirement = self.plan.goal+ data_desc = self.plan.contexttasks = json.dumps([task.dict() for task in self.plan.tasks], indent=4, ensure_ascii=False)