🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming
Merge remote-tracking branch 'origin/dev' into dev_tool_selection
lidanyang3a3b31badb34
diff --cc metagpt/actions/write_analysis_code.pyindex 3e91f4b14,7e6483371..2c45281f9--- a/metagpt/actions/write_analysis_code.py+++ b/metagpt/actions/write_analysis_code.py@@@ -24,9 -23,27 +24,9 @@@ from metagpt.utils.common import createclass BaseWriteAnalysisCode(Action):- async def run(self, context: List[Message], plan: Plan = None) -> 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 "".-- Returns:- str: The code string.- """---class WriteCodeByGenerate(BaseWriteAnalysisCode):- """Write code fully by generation"""- DEFAULT_SYSTEM_MSG = """You are Code Interpreter, a world-class programmer that can complete any goal by executing code. Strictly follow the plan and generate code step by step. Each step of the code will be executed on the user's machine, and the user will provide the code execution results to you.**Notice: The code for the next step depends on the code for the previous step. Must reuse variables in the lastest other code directly, dont creat it again, it is very import for you. Use !pip install in a standalone block to install missing packages.**""" # prompt reference: https://github.com/KillianLucas/open-interpreter/blob/v0.1.4/interpreter/system_message.txt- # REUSE_CODE_INSTRUCTION = """ATTENTION: DONT include codes from previous tasks in your current code block, include new codes only, DONT repeat codes!"""-- def __init__(self, name: str = "", context=None, llm=None) -> str:- super().__init__(name, context, llm)+ DEFAULT_SYSTEM_MSG = """You are Code Interpreter, a world-class programmer that can complete any goal by executing code. Strictly follow the plan and generate code step by step. Each step of the code will be executed on the user's machine, and the user will provide the code execution results to you.""" # prompt reference: https://github.com/KillianLucas/open-interpreter/blob/v0.1.4/interpreter/system_message.txt+ REUSE_CODE_INSTRUCTION = """ATTENTION: DONT include codes from previous tasks in your current code block, include new codes only, DONT repeat codes!"""-+def process_msg(self, prompt: Union[str, List[Dict], Message, List[Message]], system_msg: str = None):default_system_msg = system_msg or self.DEFAULT_SYSTEM_MSG# 全部转成list@@@ -61,37 -78,15 +61,36 @@@"content": messages[0]["content"] + default_system_msg,}return messages-++ async def run(+ 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.+ 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]],- plan: Plan = None,- code_steps: str = "",- system_msg: str = None,- **kwargs,+ self,+ context: [List[Message]],+ plan: Plan = None,+ system_msg: str = None,+ **kwargs,) -> str:- context.append(Message(content=self.REUSE_CODE_INSTRUCTION, role="user"))+ # context.append(Message(content=self.REUSE_CODE_INSTRUCTION, role="user"))prompt = self.process_msg(context, system_msg)code_content = await self.llm.aask_code(prompt, **kwargs)return code_content["code"]@@@ -99,62 -94,52 +98,62 @@@class WriteCodeWithTools(BaseWriteAnalysisCode):"""Write code with help of local available tools. Choose tools first, then generate code to use the tools"""-+- @staticmethod- def _parse_recommend_tools(module: str, recommend_tools: list) -> Tuple[Dict, List[Dict]]:+ def __init__(self, name: str = "", context=None, llm=None, schema_path=None):+ super().__init__(name, context, llm)+ self.schema_path = schema_path+ self.available_tools = {}-+++ if self.schema_path is not None:+ self._load_tools(schema_path)-+++ def _load_tools(self, schema_path):+ """Load tools from yaml file"""+ yml_files = schema_path.glob("*.yml")+ for yml_file in yml_files:+ module = yml_file.stem+ with open(yml_file, "r", encoding="utf-8") as f:+ self.available_tools[module] = yaml.safe_load(f)-+++ def _parse_recommend_tools(self, module: str, recommend_tools: list) -> dict:"""Parses and validates a list of recommended tools, and retrieves their schema from registry.Args:module (str): The module name for querying tools in the registry.- recommend_tools (list): A list of lists of recommended tools for each step.+ recommend_tools (list): A list of recommended tools.Returns:- Tuple[Dict, List[Dict]]:- - valid_tools: A dict of lists of valid tools for each step.- - tool_catalog: A list of dicts of unique tool schemas.+ dict: A dict of valid tool schemas."""- valid_tools = {}- available_tools = registry.get_all_by_module(module).keys()- for index, tools in enumerate(recommend_tools):- key = f"Step {index + 1}"- tools = [tool for tool in tools if tool in available_tools]- valid_tools[key] = tools-- unique_tools = set()- for tools in valid_tools.values():- unique_tools.update(tools)- tool_catalog = registry.get_schemas(module, unique_tools)- return valid_tools, tool_catalog+ valid_tools = []+ available_tools = self.available_tools[module].keys()+ for tool in recommend_tools:+ if tool in available_tools:+ valid_tools.append(tool)-+++ tool_catalog = {tool: self.available_tools[module][tool] for tool in valid_tools}+ return tool_catalog-+async def _tool_recommendation(- self,- task: str,- code_steps: str,- available_tools: dict,- self, task: str, data_desc: str, code_steps: str, available_tools: list++ self,++ task: str,++ code_steps: str,++ available_tools: dict,) -> list:"""- Recommend tools for each step of the specified task+ Recommend tools for the specified task.Args:- task (str): the task description- data_desc (str): the description of the dataset for the task+ task (str): the task to recommend tools forcode_steps (str): the code steps to generate the full code for the task- available_tools (list): the available tools for the task+ available_tools (dict): the available tools descriptionReturns:- list: recommended tools for each step of the specified task+ list: recommended tools for the specified task"""prompt = TOOL_RECOMMENDATION_PROMPT.format(- task=task,- data_desc=data_desc,+ current_task=task,code_steps=code_steps,available_tools=available_tools,)@@@ -162,59 -147,56 +161,59 @@@rsp = await self.llm.aask_code(prompt, **tool_config)recommend_tools = rsp["recommend_tools"]return recommend_tools-+async def run(- self,- context: List[Message],- plan: Plan = None,- code_steps: str = "",- column_info: str = "",- **kwargs,+ self,+ context: List[Message],+ plan: Plan = None,- data_desc: str = "",- ) -> str:++ column_info: str = "",++ **kwargs,+ ) -> Tuple[List[Message], str]:task_type = plan.current_task.task_type- task = plan.current_task.instruction+ available_tools = self.available_tools.get(task_type, {})+ special_prompt = ML_SPECIFIC_PROMPT.get(task_type, "")-+ code_steps = plan.current_task.code_steps- available_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}")+ finished_tasks = plan.get_finished_tasks()+ code_context = [remove_comments(task.code) for task in finished_tasks]+ code_context = "\n\n".join(code_context)-+++ if len(available_tools) > 0:+ available_tools = {k: v["description"] for k, v in available_tools.items()}-+++ recommend_tools = await self._tool_recommendation(+ plan.current_task.instruction,+ 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]-+++ prompt = TOOL_USAGE_PROMPT.format(+ user_requirement=plan.goal,+ history_code=code_context,+ current_task=plan.current_task.instruction,+ column_info=column_info,+ special_prompt=special_prompt,+ code_steps=code_steps,+ module_name=module_name,+ tool_catalog=tool_catalog,+ )--+++++ else:+ prompt = GENERATE_CODE_PROMPT.format(+ user_requirement=plan.goal,+ history_code=code_context,+ current_task=plan.current_task.instruction,+ column_info=column_info,+ special_prompt=special_prompt,+ code_steps=code_steps,+ )-+- 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,- )tool_config = create_func_config(CODE_GENERATOR_WITH_TOOLS)rsp = await self.llm.aask_code(prompt, **tool_config)- return rsp["code"]+ context = [Message(content=prompt, role="user")]+ return context, rsp["code"]diff --cc metagpt/roles/ml_engineer.pyindex 8ab3ac981,8b74126bc..8f06a541c--- a/metagpt/roles/ml_engineer.py+++ b/metagpt/roles/ml_engineer.py@@@ -131,18 -102,8 +129,18 @@@ class MLEngineer(Role)save_code_file(name=project_record, code_context=self.execute_code.nb, file_format="ipynb")return rsp+ 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 = (+ self.plan.current_task.code_steps = (await WriteCodeSteps().run(self.plan)if self.use_code_stepselse ""@@@ -160,35 -118,17 +158,34 @@@# 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+ context=context, plan=self.plan, 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, 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 = WriteCodeWithToolsself.working_memory.add(