main.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. import pandas as pd
  2. import os
  3. from crewai import Agent, Task, Crew
  4. from langchain_groq import ChatGroq
  5. def main():
  6. """
  7. Main function to initialize and run the CrewAI Machine Learning Assistant.
  8. This function sets up a machine learning assistant using the Llama 3 model with the ChatGroq API.
  9. It provides a text-based interface for users to define, assess, and solve machine learning problems
  10. by interacting with multiple specialized AI agents. The function outputs the results to the console
  11. and writes them to a markdown file.
  12. Steps:
  13. 1. Initialize the ChatGroq API with the specified model and API key.
  14. 2. Display introductory text about the CrewAI Machine Learning Assistant.
  15. 3. Create and configure four AI agents:
  16. - Problem_Definition_Agent: Clarifies the machine learning problem.
  17. - Data_Assessment_Agent: Evaluates the quality and suitability of the provided data.
  18. - Model_Recommendation_Agent: Suggests suitable machine learning models.
  19. - Starter_Code_Generator_Agent: Generates starter Python code for the project.
  20. 4. Prompt the user to describe their machine learning problem.
  21. 5. Check if a .csv file is available in the current directory and try to read it as a DataFrame.
  22. 6. Define tasks for the agents based on user input and data availability.
  23. 7. Create a Crew instance with the agents and tasks, and run the tasks.
  24. 8. Print the results and write them to an output markdown file.
  25. """
  26. model = 'llama3-8b-8192'
  27. llm = ChatGroq(
  28. temperature=0,
  29. groq_api_key = os.getenv('GROQ_API_KEY'),
  30. model_name=model
  31. )
  32. print('CrewAI Machine Learning Assistant')
  33. multiline_text = """
  34. The CrewAI Machine Learning Assistant is designed to guide users through the process of defining, assessing, and solving machine learning problems. It leverages a team of AI agents, each with a specific role, to clarify the problem, evaluate the data, recommend suitable models, and generate starter Python code. Whether you're a seasoned data scientist or a beginner, this application provides valuable insights and a head start in your machine learning projects.
  35. """
  36. print(multiline_text)
  37. Problem_Definition_Agent = Agent(
  38. role='Problem_Definition_Agent',
  39. goal="""clarify the machine learning problem the user wants to solve,
  40. identifying the type of problem (e.g., classification, regression) and any specific requirements.""",
  41. backstory="""You are an expert in understanding and defining machine learning problems.
  42. Your goal is to extract a clear, concise problem statement from the user's input,
  43. ensuring the project starts with a solid foundation.""",
  44. verbose=True,
  45. allow_delegation=False,
  46. llm=llm,
  47. )
  48. Data_Assessment_Agent = Agent(
  49. role='Data_Assessment_Agent',
  50. goal="""evaluate the data provided by the user, assessing its quality,
  51. suitability for the problem, and suggesting preprocessing steps if necessary.""",
  52. backstory="""You specialize in data evaluation and preprocessing.
  53. Your task is to guide the user in preparing their dataset for the machine learning model,
  54. including suggestions for data cleaning and augmentation.""",
  55. verbose=True,
  56. allow_delegation=False,
  57. llm=llm,
  58. )
  59. Model_Recommendation_Agent = Agent(
  60. role='Model_Recommendation_Agent',
  61. goal="""suggest the most suitable machine learning models based on the problem definition
  62. and data assessment, providing reasons for each recommendation.""",
  63. backstory="""As an expert in machine learning algorithms, you recommend models that best fit
  64. the user's problem and data. You provide insights into why certain models may be more effective than others,
  65. considering classification vs regression and supervised vs unsupervised frameworks.""",
  66. verbose=True,
  67. allow_delegation=False,
  68. llm=llm,
  69. )
  70. Starter_Code_Generator_Agent = Agent(
  71. role='Starter_Code_Generator_Agent',
  72. goal="""generate starter Python code for the project, including data loading,
  73. model definition, and a basic training loop, based on findings from the problem definitions,
  74. data assessment and model recommendation""",
  75. backstory="""You are a code wizard, able to generate starter code templates that users
  76. can customize for their projects. Your goal is to give users a head start in their coding efforts.""",
  77. verbose=True,
  78. allow_delegation=False,
  79. llm=llm,
  80. )
  81. user_question = input("Describe your ML problem: ")
  82. data_upload = False
  83. # Check if there is a .csv file in the current directory
  84. if any(file.endswith(".csv") for file in os.listdir()):
  85. sample_fp = [file for file in os.listdir() if file.endswith(".csv")][0]
  86. try:
  87. # Attempt to read the uploaded file as a DataFrame
  88. df = pd.read_csv(sample_fp).head(5)
  89. # If successful, set 'data_upload' to True
  90. data_upload = True
  91. # Display the DataFrame in the app
  92. print("Data successfully uploaded and read as DataFrame:")
  93. print(df)
  94. except Exception as e:
  95. print(f"Error reading the file: {e}")
  96. if user_question:
  97. task_define_problem = Task(
  98. description="""Clarify and define the machine learning problem,
  99. including identifying the problem type and specific requirements.
  100. Here is the user's problem:
  101. {ml_problem}
  102. """.format(ml_problem=user_question),
  103. agent=Problem_Definition_Agent,
  104. expected_output="A clear and concise definition of the machine learning problem."
  105. )
  106. if data_upload:
  107. task_assess_data = Task(
  108. description="""Evaluate the user's data for quality and suitability,
  109. suggesting preprocessing or augmentation steps if needed.
  110. Here is a sample of the user's data:
  111. {df}
  112. The file name is called {uploaded_file}
  113. """.format(df=df.head(),uploaded_file=sample_fp),
  114. agent=Data_Assessment_Agent,
  115. expected_output="An assessment of the data's quality and suitability, with suggestions for preprocessing or augmentation if necessary."
  116. )
  117. else:
  118. task_assess_data = Task(
  119. description="""The user has not uploaded any specific data for this problem,
  120. but please go ahead and consider a hypothetical dataset that might be useful
  121. for their machine learning problem.
  122. """,
  123. agent=Data_Assessment_Agent,
  124. expected_output="A hypothetical dataset that might be useful for the user's machine learning problem, along with any necessary preprocessing steps."
  125. )
  126. task_recommend_model = Task(
  127. description="""Suggest suitable machine learning models for the defined problem
  128. and assessed data, providing rationale for each suggestion.""",
  129. agent=Model_Recommendation_Agent,
  130. expected_output="A list of suitable machine learning models for the defined problem and assessed data, along with the rationale for each suggestion."
  131. )
  132. task_generate_code = Task(
  133. description="""Generate starter Python code tailored to the user's project using the model recommendation agent's recommendation(s),
  134. including snippets for package import, data handling, model definition, and training
  135. """,
  136. agent=Starter_Code_Generator_Agent,
  137. expected_output="Python code snippets for package import, data handling, model definition, and training, tailored to the user's project, plus a brief summary of the problem and model recommendations."
  138. )
  139. crew = Crew(
  140. agents=[Problem_Definition_Agent, Data_Assessment_Agent, Model_Recommendation_Agent, Starter_Code_Generator_Agent],
  141. tasks=[task_define_problem, task_assess_data, task_recommend_model, task_generate_code],
  142. verbose=False
  143. )
  144. result = crew.kickoff()
  145. print(result)
  146. with open('output.md', "w") as file:
  147. print('\n\nThese results have been exported to output.md')
  148. file.write(result)
  149. if __name__ == "__main__":
  150. main()