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

stellahsrad592b9501fe
diff --cc metagpt/roles/ml_engineer.py
index cd2104c4b,3755e7bac..d9a5027af
--- a/metagpt/roles/ml_engineer.py
+++ b/metagpt/roles/ml_engineer.py
@@@ -245,7 -246,9 +245,7 @@@ class MLEngineer(Role)
async def _reflect(self):
context = self.get_memories()
context = "\n".join([str(msg) for msg in context])
-
- # print("*" * 10)
- # print(context)
- # print("*" * 10)
++
reflection = await Reflect().run(context=context)
self.working_memory.add(Message(content=reflection, role="assistant"))
self.working_memory.add(Message(content=Reflect.REWRITE_PLAN_INSTRUCTION, role="user"))
@@@ -274,88 -277,14 +274,105 @@@
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)
- 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 / "save" / "2023-12-14_16-58-03"
++
++
++ # save_dir = DATA_PATH / "output" / "2023-12-14_20-40-34"
+
+ def load_history(save_dir: str = save_dir):
+ """
+ Load history from the specified save directory.
+
+ Args:
+ save_dir (str): The directory from which to load the history.
+
+ Returns:
+ Tuple: A tuple containing the loaded plan and notebook.
+ """
+
+ plan_path = Path(save_dir) / "plan.json"
- nb_path = Path(save_dir) / "history_nb.ipynb"
++ nb_path = Path(save_dir) / "history_nb" / "code.ipynb"
+ plan = json.load(open(plan_path, "r", encoding="utf-8"))
+ nb = nbformat.read(open(nb_path, "r", encoding="utf-8"), as_version=nbformat.NO_CONVERT)
+ return plan, nb
+
+
+ async def save_history(role: Role = MLEngineer, save_dir: str = save_dir):
+ """
+ Save history to the specified directory.
+
+ Args:
+ role (Role): The role containing the plan and execute_code attributes.
+ save_dir (str): The directory to save the history.
+
+ Returns:
+ Path: The path to the saved history directory.
+ """
- # save_path = Path(save_dir) if save_dir else DATA_PATH / "save" / datetime.now().strftime(
- # '%Y-%m-%d_%H-%M-%S')
- save_path = DATA_PATH / "save" / datetime.now().strftime(
- '%Y-%m-%d_%H-%M-%S')
++ record_time = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
++ save_path = DATA_PATH / "output" / f"{record_time}"
++
+ # overwrite exist trajectory
+ save_path.mkdir(parents=True, exist_ok=True)
+
+ plan = role.plan.dict()
+
+ with open(save_path / "plan.json", "w", encoding="utf-8") as plan_file:
+ json.dump(plan, plan_file, indent=4, ensure_ascii=False)
+
- role.execute_code.save_notebook(path=save_path / "history_nb.ipynb")
++ save_code_file(name=Path(record_time) / "history_nb", code_context=role.execute_code.nb, file_format="ipynb")
+ return save_path
+
+
+ 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 = await save_history(role, save_dir)
+
+ logger.exception(f"An error occurred: {e}, save trajectory here: {save_path}")
+
+
fire.Fire(main)