🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
Merge dev to dev_tool_selection
lidanyang56dd0ee8822b
diff --cc metagpt/actions/write_analysis_code.pyindex 646b4f3f1,1127dc78b..cfec95deb--- a/metagpt/actions/write_analysis_code.py+++ b/metagpt/actions/write_analysis_code.py@@@ -61,27 -81,6 +61,27 @@@ class BaseWriteAnalysisCode(Action)}return messages+ async def run(- self, context: List[Message], plan: Plan = None, task_guide: str = ""++ self, context: List[Message], plan: Plan = None, code_steps: str = ""+ ) -> str:+ """Run of a code writing action, used in data analysis or modeling++ Args:+ context (List[Message]): Action output history, source action denoted by Message.cause_by+ plan (Plan, optional): Overall plan. Defaults to None.- task_guide (str, optional): suggested step breakdown for the current task. Defaults to "".++ code_steps (str, optional): suggested step breakdown for the current task. Defaults to "".++ Returns:+ str: The code string.+ """+++class WriteCodeByGenerate(BaseWriteAnalysisCode):+ """Write code fully by generation"""++ def __init__(self, name: str = "", context=None, llm=None) -> str:+ super().__init__(name, context, llm)+async def run(self,context: [List[Message]],@@@ -152,37 -155,51 +152,38 @@@ class WriteCodeWithTools(BaseWriteAnalyself,context: List[Message],plan: Plan = None,- task_guide: str = "",+ code_steps: str = "",+ data_desc: str = "",) -> str:task_type = plan.current_task.task_type- task = plan.current_task.instructionavailable_tools = registry.get_all_schema_by_module(task_type)- available_tools = [- {k: tool[k] for k in ["name", "description"] if k in tool}- for tool in available_tools- ]- code_steps = "\n".join(- [f"Step {step.strip()}" for step in code_steps.split("\n")]- )-- recommend_tools = await self._tool_recommendation(- task, code_steps, available_tools- )- recommend_tools, tool_catalog = self._parse_recommend_tools(task_type, recommend_tools)- logger.info(f"Recommended tools for every steps: {recommend_tools}")-special_prompt = ML_SPECIFIC_PROMPT.get(task_type, "")- module_name = ML_MODULE_MAP[task_type]- output_desc = TOOL_OUTPUT_DESC.get(task_type, "")- all_tasks = ""- completed_code = ""-- for i, task in enumerate(plan.tasks):- stats = "DONE" if task.is_finished else "TODO"- all_tasks += f"Subtask {task.task_id}: {task.instruction}({stats})\n"-- for task in plan.tasks:- if task.code:- completed_code += task.code + "\n"-- prompt = TOO_ORGANIZATION_PROMPT.format(- all_tasks=all_tasks,- completed_code=completed_code,- data_desc=data_desc,- special_prompt=special_prompt,- code_steps=code_steps,- module_name=module_name,- output_desc=output_desc,- available_tools=recommend_tools,- tool_catalog=tool_catalog,- )++ if len(available_tools) > 0:+ available_tools = [+ {k: tool[k] for k in ["name", "description"] if k in tool}+ for tool in available_tools+ ]+- recommend_tools = await self._tool_recommendation(context, task_guide, available_tools)++ recommend_tools = await self._tool_recommendation(context, code_steps, available_tools)+ tool_catalog = self._parse_recommend_tools(task_type, recommend_tools)+ logger.info(f"Recommended tools: \n{recommend_tools}")++ module_name = ML_MODULE_MAP[task_type]+ output_desc = TOOL_OUTPUT_DESC.get(task_type, "")+ prompt = TOO_ORGANIZATION_PROMPT.format(+ special_prompt=special_prompt,- code_steps=task_guide,++ code_steps=code_steps,+ module_name=module_name,+ output_desc=output_desc,+ function_catalog=tool_catalog,+ )+ context.append(Message(content=prompt, role="user"))+ else:+ context.append(Message(content=self.REUSE_CODE_INSTRUCTION, role="user"))+ context.append(Message(content=special_prompt, role="user"))++ prompt = self.process_msg(context)tool_config = create_func_config(CODE_GENERATOR_WITH_TOOLS)rsp = await self.llm.aask_code(prompt, **tool_config)return rsp["code"]diff --cc metagpt/roles/ml_engineer.pyindex 15edb2b06,ce0689497..148851e9e--- a/metagpt/roles/ml_engineer.py+++ b/metagpt/roles/ml_engineer.py@@@ -1,21 -1,18 +1,21 @@@-from typing import Dict, List, Union+import globimport json-import subprocess+from typing import Listimport fire+import pandas as pdimport re-from metagpt.roles import Rolefrom metagpt.actions import Action-from metagpt.schema import Message, Task, Plan-from metagpt.logs import logger-from metagpt.actions.write_plan import WritePlan-from metagpt.actions.write_analysis_code import WriteCodeByGenerate, WriteCodeWithToolsfrom metagpt.actions.execute_code import ExecutePyCode+from metagpt.actions.write_analysis_code import WriteCodeByGenerate, WriteCodeWithTools+from metagpt.actions.write_plan import WritePlan- from metagpt.actions.write_task_guide import WriteTaskGuide+from metagpt.logs import logger+from metagpt.prompts.ml_engineer import GEN_DATA_DESC_PROMPT+from metagpt.roles import Role+from metagpt.schema import Message, Plan+from metagpt.utils.common import CodeParser+ from metagpt.actions.write_code_steps import WriteCodeStepsSTRUCTURAL_CONTEXT = """## User Requirement@@@ -123,47 -67,19 +123,42 @@@ class AskReview(Action)return rsp, confirmed- # class WriteTaskGuide(Action):- # async def run(self, task_instruction: str, data_desc: dict = None) -> str:- # return ""--+class GenerateDataDesc(Action):+ async def run(self, files: list) -> dict:+ data_desc = {}+ for file in files:+ df = read_data(file)+ file_name = file.split("/")[-1]+ data_head = df.head().to_dict(orient="list")+ data_head = json.dumps(data_head, indent=4, ensure_ascii=False)+ prompt = GEN_DATA_DESC_PROMPT.replace("{data_head}", data_head)+ rsp = await self._aask(prompt)+ rsp = CodeParser.parse_code(block=None, text=rsp)+ data_desc[file_name] = {}+ data_desc[file_name]["path"] = file+ data_desc[file_name]["description"] = rsp+ data_desc[file_name]["column_info"] = get_samples(df)+ return data_desc++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, data_path: str = None):super().__init__(name=name, profile=profile, goal=goal)self._set_react_mode(react_mode="plan_and_act")self.plan = Plan(goal=goal)- self.use_tools = False+ self.use_tools = True- self.use_task_guide = True+ self.use_code_steps = Trueself.execute_code = ExecutePyCode()self.auto_run = auto_run+ self.data_path = data_path+ self.data_desc = {}async def _plan_and_act(self):+ if self.data_path:+ self.data_desc = await self._generate_data_desc()+# create initial plan and update until confirmationawait self._update_plan()@@@ -188,15 -105,10 +184,15 @@@# update plan according to user's feedback and to take on changed tasksawait self._update_plan()+ async def _generate_data_desc(self):+ files = glob.glob(self.data_path + "/*.csv")+ data_desc = await GenerateDataDesc().run(files=files)+ return data_desc+async def _write_and_exec_code(self, max_retry: int = 3):- task_guide = (- await WriteTaskGuide().run(self.plan)- if self.use_task_guide+ code_steps = (+ await WriteCodeSteps().run(self.plan)+ if self.use_code_stepselse "")@@@ -211,16 -123,14 +207,16 @@@# breakpoint()if not self.use_tools or self.plan.current_task.task_type == "other":+ logger.info("Write code with pure generation")# code = "print('abc')"code = await WriteCodeByGenerate().run(- context=context, plan=self.plan, task_guide=task_guide, temperature=0.0+ context=context, plan=self.plan, code_steps=code_steps, temperature=0.0)cause_by = WriteCodeByGenerateelse:+ logger.info("Write code with tools")code = await WriteCodeWithTools().run(- context=context, plan=self.plan, task_guide=task_guide- context=context, plan=self.plan, code_steps=code_steps, data_desc=""++ context=context, plan=self.plan, code_steps=code_steps,)cause_by = WriteCodeWithTools@@@ -298,13 -205,10 +294,13 @@@ if __name__ == "__main__"# requirement = "Run data analysis on sklearn Diabetes dataset, include a plot"# requirement = "Run data analysis on sklearn Wine recognition dataset, include a plot, and train a model to predict wine class (20% as validation), and show validation accuracy"# requirement = "Run data analysis on sklearn Wisconsin Breast Cancer dataset, include a plot, train a model to predict targets (20% as validation), and show validation accuracy"- # requirement = "Run EDA and visualization on this dataset, train a model to predict survival, report metrics on validation set (20%), dataset: workspace/titanic/train.csv"+ requirement = "Run EDA and visualization on this dataset, train a model to predict survival, report metrics on validation set (20%), dataset: workspace/titanic/train.csv"- async def main(requirement: str = requirement, auto_run: bool = False):- role = MLEngineer(goal=requirement, auto_run=auto_run)+ requirement = "Perform data analysis on the provided data. Train a model to predict the target variable Survived. Include data preprocessing, feature engineering, and modeling in your pipeline. The metric is accuracy."+ data_path = "/data/lidanyang/tabular_data/titanic"++ async def main(requirement: str = requirement, auto_run: bool = True, data_path: str = data_path):+ role = MLEngineer(goal=requirement, auto_run=auto_run, data_path=data_path)await role.run(requirement)fire.Fire(main)