Skip to content

🌟 The Multi-Agent Framework: First AI Software Company, Towards Natural Language Programming

Merge branch 'dev_tool_selection' of https://gitlab.deepwisdomai.com/agents/data_agents_opt into dev_tool_selection

stellahsrb9d12f17aed6
diff --cc metagpt/actions/write_analysis_code.py
index 777064f93,f96ade1b4..58cab9c6a
--- a/metagpt/actions/write_analysis_code.py
+++ b/metagpt/actions/write_analysis_code.py
@@@ -12,11 -12,10 +12,11 @@@ from metagpt.prompts.ml_engineer impor
TOOL_RECOMMENDATION_PROMPT,
SELECT_FUNCTION_TOOLS,
CODE_GENERATOR_WITH_TOOLS,
- TOOL_ORGANIZATION_PROMPT,
- TOO_ORGANIZATION_PROMPT,
++ TOOL_USAGE_PROMPT,
ML_SPECIFIC_PROMPT,
ML_MODULE_MAP,
- TOOL_OUTPUT_DESC,
- TOOL_USAGE_PROMPT,
+ TOOL_OUTPUT_DESC, DATA_PROCESS_PROMPT,
++ GENERATE_CODE_PROMPT
)
from metagpt.schema import Message, Plan
from metagpt.tools.functions import registry
@@@ -131,10 -121,10 +122,10 @@@ class WriteCodeWithTools(BaseWriteAnaly
return tool_catalog
async def _tool_recommendation(
- self,
- task: str,
- code_steps: str,
- available_tools: list
+ self,
- context: [List[Message]],
++ task: str,
+ code_steps: str,
+ available_tools: list
) -> list:
"""
Recommend tools for the specified task.
@@@ -159,21 -148,18 +149,20 @@@
return recommend_tools
async def run(
- self,
- context: List[Message],
- plan: Plan = None,
- code_steps: str = "",
- column_info: str = "",
+ self,
+ context: List[Message],
+ plan: Plan = None,
+ code_steps: str = "",
++ column_info: str = "",
+ **kwargs,
) -> str:
task_type = plan.current_task.task_type
- logger.info(f"task_type is: {task_type}")
available_tools = registry.get_all_schema_by_module(task_type)
special_prompt = ML_SPECIFIC_PROMPT.get(task_type, "")
+ column_names = kwargs.get("column_names", {})
finished_tasks = plan.get_finished_tasks()
- code_context = [task.code for task in 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:
@@@ -192,45 -178,22 +181,45 @@@
module_name = ML_MODULE_MAP[task_type]
output_desc = TOOL_OUTPUT_DESC.get(task_type, "")
-
- prompt = DATA_PROCESS_PROMPT.format(
- user_requirement=plan.goal,
- history_code=code_context,
- current_task=plan.current_task.instruction,
- column_info=column_info,
- special_prompt=special_prompt,
++ new_code = ""
+
+ for idx, tool in enumerate(recommend_tools):
+ hist_info = f"Previous finished code is \n\n ```Python {code_context} ``` \n\n "
+
+ prompt = TOOL_USAGE_PROMPT.format(
+ goal=plan.current_task.instruction,
+ context=hist_info,
+ code_steps=code_steps,
+ column_names=column_names,
+ special_prompt=special_prompt,
+ module_name=module_name,
+ output_desc=output_desc,
+ function_catalog=tool_catalog[idx],
+ )
+
+ tool_config = create_func_config(CODE_GENERATOR_WITH_TOOLS)
+
+ rsp = await self.llm.aask_code(prompt, **tool_config)
+ logger.info(f"rsp is: {rsp}")
+ # final_code = final_code + "\n\n" + rsp["code"]
+ # final_code[key] = rsp["code"]
+ new_code = new_code + "\n\n" + rsp["code"]
+ code_context = code_context + "\n\n" + rsp["code"]
+ return new_code
+
+ else:
+ hist_info = f"Previous finished code is \n\n ```Python {code_context} ``` \n\n "
+
+ prompt = GENERATE_CODE_PROMPT.format(
+ goal=plan.current_task.instruction,
+ context=hist_info,
code_steps=code_steps,
- module_name=module_name,
- output_desc=output_desc,
- function_catalog=tool_catalog,
+ special_prompt=special_prompt,
+ # column_names=column_names
)
- 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']
+ tool_config = create_func_config(CODE_GENERATOR_WITH_TOOLS)
+ logger.info(f"prompt is: {prompt}")
+ rsp = await self.llm.aask_code(prompt, **tool_config)
+ logger.info(f"rsp is: {rsp}")
+ return rsp["code"]
diff --cc metagpt/prompts/ml_engineer.py
index 9a234478c,88cebf68a..5c7b9f82e
--- a/metagpt/prompts/ml_engineer.py
+++ b/metagpt/prompts/ml_engineer.py
@@@ -135,20 -135,13 +141,25 @@@ Make sure use the columns from the data
Finish your coding tasks as a helpful programmer based on the tools.
"""
++
GENERATE_CODE_PROMPT = """
## Target
{goal}
-## History Info
+Specifically, {special_prompt}
+
+
- ## History Info
++## Finished Task and Code
{context}
+## Code Steps for Current Task:
+Follow steps below when you writing code if it's convenient.
+{code_steps}
+
++## Instruction
++Finished task and code are executable, and you should based on the code to continue your current task
++Do not repeat functions and code, try to reuse the code in [Finished Task and Code]
++
## Your Output Format:
Generate the complete code for this task:
```python
@@@ -162,7 -155,35 +173,35 @@@ Finish your coding tasks as a helpful p
"""
+ TOOL_USAGE_PROMPT = """
+ ## Target
+ {goal}
+
+ ## History Info
+ {context}
+
+ ## Available Tools:
+ Each function is described in JSON format, including the function name and parameters. {output_desc}
+ {function_catalog}
+
+ When you call a function above, you should import the function from `{module_name}` first, e.g.:
+ ```python
+ from metagpt.tools.functions.libs.data_preprocess import fill_missing_value
+ ```end
+
+ ## Your Output Format:
+ Generate the complete code for this task:
+ ```python
+ # Tools used: [function names or 'none']
+ <your code for the current task, without any comments>
+ ```end
+
+ ## Attention:
+ Make sure use the columns from the dataset columns
+ Finish your coding tasks as a helpful programmer based on the tools.
+ """
+
-TOO_ORGANIZATION_PROMPT = """
+TOOL_ORGANIZATION_PROMPT = """
The previous conversation has provided all tasks step-by-step for the use goal and their statuses.
Now, begin writing code for the current task. This code should writen strictly on the basis of all previous completed tasks code, not a standalone code. And avoid writing duplicate code that has already been written in previous tasks, such as repeated import of packages, reading data, etc.
Specifically, {special_prompt}
diff --cc metagpt/roles/ml_engineer.py
index b5904213c,4ad24df52..1b191c8ba
--- a/metagpt/roles/ml_engineer.py
+++ b/metagpt/roles/ml_engineer.py
@@@ -15,8 -16,6 +16,7 @@@ from metagpt.prompts.ml_engineer impor
from metagpt.roles import Role
from metagpt.schema import Message, Plan
from metagpt.utils.common import CodeParser
- from metagpt.actions.write_code_steps import WriteCodeSteps
+from metagpt.actions.debug_code import DebugCode
STRUCTURAL_CONTEXT = """
## User Requirement
@@@ -188,18 -169,8 +173,17 @@@ class MLEngineer(Role)
# update plan according to user's feedback and to take on changed tasks
await self._update_plan()
+
+ finished_tasks = self.plan.get_finished_tasks()
+ if len(finished_tasks) == len(self.plan.tasks):
+ code_context = [task.code for task in finished_tasks]
+ code_context = "\n\n".join(code_context)
+ result, success = await self.execute_code.run(code_context)
+ # truncated the result
+ print(truncate(result))
+
async def _generate_data_desc(self):
- files = glob.glob(self.data_path + "/*.csv")
- data_desc = await GenerateDataDesc().run(files=files)
+ data_desc = await GenerateDataDesc().run(self.data_path)
return data_desc
async def _write_and_exec_code(self, max_retry: int = 3):
@@@ -210,25 -181,14 +194,21 @@@
)
counter = 0
+ improve_code = ""
success = False
+
+ finished_tasks = self.plan.get_finished_tasks()
+ code_context = [task.code for task in finished_tasks]
+ code_context = "\n\n".join(code_context)
+
while not success and counter < max_retry:
- context = self.get_useful_memories()
+ if counter == 0:
+ context = self.get_useful_memories()
+ else:
- # improve_code = await DebugCode().run(plan=self.plan,
- # code= code_context + "\n\n" + code,
- # runtime_result=self.working_memory.get())
- improve_code = ""
-
- # breakpoint()
++ improve_code = await DebugCode().run(plan=self.plan,
++ code= code_context + "\n\n" + code,
++ runtime_result=self.working_memory.get())
- column_names_dict = {key: value["column_info"] for key, value in self.data_desc.items()}
- # print("*" * 10)
- # print(context)
- # print("*" * 10)
- # breakpoint()
if not self.use_tools or self.plan.current_task.task_type == "other":
logger.info("Write code with pure generation")
@@@ -239,28 -199,20 +219,28 @@@
cause_by = WriteCodeByGenerate
else:
logger.info("Write code with tools")
- column_info = self.data_desc['column_info']
- code = await WriteCodeWithTools().run(
- context=context, plan=self.plan, code_steps=code_steps, column_info=column_info
- )
- cause_by = WriteCodeWithTools
+
+ if improve_code!="":
+ code = improve_code
+ logger.info(f"new code {code}")
+ cause_by = DebugCode
+ else:
+ code = await WriteCodeWithTools().run(
- context=context, plan=self.plan, code_steps=code_steps, **{"column_names": column_names_dict}
++ context=context, plan=self.plan, code_steps=code_steps, **{"column_names": {}}
+ )
+
+ cause_by = WriteCodeWithTools
self.working_memory.add(
Message(content=code, role="assistant", cause_by=cause_by)
)
- result, success = await self.execute_code.run(code)
+ # debug on code, run on runcode with finished code and new_df
+ runcode = code_context + "\n\n" + code
+ result, success = await self.execute_code.run(runcode)
# truncated the result
print(truncate(result))
-- # print(result)
++
self.working_memory.add(
Message(content=truncate(remove_escape_and_color_codes(result)), role="user", cause_by=ExecutePyCode)
)
@@@ -330,13 -281,10 +310,12 @@@ if __name__ == "__main__"
# 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"
- from metagpt.const import DATA_PATH
-
- 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 = f"{DATA_PATH}/titanic.csv"
+ # 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."
+
- async def main(requirement: str = requirement, auto_run: bool = True, data_path: str = data_path):
+ data_path = f"{DATA_PATH}/titanic"
+ requirement = f"This is a titanic passenger survival dataset, your goal is to predict passenger survival outcome. The target column is Survived. Perform data analysis, data preprocessing, feature engineering, and modeling to predict the target. Report accuracy on the eval data. Train data path: '{data_path}/split_train.csv', eval data path: '{data_path}/split_eval.csv'."
+
+ async def main(requirement: str = requirement, auto_run: bool = True, data_path: str = ""):
role = MLEngineer(goal=requirement, auto_run=auto_run, data_path=data_path)
await role.run(requirement)