"In this notebook, we demonstrate how to use `AssistantAgent` and `UserProxyAgent` to write code and execute the code. Here `AssistantAgent` is an LLM-based agent that can write Python code (in a Python coding block) for a user to execute for a given task. `UserProxyAgent` is an agent which serves as a proxy for the human user to execute the code written by `AssistantAgent`, or automatically execute the code. Depending on the setting of `human_input_mode` and `max_consecutive_auto_reply`, the `UserProxyAgent` either solicits feedback from the human user or returns auto-feedback based on the result of code execution (success or failure and corresponding outputs) to `AssistantAgent`. `AssistantAgent` will debug the code and suggest new code if the result contains error. The two agents keep communicating to each other until the task is done.\n",
"In the example below, let's see how to use the agents in AutoGen to write a python script and execute the script. This process involves constructing a `AssistantAgent` to serve as the assistant, along with a `UserProxyAgent` that acts as a proxy for the human user. In this example demonstrated below, when constructing the `UserProxyAgent`, we select the `human_input_mode` to \"NEVER\". This means that the `UserProxyAgent` will not solicit feedback from the human user. It stops replying when the limit defined by `max_consecutive_auto_reply` is reached, or when `is_termination_msg()` returns true for the received message."
"Next, we need to fetch the stock prices for META (Facebook) and TESLA for the current year. We can use the `yfinance` library in Python to fetch this data. If `yfinance` is not installed, it can be installed using pip: `pip install yfinance`.\n",
"\n",
"Here is the Python code to fetch the stock prices and calculate the year-to-date gain:\n",
"This code fetches the closing prices for META and TESLA for the current year, calculates the year-to-date gain for each stock, and prints the results. The year-to-date gain is calculated as the percentage change in the closing price from the first trading day of the year to the most recent trading day.\n",
"I apologize for the oversight. The variable `today` was defined in the first code block but not in the second one. Let's correct this by defining `today` in the second code block as well. Here's the corrected code:\n",
"[*********************100%%**********************] 1 of 1 completed\n",
"\n",
"1 Failed download:\n",
"['FB']: Exception('%ticker%: No timezone found, symbol may be delisted')\n",
"/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
"[*********************100%%**********************] 1 of 1 completed\n",
"/Users/ekzhu/autogen/notebook/coding/tmp_code_9ca584c3d8b484c70ee49c1ce5e4b975.py:14: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`\n",
"I apologize for the confusion. It seems like the ticker symbol for Meta Platforms Inc. (formerly Facebook) has changed from 'FB' to 'META'. Let's correct this in the code. Also, it seems like the data for the current day might not be available yet, so let's fetch the data until the previous day. Here's the corrected code:\n",
"Code output: /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
"[*********************100%%**********************] 1 of 1 completed\n",
"/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
"[*********************100%%**********************] 1 of 1 completed\n",
"/Users/ekzhu/autogen/notebook/coding/tmp_code_0b52d7fcfe06d76c8b1e0ce9333cb5cf.py:14: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`\n",
"/Users/ekzhu/autogen/notebook/coding/tmp_code_0b52d7fcfe06d76c8b1e0ce9333cb5cf.py:15: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`\n",
"As of yesterday, the year-to-date gain for META (Meta Platforms Inc.) is approximately 50.11%, and for TESLA (Tesla Inc.) it is approximately -30.86%. This means that so far this year, META's stock price has increased by about 50.11% while TESLA's stock price has decreased by about 30.86%.\n",
"The example above involves code execution. In AutoGen, code execution is triggered automatically by the `UserProxyAgent` when it detects an executable code block in a received message and no human user input is provided. \n",
"Users have the option to specify a different working directory by setting the `work_dir` argument when constructing a new instance of the `LocalCommandLineCodeExecutor`.\n",
"For Docker-based or Jupyter kernel-based code execution, please refer to \n",
"[Code Executors Tutorial](/docs/tutorial/code-executors) for more information."
"The `initiate_chat` method returns a `ChatResult` object, which is a dataclass object storing information about the chat. Currently, it includes the following attributes:\n",
"\n",
"- `chat_history`: a list of chat history.\n",
"- `summary`: a string of chat summary. A summary is only available if a summary_method is provided when initiating the chat.\n",
"- `cost`: a tuple of (total_cost, total_actual_cost), where total_cost is a dictionary of cost information, and total_actual_cost is a dictionary of information on the actual incurred cost with cache.\n",
"- `human_input`: a list of strings of human inputs solicited during the chat. (Note that since we are setting `human_input_mode` to `NEVER` in this notebook, this list is always empty.)"
"Chat history: [{'content': 'What date is today? Compare the year-to-date gain for META and TESLA.', 'role': 'assistant'}, {'content': 'First, let\\'s get the current date using Python. \\n\\n```python\\n# Python code\\nfrom datetime import date\\n\\n# Get today\\'s date\\ntoday = date.today()\\n\\n# Print today\\'s date\\nprint(\"Today\\'s date:\", today)\\n```\\n\\nNext, we need to fetch the stock prices for META (Facebook) and TESLA for the current year. We can use the `yfinance` library in Python to fetch this data. If `yfinance` is not installed, it can be installed using pip: `pip install yfinance`.\\n\\nHere is the Python code to fetch the stock prices and calculate the year-to-date gain:\\n\\n```python\\n# Python code\\nimport yfinance as yf\\nfrom datetime import datetime\\n\\n# Get the current year\\ncurrent_year = datetime.now().year\\n\\n# Download stock data for the current year\\nmeta_data = yf.download(\\'FB\\', start=f\\'{current_year}-01-01\\', end=today)\\ntesla_data = yf.download(\\'TSLA\\', start=f\\'{current_year}-01-01\\', end=today)\\n\\n# Calculate the year-to-date gain for each stock\\nmeta_ytd_gain = ((meta_data[\\'Close\\'][-1] - meta_data[\\'Close\\'][0]) / meta_data[\\'Close\\'][0]) * 100\\ntesla_ytd_gain = ((tesla_data[\\'Close\\'][-1] - tesla_data[\\'Close\\'][0]) / tesla_data[\\'Close\\'][0]) * 100\\n\\n# Print the year-to-date gain for each stock\\nprint(f\\'META year-to-date gain: {meta_ytd_gain}%\\')\\nprint(f\\'TESLA year-to-date gain: {tesla_ytd_gain}%\\')\\n```\\n\\nThis code fetches the closing prices for META and TESLA for the current year, calculates the year-to-date gain for each stock, and prints the results. The year-to-date gain is calculated as the percentage change in the closing price from the first trading day of the year to the most recent trading day.', 'role': 'user'}, {'content': 'exitcode: 1 (execution failed)\\nCode output: Today\\'s date: 2024-04-12\\nTraceback (most recent call last):\\n File \"/Users/ekzhu/autogen/notebook/coding/tmp_code_cb9ef30baa23cf28e127198c0ebeb7e6.py\", line 9, in <module>\\n meta_data = yf.download(\\'FB\\', start=f\\'{current_year}-01-01\\', end=today)\\n ^^^^^\\nNameError: name \\'today\\' is not defined\\n', 'role': 'assistant'}, {'content': \"I apologize for the oversight. The variable `today` was defined in the first code block but not in the second one. Let's correct this by defining `today` in the second code block as well. Here's the corrected code:\\n\\n```python\\n# Python code\\nimport yfinance as yf\\nfrom datetime import datetime, date\\n\\n# Get the current year and today's date\\ncurrent_year = datetime.now().year\\ntoday = date.today()\\n\\n# Download stock data for the current year\\nmeta_data = yf.download('FB', start=f'{current_year}-01-01', end=today)\\ntesla_data = yf.download('TSLA', start=f'{current_year}-01-01', end=today)\\n\\n# Calculate the year-to-date gain for each stock\\nmeta_ytd_gain = ((meta_data['Close'][-1] - meta_data['Close'][0]) / meta_data['Close'][0]) * 100\\ntesla_ytd_gain = ((tesla_data['Close'][-1] - tesla_data['Close'][0]) / tesla_data['Close'][0]) * 100\\n\\n# Print the year-to-date gain for each stock\\nprint(f'META year-to-date gain: {meta_ytd_gain}%')\\nprint(f'TESLA year-to-date gain: {tesla_ytd_gain}%')\\n```\\n\\nThis code should now correctly fetch the stock prices for META and TESLA, calculate the year-to-date gain for each, and print the results.\", 'role': 'user'}, {'content': 'exitcode: 1 (execution failed)\\nCode output: \\n[*********************100%%**********************] 1 of 1 completed\\n\\n1 Failed download:\\n[\\'FB\\']: Exception(\\'%ticker%: No timezone found, symbol may be delisted\\')\\n/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The \\'unit\\' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\\n df.index += _pd.TimedeltaIndex(dst_error_hours, \\'h\\')\\n\\n[****
"Summary: The year-to-date gain for META (Meta Platforms Inc.) is approximately 50.11%, and for TESLA (Tesla Inc.) it is approximately -30.86%. This means that so far this year, META's stock price has increased by about 50.11% while TESLA's stock price has decreased by about 30.86%.\n",
"To plot a chart of the stock price change year-to-date (YTD) for META and TESLA, and to save the data and the plot, we can use the `matplotlib` and `pandas` libraries in Python. If these libraries are not installed, they can be installed using pip: `pip install matplotlib pandas`.\n",
"This code fetches the closing prices for META and TESLA for the current year, plots the closing prices, saves the plot to 'stock_price_ytd.png', and saves the closing prices to 'stock_price_ytd.csv'.\n",
"Code output: /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
"[*********************100%%**********************] 1 of 1 completed\n",
"/Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages/yfinance/utils.py:775: FutureWarning: The 'unit' keyword in TimedeltaIndex construction is deprecated and will be removed in a future version. Use pd.to_timedelta instead.\n",
"The code has successfully fetched the stock prices for META and TESLA, plotted the chart of their stock price change year-to-date (YTD), and saved the data to 'stock_price_ytd.csv' and the plot to 'stock_price_ytd.png'.\n",
" message=\"\"\"Plot a chart of their stock price change YTD. Save the data to stock_price_ytd.csv, and save the plot to stock_price_ytd.png.\"\"\",\n",
" with open(file_path, mode=\"r\", encoding=\"utf-8\") as file:\n",
" # Read each line in the file\n",
" for line in file:\n",
" # Split the line into a list using the comma as a separator\n",
" row = line.strip().split(\",\")\n",
" # Print the list representing the current row\n",
" print(row)\n",
"except FileNotFoundError:\n",
" print(\"File not found. Please check the file name and modify if necessary.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example Task: Use User Defined Message Function to let Agents Analyze data Collected\n",
"\n",
"Let's create a user defined message to let the agents analyze the raw data and write a blogpost. The function is supposed to take `sender`, `recipient` and `context` as inputs and outputs a string of message.\n",
"\n",
"**kwargs from `initiate_chat` will be used as `context`. Take the following code as an example, the `context` includes a field `file_name` as provided in `initiate_chat`. In the user defined message function `my_message_generator`, we are reading data from the file specified by this filename.\n"
"To analyze this data and write a blog post, we first need to load the data into a pandas DataFrame, then perform some basic analysis on it. We can then use the results of this analysis to write the blog post.\n",
"After running this code, we can use the results to write the blog post. Here is a possible blog post based on the results:\n",
"\n",
"---\n",
"\n",
"Title: A Comparative Analysis of META and TESLA Stocks in Early 2024\n",
"\n",
"In the first quarter of 2024, the stock market saw some interesting movements in the tech sector. Two companies that stood out during this period were META and TESLA. \n",
"\n",
"META, the social media giant, had an average stock price of [META Mean] during this period. The highest it reached was [META Max], while the lowest was [META Min]. The standard deviation, a measure of how spread out the prices were, was [META Std].\n",
"\n",
"On the other hand, TESLA, the electric vehicle and clean energy company, had an average stock price of [TESLA Mean]. The stock reached a high of [TESLA Max] and a low of [TESLA Min]. The standard deviation for TESLA was [TESLA Std].\n",
"\n",
"These figures show that both META and TESLA had their ups and downs during this period. However, the higher standard deviation for [Company with higher Std] indicates that its stock price fluctuated more compared to [Company with lower Std].\n",
"\n",
"As we move further into 2024, it will be interesting to see how these trends evolve. Will META and TESLA continue on their current trajectories, or will we see a shift in the market dynamics? Only time will tell.\n",
"\n",
"---\n",
"\n",
"Please replace [META Mean], [META Max], [META Min], [META Std], [TESLA Mean], [TESLA Max], [TESLA Min], [TESLA Std], [Company with higher Std], and [Company with lower Std] with the actual values obtained from the Python code.\n",
"In the first quarter of 2024, the stock market saw some interesting movements in the tech sector. Two companies that stood out during this period were META and TESLA. \n",
"META, the social media giant, had an average stock price of 403.53 during this period. The highest it reached was 519.83, while the lowest was 344.47. The standard deviation, a measure of how spread out the prices were, was 100.72.\n",
"On the other hand, TESLA, the electric vehicle and clean energy company, had an average stock price of 219.54. The stock reached a high of 248.42 and a low of 171.76. The standard deviation for TESLA was 41.68.\n",
"These figures show that both META and TESLA had their ups and downs during this period. However, the higher standard deviation for META indicates that its stock price fluctuated more compared to TESLA.\n",
"As we move further into 2024, it will be interesting to see how these trends evolve. Will META and TESLA continue on their current trajectories, or will we see a shift in the market dynamics? Only time will tell.\n",
"This blog post provides a brief but engaging analysis of the META and TESLA stocks based on the provided data. It highlights the mean, max, min, and standard deviation of the stock prices for both companies, and provides some commentary on what these figures might mean for the future.\n",
"In the first quarter of 2024, the stock market saw some interesting movements in the tech sector. Two companies that stood out during this period were META and TESLA. \n",
"META, the social media giant, had an average stock price of 403.53 during this period. The highest it reached was 519.83, while the lowest was 344.47. The standard deviation, a measure of how spread out the prices were, was 100.72.\n",
"On the other hand, TESLA, the electric vehicle and clean energy company, had an average stock price of 219.54. The stock reached a high of 248.42 and a low of 171.76. The standard deviation for TESLA was 41.68.\n",
"These figures show that both META and TESLA had their ups and downs during this period. However, the higher standard deviation for META indicates that its stock price fluctuated more compared to TESLA.\n",
"As we move further into 2024, it will be interesting to see how these trends evolve. Will META and TESLA continue on their current trajectories, or will we see a shift in the market dynamics? Only time will tell.\n",
"In the first quarter of 2024, the stock market saw some interesting movements in the tech sector. Two companies that stood out during this period were META and TESLA. \n",
"META, the social media giant, had an average stock price of 403.53 during this period. The highest it reached was 519.83, while the lowest was 344.47. The standard deviation, a measure of how spread out the prices were, was 100.72.\n",
"On the other hand, TESLA, the electric vehicle and clean energy company, had an average stock price of 219.54. The stock reached a high of 248.42 and a low of 171.76. The standard deviation for TESLA was 41.68.\n",
"\n",
"These figures show that both META and TESLA had their ups and downs during this period. However, the higher standard deviation for META indicates that its stock price fluctuated more compared to TESLA.\n",
"\n",
"As we move further into 2024, it will be interesting to see how these trends evolve. Will META and TESLA continue on their current trajectories, or will we see a shift in the market dynamics? Only time will tell."
"description": "Use conversable language learning model agents to solve tasks and provide automatic feedback through a comprehensive example of writing, executing, and debugging Python code to compare stock price changes.",