Skip to content

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

Merge branch 'dev' into dev_make_tools

刘棒棒d72b457c83a4
diff --cc metagpt/roles/ml_engineer.py
index 9fa12b41d,33b570d1a..5d514a18f
--- a/metagpt/roles/ml_engineer.py
+++ b/metagpt/roles/ml_engineer.py
@@@ -45,12 -46,10 +46,12 @@@ class MLEngineer(Role)
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.make_udfs = False # user-defined functions
+ self.use_udfs = False
- self.use_code_steps = False
+ self.use_tools = True
+ self.use_code_steps = True
self.execute_code = ExecutePyCode()
self.auto_run = auto_run
self.data_desc = {}
@@@ -151,16 -150,11 +152,11 @@@
counter = 0
success = False
debug_context = []
-
+
while not success and counter < max_retry:
context = self.get_useful_memories()
-
- # print("*" * 10)
- # print(context)
- # print("*" * 10)
- # breakpoint()
-
- if counter > 0 and self.use_tools:
+ if counter > 0 and (self.use_tools or self.use_udfs):
+ logger.warning('We got a bug code, now start to debug...')
code = await DebugCode().run(
plan=self.plan.current_task.instruction,
code=code,
@@@ -207,13 -184,9 +203,13 @@@
self.working_memory.add(
Message(content=code, role="assistant", cause_by=cause_by)
)
-
+
result, success = await self.execute_code.run(code)
print(result)
+ # make tools for successful code and long code.
+ if success and self.make_udfs and len(code.split('\n')) > 4:
+ logger.info('Execute code successfully. Now start to make tools ...')
+ await self.make_tools(code=code)
self.working_memory.add(
Message(content=result, role="user", cause_by=ExecutePyCode)
)
@@@ -299,57 -270,63 +293,109 @@@
def get_working_memories(self) -> List[Message]:
return self.working_memory.get()
+ def reset(self):
+ """Restart role with the same goal."""
+ self.plan = Plan(goal=self.plan.goal)
+ self.execute_code = ExecutePyCode()
+
+ async def make_tools(self, code: str):
+ """Make user-defined functions(udfs, aka tools) for pure generation code.
+
+ Args:
+ code (str): pure generation code by class WriteCodeByGenerate.
+ """
+ logger.warning(f"Making tools for task_id {self.plan.current_task_id}: \
+ `{self.plan.current_task.instruction}` \n code: \n {code}")
+ make_tools = MakeTools()
+ code_prompt = f"The following code is about {self.plan.current_task.instruction},\
+ convert it to be a General Function, {code}"
+ tool_code = await make_tools.run(code_prompt)
+ # check tool_code by execute_code
+ logger.info(f"Checking task_id {self.plan.current_task_id} tool code by executor...")
+ _, success = await self.execute_code.run(tool_code)
+ make_tool_retries, make_tool_current_retry = 3, 1
+ while not success:
+ tool_code = await make_tools.run(code_prompt)
+ _, success = await self.execute_code.run(tool_code)
+ if make_tool_current_retry > make_tool_retries:
+ logger.error(f"We have tried the maximum number of attempts {make_tool_retries}\
+ and still have not created tools for task_id {self.plan.current_task_id} successfully,\
+ we will skip it.")
+ break
+ # save successful tool code in udf
+ if success:
+ make_tools.save(tool_code)
+
if __name__ == "__main__":
- requirement = "Run data analysis on sklearn Iris dataset, include a plot"
+ # requirement = "Run data analysis on sklearn Iris dataset, include a plot"
# 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"
+
- async def main(requirement: str = requirement, auto_run: bool = True):
- role = MLEngineer(goal=requirement, auto_run=auto_run)
- # make udfs
- role.make_udfs = True
- role.use_udfs = False
- await role.run(requirement)
- # use udfs
- role.reset()
- role.make_udfs = False
- role.use_udfs = True
- await role.run(requirement)
++ # async def main(requirement: str = requirement, auto_run: bool = True):
++ # role = MLEngineer(goal=requirement, auto_run=auto_run)
++ # # make udfs
++ # role.make_udfs = True
++ # role.use_udfs = False
++ # await role.run(requirement)
++ # # use udfs
++ # role.reset()
++ # role.make_udfs = False
++ # role.use_udfs = True
++ # await role.run(requirement)
+
+
+ # 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"
+ # 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'."
+ # requirement = f"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"
+ # data_path = f"{DATA_PATH}/icr-identify-age-related-conditions"
+ # requirement = f"This is a medical dataset with over fifty anonymized health characteristics linked to three age-related conditions. Your goal is to predict whether a subject has or has not been diagnosed with one of these conditions.The target column is Class. Perform data analysis, data preprocessing, feature engineering, and modeling to predict the target. Report f1 score on the eval data. Train data path: {data_path}/split_train.csv, eval data path: {data_path}/split_eval.csv."
+
+ # data_path = f"{DATA_PATH}/santander-customer-transaction-prediction"
+ # requirement = f"This is a customers financial dataset. Your goal is to predict which customers will make a specific transaction in the future. The target column is target. Perform data analysis, data preprocessing, feature engineering, and modeling to predict the target. Report F1 Score on the eval data. Train data path: '{data_path}/split_train.csv', eval data path: '{data_path}/split_eval.csv' ."
+
+ data_path = f"{DATA_PATH}/house-prices-advanced-regression-techniques"
+ requirement = f"This is a house price dataset, your goal is to predict the sale price of a property based on its features. The target column is SalePrice. Perform data analysis, data preprocessing, feature engineering, and modeling to predict the target. Report RMSE between the logarithm of the predicted value and the logarithm of the observed sales price on the eval data. Train data path: '{data_path}/split_train.csv', eval data path: '{data_path}/split_eval.csv'."
+
+ save_dir = ""
+
+
+ # save_dir = DATA_PATH / "output" / "2023-12-14_20-40-34"
+
+ async def main(requirement: str = requirement, auto_run: bool = True, save_dir: str = save_dir):
+ """
+ The main function to run the MLEngineer with optional history loading.
+
+ Args:
+ requirement (str): The requirement for the MLEngineer.
+ auto_run (bool): Whether to auto-run the MLEngineer.
+ save_dir (str): The directory from which to load the history or to save the new history.
+
+ Raises:
+ Exception: If an error occurs during execution, log the error and save the history.
+ """
+ if save_dir:
+ logger.info("Resuming from history trajectory")
+ plan, nb = load_history(save_dir)
+ role = MLEngineer(goal=requirement, auto_run=auto_run)
+ role.plan = Plan(**plan)
+ role.execute_code = ExecutePyCode(nb)
+
+ else:
+ logger.info("Run from scratch")
+ role = MLEngineer(goal=requirement, auto_run=auto_run)
+
+ try:
+ await role.run(requirement)
+ except Exception as e:
+
+ save_path = save_history(role, save_dir)
+
+ logger.exception(f"An error occurred: {e}, save trajectory here: {save_path}")
+
+
fire.Fire(main)