2023-05-27 23:17:23 -04:00
{
"cells": [
2023-06-09 11:40:04 -07:00
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"<a href=\"https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/autogen_agent_auto_feedback_from_code_execution.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
2023-05-27 23:17:23 -04:00
{
"attachments": {},
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
2023-06-09 11:40:04 -07:00
"# Interactive LLM Agent with Auto Feedback from Code Execution\n",
2023-05-27 23:17:23 -04:00
"\n",
2023-06-09 11:40:04 -07:00
"FLAML offers an experimental feature of interactive LLM agents, which can be used to solve various tasks with human or automatic feedback, including tasks that require using tools via code.\n",
2023-07-23 06:23:09 -07:00
"Please find documentation about this feature [here](https://microsoft.github.io/FLAML/docs/Use-Cases/Auto-Generation#agents-experimental).\n",
2023-05-27 23:17:23 -04:00
"\n",
2023-06-09 11:40:04 -07:00
"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 uses auto-feedback based on the result of code execution. For example, when `human_input_mode` is set to \"ALWAYS\", the `UserProxyAgent` will always prompt the user for feedback. When user feedback is provided, the `UserProxyAgent` will directly pass the feedback to `AssistantAgent` without doing any additional steps. When no user feedback is provided, the `UserProxyAgent` will execute the code written by `AssistantAgent` directly and return the execution results (success or failure and corresponding outputs) to `AssistantAgent`.\n",
2023-05-27 23:17:23 -04:00
"\n",
"## Requirements\n",
"\n",
2023-07-08 22:25:43 -07:00
"FLAML requires `Python>=3.8`. To run this notebook example, please install flaml with the [autogen] option:\n",
2023-05-27 23:17:23 -04:00
"```bash\n",
"pip install flaml[autogen]\n",
"```"
]
},
{
"cell_type": "code",
2023-06-09 11:40:04 -07:00
"execution_count": 1,
2023-05-27 23:17:23 -04:00
"metadata": {
"execution": {
"iopub.execute_input": "2023-02-13T23:40:52.317406Z",
"iopub.status.busy": "2023-02-13T23:40:52.316561Z",
"iopub.status.idle": "2023-02-13T23:40:52.321193Z",
"shell.execute_reply": "2023-02-13T23:40:52.320628Z"
}
},
"outputs": [],
"source": [
2023-07-17 20:40:41 -07:00
"# %pip install flaml[autogen]~=2.0.0rc4"
2023-05-27 23:17:23 -04:00
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"## Set your API Endpoint\n",
"\n",
2023-07-23 06:23:09 -07:00
"The [`config_list_from_json`](https://microsoft.github.io/FLAML/docs/reference/autogen/oai/openai_utils#config_list_from_json) function loads a list of configurations from an environment variable or a json file.\n"
2023-05-27 23:17:23 -04:00
]
},
{
"cell_type": "code",
2023-06-09 11:40:04 -07:00
"execution_count": 2,
2023-05-27 23:17:23 -04:00
"metadata": {},
"outputs": [],
"source": [
"from flaml import oai\n",
"\n",
2023-07-23 06:23:09 -07:00
"config_list = oai.config_list_from_json(\n",
" \"OAI_CONFIG_LIST\",\n",
" filter_dict={\n",
" \"model\": [\"gpt-4\", \"gpt4\", \"gpt-4-32k\", \"gpt-4-32k-0314\"],\n",
" },\n",
")"
2023-05-27 23:17:23 -04:00
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
2023-07-23 06:23:09 -07:00
"It first looks for environment variable \"OAI_CONFIG_LIST\" which needs to be a valid json string. If that variable is not found, it then looks for a json file named \"OAI_CONFIG_LIST\". It filters the configs by models (you can filter by other keys as well). Only the gpt-4 models are kept in the list based on the filter condition.\n",
"\n",
2023-06-09 11:40:04 -07:00
"The config list looks like the following:\n",
"```python\n",
"config_list = [\n",
" {\n",
" 'model': 'gpt-4',\n",
" 'api_key': '<your OpenAI API key here>',\n",
2023-07-23 06:23:09 -07:00
" },\n",
2023-06-09 11:40:04 -07:00
" {\n",
" 'model': 'gpt-4',\n",
2023-07-23 06:23:09 -07:00
" 'api_key': '<your Azure OpenAI API key here>',\n",
" 'api_base': '<your Azure OpenAI API base here>',\n",
2023-06-09 11:40:04 -07:00
" 'api_type': 'azure',\n",
2023-07-23 06:23:09 -07:00
" 'api_version': '2023-06-01-preview',\n",
" },\n",
2023-06-09 11:40:04 -07:00
" {\n",
2023-07-23 06:23:09 -07:00
" 'model': 'gpt-4-32k',\n",
" 'api_key': '<your Azure OpenAI API key here>',\n",
" 'api_base': '<your Azure OpenAI API base here>',\n",
2023-06-09 11:40:04 -07:00
" 'api_type': 'azure',\n",
2023-07-23 06:23:09 -07:00
" 'api_version': '2023-06-01-preview',\n",
" },\n",
2023-06-09 11:40:04 -07:00
"]\n",
"```\n",
2023-05-27 23:17:23 -04:00
"\n",
2023-07-23 06:23:09 -07:00
"If you open this notebook in colab, you can upload your files by clicking the file icon on the left panel and then choose \"upload file\" icon.\n",
"\n",
"You can set the value of config_list in other ways you prefer, e.g., loading from a YAML file."
2023-06-09 11:40:04 -07:00
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
2023-07-14 15:52:45 -07:00
"## Example Task: Check Stock Price Change\n",
2023-06-09 11:40:04 -07:00
"\n",
"In the example below, let's see how to use the agents in FLAML 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."
2023-05-27 23:17:23 -04:00
]
},
{
"cell_type": "code",
2023-06-09 11:40:04 -07:00
"execution_count": 3,
2023-05-27 23:17:23 -04:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
2023-06-09 11:40:04 -07:00
"user (to assistant):\n",
2023-05-27 23:17:23 -04:00
"\n",
2023-07-14 15:52:45 -07:00
"What date is today? Compare the year-to-date gain for META and TESLA.\n",
2023-05-27 23:17:23 -04:00
"\n",
2023-07-25 16:46:11 -07:00
"--------------------------------------------------------------------------------\n",
2023-06-09 11:40:04 -07:00
"assistant (to user):\n",
2023-07-08 22:25:43 -07:00
"\n",
2023-07-14 15:52:45 -07:00
"# filename: stock_comparison.py\n",
2023-07-23 06:23:09 -07:00
"```python\n",
2023-07-14 15:52:45 -07:00
"import datetime\n",
"import yfinance as yf\n",
2023-07-10 09:07:48 -07:00
"\n",
2023-07-14 15:52:45 -07:00
"# Get today's date\n",
"today = datetime.date.today()\n",
"print(\"Today's date:\", today)\n",
2023-07-10 09:07:48 -07:00
"\n",
2023-07-23 06:23:09 -07:00
"# Get the start of the year\n",
"start_of_year = datetime.date(today.year, 1, 1)\n",
2023-05-27 23:17:23 -04:00
"\n",
2023-07-23 06:23:09 -07:00
"# Download the historical data for META and TESLA\n",
"meta_data = yf.download('META', start=start_of_year, end=today)\n",
"tesla_data = yf.download('TSLA', start=start_of_year, end=today)\n",
2023-07-10 09:07:48 -07:00
"\n",
2023-07-23 06:23:09 -07:00
"# Calculate the year-to-date gain for META and TESLA\n",
2023-07-14 15:52:45 -07:00
"meta_gain = (meta_data['Close'][-1] - meta_data['Close'][0]) / meta_data['Close'][0]\n",
"tesla_gain = (tesla_data['Close'][-1] - tesla_data['Close'][0]) / tesla_data['Close'][0]\n",
2023-07-10 09:07:48 -07:00
"\n",
2023-07-23 06:23:09 -07:00
"# Print the year-to-date gain for META and TESLA\n",
"print(\"Year-to-date gain for META:\", round(meta_gain * 100, 2), \"%\")\n",
"print(\"Year-to-date gain for TESLA:\", round(tesla_gain * 100, 2), \"%\")\n",
2023-07-10 09:07:48 -07:00
"```\n",
2023-07-23 06:23:09 -07:00
"Please save this code in a file named `stock_comparison.py` and run it. This script will print today's date and compare the year-to-date gain for META and TESLA. It uses the `yfinance` library to download the historical data for the stocks. If you haven't installed `yfinance`, please install it by running `pip install yfinance`.\n",
2023-07-10 09:07:48 -07:00
"\n",
"--------------------------------------------------------------------------------\n",
"\n",
2023-07-25 16:46:11 -07:00
">>>>>>>> USING AUTO REPLY FOR THE USER...\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
2023-07-10 09:07:48 -07:00
"user (to assistant):\n",
"\n",
2023-07-14 15:52:45 -07:00
"exitcode: 0 (execution succeeded)\n",
2023-07-10 09:07:48 -07:00
"Code output: \n",
2023-07-25 16:46:11 -07:00
"Today's date: 2023-07-24\n",
2023-07-23 06:23:09 -07:00
"[*********************100%***********************] 1 of 1 completed\n",
"[*********************100%***********************] 1 of 1 completed\n",
"Year-to-date gain for META: 135.9 %\n",
"Year-to-date gain for TESLA: 140.54 %\n",
2023-05-27 23:17:23 -04:00
"\n",
"\n",
2023-07-08 22:25:43 -07:00
"--------------------------------------------------------------------------------\n",
2023-06-09 11:40:04 -07:00
"assistant (to user):\n",
"\n",
2023-07-25 16:46:11 -07:00
"Great! The script has successfully executed and provided the year-to-date gain for both META and TESLA stocks. As of today's date (July 24, 2023), the year-to-date gain for META is 135.9%, and for TESLA, it's 140.54%. \n",
2023-07-10 09:07:48 -07:00
"\n",
2023-07-25 16:46:11 -07:00
"Please let me know if you need help with anything else. \n",
2023-07-08 22:25:43 -07:00
"\n",
"TERMINATE\n",
2023-05-27 23:17:23 -04:00
"\n",
2023-07-08 22:25:43 -07:00
"--------------------------------------------------------------------------------\n"
2023-05-27 23:17:23 -04:00
]
}
],
"source": [
2023-06-09 11:40:04 -07:00
"from flaml.autogen.agent import AssistantAgent, UserProxyAgent\n",
2023-05-27 23:17:23 -04:00
"\n",
2023-06-09 11:40:04 -07:00
"# create an AssistantAgent named \"assistant\"\n",
2023-07-14 15:52:45 -07:00
"assistant = AssistantAgent(\n",
" \"assistant\",\n",
2023-07-25 16:46:11 -07:00
" oai_config={\n",
" \"seed\": 42,\n",
" \"config_list\": config_list,\n",
" \"temperature\": 0,\n",
" }\n",
2023-07-14 15:52:45 -07:00
")\n",
2023-05-27 23:17:23 -04:00
"# create a UserProxyAgent instance named \"user\"\n",
"user = UserProxyAgent(\n",
" \"user\",\n",
" human_input_mode=\"NEVER\",\n",
" max_consecutive_auto_reply=10,\n",
2023-07-06 06:08:44 +08:00
" is_termination_msg=lambda x: x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\") or x.get(\"content\", \"\").rstrip().endswith('\"TERMINATE\".'),\n",
2023-07-23 06:23:09 -07:00
" code_execution_config={\n",
" \"work_dir\": \"coding\",\n",
" \"use_docker\": False, # set to True or image name like \"python:3\" to use docker\n",
" },\n",
2023-05-27 23:17:23 -04:00
")\n",
"# the assistant receives a message from the user, which contains the task description\n",
2023-07-17 20:40:41 -07:00
"user.initiate_chat(\n",
" assistant,\n",
2023-07-23 06:23:09 -07:00
" message=\"\"\"What date is today? Compare the year-to-date gain for META and TESLA.\"\"\",\n",
2023-05-27 23:17:23 -04:00
")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
2023-07-14 15:52:45 -07:00
"The example above involves code execution. In FLAML, 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. This process occurs in a designated working directory, using a Docker container by default. Unless a specific directory is specified, FLAML defaults to the `flaml/autogen/extensions` directory. Users have the option to specify a different working directory by setting the `work_dir` argument when constructing a new instance of the `UserProxyAgent`.\n"
2023-05-27 23:17:23 -04:00
]
},
{
2023-07-14 15:52:45 -07:00
"attachments": {},
"cell_type": "markdown",
2023-05-27 23:17:23 -04:00
"metadata": {},
"source": [
2023-07-14 15:52:45 -07:00
"All the feedback is auto generated."
2023-05-27 23:17:23 -04:00
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
2023-07-14 15:52:45 -07:00
"## Example Task: Plot Chart"
2023-05-27 23:17:23 -04:00
]
},
{
"cell_type": "code",
2023-07-14 15:52:45 -07:00
"execution_count": 4,
2023-05-27 23:17:23 -04:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
2023-06-09 11:40:04 -07:00
"user (to assistant):\n",
2023-05-27 23:17:23 -04:00
"\n",
2023-07-14 15:52:45 -07:00
"Plot a chart of their stock price change YTD and save to stock_price_ytd.png.\n",
2023-05-27 23:17:23 -04:00
"\n",
2023-07-08 22:25:43 -07:00
"--------------------------------------------------------------------------------\n",
2023-06-09 11:40:04 -07:00
"assistant (to user):\n",
2023-07-08 22:25:43 -07:00
"\n",
2023-07-23 06:23:09 -07:00
"# filename: stock_plot.py\n",
2023-06-09 11:40:04 -07:00
"```python\n",
2023-07-23 06:23:09 -07:00
"import matplotlib.pyplot as plt\n",
2023-07-14 15:52:45 -07:00
"\n",
2023-07-23 06:23:09 -07:00
"# Plot the close price of META and TESLA\n",
2023-07-25 16:46:11 -07:00
"plt.figure(figsize=(14,7))\n",
2023-07-23 06:23:09 -07:00
"plt.plot(meta_data['Close'], label='META')\n",
"plt.plot(tesla_data['Close'], label='TESLA')\n",
"\n",
"# Set the title and labels\n",
2023-07-25 16:46:11 -07:00
"plt.title('Year-to-date stock price change for META and TESLA')\n",
2023-07-23 06:23:09 -07:00
"plt.xlabel('Date')\n",
"plt.ylabel('Close Price')\n",
"\n",
"# Show the legend\n",
"plt.legend()\n",
"\n",
2023-07-25 16:46:11 -07:00
"# Save the plot as a PNG file\n",
2023-07-23 06:23:09 -07:00
"plt.savefig('stock_price_ytd.png')\n",
"```\n",
2023-07-25 16:46:11 -07:00
"Please save this code in a file named `stock_plot.py` and run it. This script will plot the year-to-date stock price change for META and TESLA and save the plot as a PNG file named `stock_price_ytd.png`. It uses the `matplotlib` library to create the plot. If you haven't installed `matplotlib`, please install it by running `pip install matplotlib`.\n",
2023-07-23 06:23:09 -07:00
"\n",
"--------------------------------------------------------------------------------\n",
"\n",
">>>>>>>> USING AUTO REPLY FOR THE USER...\n",
"user (to assistant):\n",
"\n",
"exitcode: 1 (execution failed)\n",
"Code output: \n",
"Traceback (most recent call last):\n",
2023-07-25 16:46:11 -07:00
" File \"/workspaces/FLAML/notebook/coding/tmp_code_0e68902a38546d82fddf9b82f39278e3.py\", line 5, in <module>\n",
2023-07-23 06:23:09 -07:00
" plt.plot(meta_data['Close'], label='META')\n",
"NameError: name 'meta_data' is not defined\n",
"\n",
"\n",
"--------------------------------------------------------------------------------\n",
"assistant (to user):\n",
"\n",
2023-07-25 16:46:11 -07:00
"I apologize for the oversight. The error occurred because the `meta_data` and `tesla_data` variables, which hold the stock data, were not defined in this script. We need to fetch the stock data again in this script. Here is the corrected code:\n",
2023-07-23 06:23:09 -07:00
"\n",
2023-07-25 16:46:11 -07:00
"# filename: stock_plot.py\n",
2023-07-23 06:23:09 -07:00
"```python\n",
2023-07-10 09:07:48 -07:00
"import datetime\n",
2023-06-09 11:40:04 -07:00
"import yfinance as yf\n",
2023-07-14 15:52:45 -07:00
"import matplotlib.pyplot as plt\n",
"\n",
"# Get today's date\n",
"today = datetime.date.today()\n",
"\n",
2023-07-23 06:23:09 -07:00
"# Get the start of the year\n",
"start_of_year = datetime.date(today.year, 1, 1)\n",
2023-07-14 15:52:45 -07:00
"\n",
2023-07-23 06:23:09 -07:00
"# Download the historical data for META and TESLA\n",
"meta_data = yf.download('META', start=start_of_year, end=today)\n",
"tesla_data = yf.download('TSLA', start=start_of_year, end=today)\n",
2023-07-14 15:52:45 -07:00
"\n",
2023-07-23 06:23:09 -07:00
"# Plot the close price of META and TESLA\n",
2023-07-25 16:46:11 -07:00
"plt.figure(figsize=(14,7))\n",
2023-07-14 15:52:45 -07:00
"plt.plot(meta_data['Close'], label='META')\n",
"plt.plot(tesla_data['Close'], label='TESLA')\n",
2023-07-23 06:23:09 -07:00
"\n",
"# Set the title and labels\n",
2023-07-25 16:46:11 -07:00
"plt.title('Year-to-date stock price change for META and TESLA')\n",
2023-07-14 15:52:45 -07:00
"plt.xlabel('Date')\n",
2023-07-23 06:23:09 -07:00
"plt.ylabel('Close Price')\n",
"\n",
"# Show the legend\n",
2023-07-14 15:52:45 -07:00
"plt.legend()\n",
"\n",
2023-07-25 16:46:11 -07:00
"# Save the plot as a PNG file\n",
2023-07-14 15:52:45 -07:00
"plt.savefig('stock_price_ytd.png')\n",
2023-06-09 11:40:04 -07:00
"```\n",
2023-07-25 16:46:11 -07:00
"Please save this code in a file named `stock_plot.py` and run it. This script will plot the year-to-date stock price change for META and TESLA and save the plot as a PNG file named `stock_price_ytd.png`.\n",
2023-05-27 23:17:23 -04:00
"\n",
2023-07-08 22:25:43 -07:00
"--------------------------------------------------------------------------------\n",
2023-05-27 23:17:23 -04:00
"\n",
2023-07-23 06:23:09 -07:00
">>>>>>>> USING AUTO REPLY FOR THE USER...\n",
2023-06-09 11:40:04 -07:00
"user (to assistant):\n",
2023-07-08 22:25:43 -07:00
"\n",
2023-07-10 09:07:48 -07:00
"exitcode: 0 (execution succeeded)\n",
2023-06-09 11:40:04 -07:00
"Code output: \n",
2023-07-23 06:23:09 -07:00
"[*********************100%***********************] 1 of 1 completed\n",
"[*********************100%***********************] 1 of 1 completed\n",
2023-07-10 09:07:48 -07:00
"\n",
"\n",
"--------------------------------------------------------------------------------\n",
"assistant (to user):\n",
"\n",
2023-07-25 16:46:11 -07:00
"Great! The script has successfully executed and the plot of the year-to-date stock price change for META and TESLA has been saved as a PNG file named `stock_price_ytd.png`. You can find this file in the same directory where you ran the script.\n",
2023-07-14 15:52:45 -07:00
"\n",
2023-07-25 16:46:11 -07:00
"Please let me know if you need help with anything else.\n",
2023-07-14 15:52:45 -07:00
"\n",
2023-07-10 09:07:48 -07:00
"TERMINATE\n",
"\n",
"--------------------------------------------------------------------------------\n"
]
}
],
"source": [
2023-07-14 15:52:45 -07:00
"# followup of the previous question\n",
2023-07-17 20:40:41 -07:00
"user.send(\n",
" recipient=assistant,\n",
" message=\"\"\"Plot a chart of their stock price change YTD and save to stock_price_ytd.png.\"\"\",\n",
2023-07-10 09:07:48 -07:00
")"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
2023-07-14 15:52:45 -07:00
"Let's display the generated figure."
2023-07-10 09:07:48 -07:00
]
},
{
"cell_type": "code",
2023-07-14 15:52:45 -07:00
"execution_count": 5,
2023-07-10 09:07:48 -07:00
"metadata": {},
"outputs": [
{
2023-07-14 15:52:45 -07:00
"data": {
2023-07-25 16:46:11 -07:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAABXgAAAK8CAYAAABV1dcbAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8pXeV/AAAACXBIWXMAAA9hAAAPYQGoP6dpAAEAAElEQVR4nOzdd1yVdf/H8ffhsPcQBAURcCLulZZaampqpWbDsrRlw+67Xb+22bC677tdtsyWNixbVpqVI7fm3gu3iIAMQea5fn9ccpJABQQOB17Px4PHubiu61zX5xyQ8u2Hz9diGIYhAAAAAAAAAIDTcXF0AQAAAAAAAACAyiHgBQAAAAAAAAAnRcALAAAAAAAAAE6KgBcAAAAAAAAAnBQBLwAAAAAAAAA4KQJeAAAAAAAAAHBSBLwAAAAAAAAA4KQIeAEAAAAAAADASRHwAgAAAAAAAICTIuAFAAAAAAAAACdFwAsAAAAAAAAAToqAFwAAAAAAAACcFAEvAAAAAAAAADgpAl4AAAAAAAAAcFIEvAAAAAAAAADgpAh4AQAAAAAAAMBJEfACAAAAAAAAgJMi4AUAAAAAAAAAJ0XACwAAAAAAAABOioAXAAAAAAAAAJwUAS8AAAAAAAAAOCkCXgAAAAAAAABwUgS8AAAAAAAAAOCkCHgBAAAAAAAAwEkR8AIAAAAAAACAkyLgBQAAAAAAAAAnRcALAAAAAAAAAE6KgBcAAAAAAAAAnBQBLwAAAAAAAAA4KQJeAAAAAAAAAHBSBLwAAAAAAAAA4KQIeAEAAAAAAADASRHwAgAAAAAAAICTIuAFAAAAAAAAACdFwAsAAAAAAAAAToqAFwAAAAAAAAC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Tywxli38up6WlqUuXLsrMzNRNN92kVq1aKTU1VevXr9fkyZN1xx13VLr7f8aMGbJYLAoPD9e0adP07LPPVuo6AACgJAJeAADqiJiYGD311FN6+OGHNXbsWA0YMECStHLlSr3zzjt64IEH1L59+2qtITc3V+7u7g4LkVH7FRYWymazyd3dXZ6eno4up95KTk6WpCr9x5acnBx5e3uf8ZzBgweXGfBOnz5dQ4YM0TfffFPm8zp16qTRo0ef9rqxsbElPr/99tsVGxt72ud89tlnCgsL0//+9z+NHDlSe/bscbp/UImNja3w65akkSNHqkGDBqc9PmXKFO3bt0+LFy9Wz549SxzLzMyUu7t7pWv+7LPPNHjwYEVHR2v69OkEvAAAVBH+9gUAQB1y3333qV27drrzzjuVm5uroqIi3X777YqOjtZTTz2lrVu3auTIkQoODpanp6e6dOmiH374ocQ10tLS9MADD6ht27by9fWVv7+/LrnkEq1bt67EefPnz5fFYtEXX3yhxx9/XI0bN5a3t7cyMzNL1TVhwgQ9+OCDkswguvhXgovHEBQWFuqZZ55RXFycPDw81LRpUz366KPKy8sr92t/7733FBcXJy8vL3Xr1k1//vlnqXPy8/P15JNPqnPnzgoICJCPj4969eqlefPm2c/Zs2ePQkNDJUlPP/20vdYJEybYzynP+3g6X3zxhTp37iw/Pz/5+/urbdu2eu211ySZv3J95ZVXSpIuuugi+71PHRXx9ttvq02bNvLw8FCjRo00fvz4MsdeLF++XIMHD1ZQUJB8fHzUrl07+31OZ+3atQoNDdWFF15Y4tew/6n417J3796tgQMHysfHR40aNdLEiRNlGIb9vOJfr//vf/+rV1991f713bx582ln8G7dulVXXXWVQkND5eXlpZYtW+qxxx4rcc7Bgwd10003qWHDhvLw8FCbNm304YcfnvG1neqzzz5Tt27d5O3traCgIPXu3Vu//vprqfMWLVqkbt26ydPTU7Gxsfrkk09KHK/on5WvvvpKzz33nCIjI+Xp6al+/fpp586dpe771ltvKTY2tsT3clnzpPPy8vTUU0+pWbNm8vDwUFRUlB566KGz/rlp2rSpnnrqKUlSaGhoqe/v8nyPXXjhhUpISNBff/2l3r17y9vbW48++ugZ7ytJ1157rdauXautW7fa9yUlJemPP/7Qtddee9bnV5Xp06dr5MiRGjp0qAICAkr91sPplOdniFTye7/4Z5OHh4e6du2qlStXlrrud999p4SEBHl6eiohIUHffvttlbzOyti1a5esVqvOO++8Usf8/f0r/Q8z+/bt059//qlrrrlG11xzjRITE7VkyZJzLRcAAIgOXgAA6hRXV1e999576tmzp5555hmFhYVp9erVmj17thITE3X++eercePG+r//+z/5+Pjoq6++0rBhw/TNN99o+PDhkqTdu3fru+++05VXXqmYmBgdOXJE7777rvr06aPNmzerUaNGJe75zDPPyN3dXQ888IDy8vLK7O4aMWKEtm/frs8//1yvvPKKvXusOEi95ZZb9PHHH2vkyJG6//77tXz5ck2aNElbtmwpV9AxZcoU3XbbberZs6fuuece7d69W5dddpmCg4MVFRVlPy8zM1MffPCBRo0apVtvvVVZWVmaMmWKBg4cqBUrVqhDhw4KDQ21/xry8OHDNWLECElSu3btJEmbNm0q1/tYlrlz52rUqFHq16+fXnzxRUnSli1btHjxYt19993q3bu3/v3vf+v111/Xo48+qtatW0uS/XHChAl6+umn1b9/f91xxx3atm2bJk+erJUrV2rx4sX2cQdz587V0KFDFRERobvvvlvh4eHasmWLZs2apbvvvrvM2lauXKmBAweqS5cu+v777+Xl5XXG97yoqEiDBg3Seeedp5deekmzZ8/WU089pcLCQk2cOLHEuVOnTlVubq7GjRsnDw8PBQcHlzkLev369erVq5fc3Nw0btw4NW3aVLt27dKPP/6o5557TpJ05MgRnXfeefZZraGhofrll1908803KzMzU/fcc88Z63766ac1YcIE9ezZUxMnTpS7u7uWL1+uP/74w971Lkk7d+7UyJEjdfPNN2vMmDH68MMPNXb
2023-07-14 15:52:45 -07:00
"text/plain": [
"<IPython.core.display.Image object>"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
2023-05-27 23:17:23 -04:00
}
],
"source": [
2023-07-14 15:52:45 -07:00
"from IPython.display import Image\n",
"\n",
"Image(filename='coding/stock_price_ytd.png')"
2023-06-09 11:40:04 -07:00
]
2023-07-23 06:23:09 -07:00
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use a Different Code Execution Environment\n",
"\n",
"The code execution happened in a separate process, so the plot is not directly displayed in the notebook. Is it possible to change the code execution environment into IPython?\n",
"\n",
"Yes! In the following we demonstrate how to extend the `UserProxyAgent` to use a different code execution environment."
]
},
{
"cell_type": "code",
2023-07-25 16:46:11 -07:00
"execution_count": 6,
2023-07-23 06:23:09 -07:00
"metadata": {},
"outputs": [],
"source": [
"from typing import Dict, Union\n",
"from IPython import get_ipython\n",
"\n",
"class IPythonUserProxyAgent(UserProxyAgent):\n",
" def __init__(self, name: str, **kwargs):\n",
" super().__init__(name, **kwargs)\n",
" self._ipython = get_ipython()\n",
"\n",
" def generate_init_message(self, *args, **kwargs) -> Union[str, Dict]:\n",
" return super().generate_init_message(*args, **kwargs) + \"\"\"\n",
"If you suggest code, the code will be executed in IPython.\"\"\"\n",
"\n",
2023-07-25 16:46:11 -07:00
" def run_code(self, code, **kwargs):\n",
2023-07-23 06:23:09 -07:00
" result = self._ipython.run_cell(code)\n",
" log = str(result.result)\n",
" exitcode = 0 if result.success else 1\n",
" if result.error_before_exec is not None:\n",
" log += f\"\\n{result.error_before_exec}\"\n",
" exitcode = 1\n",
" if result.error_in_exec is not None:\n",
" log += f\"\\n{result.error_in_exec}\"\n",
" exitcode = 1\n",
" return exitcode, bytes(log, \"utf-8\"), None"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The implementation overrides three functions in `UserProxyAgent`:\n",
"* constructor. We get the ipython instance as the code execution environment.\n",
2023-07-25 16:46:11 -07:00
"* `generate_init_message`. We generate a modified initial message to send to the assistant agent, by adding the info that the execution will be performed in IPython.\n",
"* `run_code`. We execute the code with the ipython instance.\n",
"\n",
2023-07-23 06:23:09 -07:00
"With the new `IPythonUserProxyAgent`, we are able to run the code within the current notebook environment and display plot directly."
]
},
{
"cell_type": "code",
2023-07-25 16:46:11 -07:00
"execution_count": 7,
2023-07-23 06:23:09 -07:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ipython_user (to assistant):\n",
"\n",
"Plot a chart of META and TESLA stock price change YTD\n",
"If you suggest code, the code will be executed in IPython.\n",
"\n",
"--------------------------------------------------------------------------------\n",
"assistant (to ipython_user):\n",
"\n",
"Sure, we can use the `yfinance` library in Python to download the stock price data and `matplotlib` to plot the data. If you don't have `yfinance` installed, you can install it using pip:\n",
"\n",
"```python\n",
"!pip install yfinance\n",
"```\n",
"\n",
"Here is the Python code to plot the YTD stock price change for META (Facebook) and TESLA.\n",
"\n",
"```python\n",
"# Python code\n",
"import yfinance as yf\n",
"import matplotlib.pyplot as plt\n",
"from datetime import datetime\n",
"\n",
"# Define the ticker symbol\n",
"tickerSymbols = ['META', 'TSLA']\n",
"\n",
"# Get data on this ticker\n",
"start_date = datetime(datetime.now().year, 1, 1)\n",
"end_date = datetime.now()\n",
"\n",
"# Fetch the data\n",
"data = yf.download(tickerSymbols, start=start_date, end=end_date)\n",
"\n",
"# Plot the close prices\n",
"plt.figure(figsize=(14,7))\n",
"plt.plot(data['Close'])\n",
"plt.title('YTD Stock Price Change for META and TESLA')\n",
"plt.xlabel('Date')\n",
"plt.ylabel('Price (USD)')\n",
"plt.legend(tickerSymbols)\n",
"plt.grid(True)\n",
"plt.show()\n",
"```\n",
"\n",
"This code will plot the closing prices of META and TESLA stocks from the start of this year to the current date. The prices are in USD.\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\n",
">>>>>>>> USING AUTO REPLY FOR THE USER...\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Defaulting to user installation because normal site-packages is not writeable\n",
"Requirement already satisfied: yfinance in /home/vscode/.local/lib/python3.9/site-packages (0.2.26)\n",
2023-07-25 16:46:11 -07:00
"Requirement already satisfied: pandas>=1.3.0 in /home/vscode/.local/lib/python3.9/site-packages (from yfinance) (2.0.3)\n",
"Requirement already satisfied: lxml>=4.9.1 in /home/vscode/.local/lib/python3.9/site-packages (from yfinance) (4.9.3)\n",
2023-07-23 06:23:09 -07:00
"Requirement already satisfied: appdirs>=1.4.4 in /home/vscode/.local/lib/python3.9/site-packages (from yfinance) (1.4.4)\n",
"Requirement already satisfied: numpy>=1.16.5 in /home/vscode/.local/lib/python3.9/site-packages (from yfinance) (1.25.1)\n",
2023-07-25 16:46:11 -07:00
"Requirement already satisfied: html5lib>=1.1 in /home/vscode/.local/lib/python3.9/site-packages (from yfinance) (1.1)\n",
2023-07-23 06:23:09 -07:00
"Requirement already satisfied: pytz>=2022.5 in /home/vscode/.local/lib/python3.9/site-packages (from yfinance) (2023.3)\n",
2023-07-25 16:46:11 -07:00
"Requirement already satisfied: beautifulsoup4>=4.11.1 in /home/vscode/.local/lib/python3.9/site-packages (from yfinance) (4.12.2)\n",
2023-07-23 06:23:09 -07:00
"Requirement already satisfied: frozendict>=2.3.4 in /home/vscode/.local/lib/python3.9/site-packages (from yfinance) (2.3.8)\n",
2023-07-25 16:46:11 -07:00
"Requirement already satisfied: requests>=2.31 in /usr/local/lib/python3.9/site-packages (from yfinance) (2.31.0)\n",
2023-07-23 06:23:09 -07:00
"Requirement already satisfied: multitasking>=0.0.7 in /home/vscode/.local/lib/python3.9/site-packages (from yfinance) (0.0.11)\n",
"Requirement already satisfied: soupsieve>1.2 in /home/vscode/.local/lib/python3.9/site-packages (from beautifulsoup4>=4.11.1->yfinance) (2.4.1)\n",
"Requirement already satisfied: webencodings in /home/vscode/.local/lib/python3.9/site-packages (from html5lib>=1.1->yfinance) (0.5.1)\n",
2023-07-25 16:46:11 -07:00
"Requirement already satisfied: six>=1.9 in /usr/local/lib/python3.9/site-packages (from html5lib>=1.1->yfinance) (1.16.0)\n",
2023-07-23 06:23:09 -07:00
"Requirement already satisfied: tzdata>=2022.1 in /home/vscode/.local/lib/python3.9/site-packages (from pandas>=1.3.0->yfinance) (2023.3)\n",
2023-07-25 16:46:11 -07:00
"Requirement already satisfied: python-dateutil>=2.8.2 in /home/vscode/.local/lib/python3.9/site-packages (from pandas>=1.3.0->yfinance) (2.8.2)\n",
2023-07-23 06:23:09 -07:00
"Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.9/site-packages (from requests>=2.31->yfinance) (3.2.0)\n",
2023-07-25 16:46:11 -07:00
"Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.9/site-packages (from requests>=2.31->yfinance) (2023.5.7)\n",
"Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.9/site-packages (from requests>=2.31->yfinance) (3.4)\n",
"Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.9/site-packages (from requests>=2.31->yfinance) (2.0.3)\n",
2023-07-23 06:23:09 -07:00
"\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m23.0.1\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m23.2\u001b[0m\n",
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
"[*********************100%***********************] 2 of 2 completed\n"
]
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABIgAAAJwCAYAAADiPVqNAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8pXeV/AAAACXBIWXMAAA9hAAAPYQGoP6dpAAEAAElEQVR4nOzdd3hUZdrH8e9Meu8hgUCA0Kv0ohQVAUUQEQtYQMS2urr2de297NpfuwgoTVHsCAIiHWnSewuEEhJI75k57x+HDMQESMIkk/L7XFeuOXPOc865JzlxNzf3cz8WwzAMRERERERERESkzrK6OgAREREREREREXEtJYhEREREREREROo4JYhEREREREREROo4JYhEREREREREROo4JYhEREREREREROo4JYhEREREREREROo4JYhEREREREREROo4JYhEREREREREROo4JYhEREREREREROo4JYhERERqsP79+9OuXTuX3b9x48aMHTvWZfc/lz/++AOLxcI333zj6lAqVWZmJuPHjycqKgqLxcK//vUvV4ckf2OxWHj22WddHYaIiMgZKUEkIiLVzuWXX05ISAiJiYkljqWlpREdHU29evWwWCzn/Jo0aRJAsX3u7u6EhobSpUsX7r//frZu3Vrm2PLz83nnnXfo1KkTgYGBBAcH07ZtW+644w62b9/uGLd8+XKeffZZUlNTz/fbUWnGjh1b7PsSGBhIx44deeONN8jLy3N1eOf0xx9/MGLECKKiovD09CQyMpKhQ4cya9YsV4dW5V5++WUmTZrE3XffzZdffsnNN99cqfdr3LgxFouFAQMGlHr8008/dTxXa9ascex/9tlnz/r7evToUfr371+m3+3Tky3btm3DYrHg7e1drX/nzqa8n7voZ1Da1+DBg4tde+nSpVx++eU0aNAAb29vGjVqxNChQ5k2bVqxcRaLhXvvvbfMMX/wwQdYLBZ69Ohx3p9fRERcz93VAYiIiPzdBx98QLt27XjggQdK/AHzn//8h+TkZJ588kni4uIc+2fPns306dN56623CA8Pd+zv3bu3Y/uyyy7jlltuwTAM0tLS2LBhA5MnT+aDDz7gtdde48EHHzxnbNdccw2//voro0aN4vbbb6egoIDt27fz888/07t3b1q1agWYCaLnnnuOsWPHEhwcfJ7fkcrj5eXFZ599BkBqairffvstDz/8MKtXr2bGjBnnPH/Hjh1YrVX/703PPPMMzz//PM2bN+fOO+8kNjaW48ePM3v2bK655hqmTp3K6NGjqzwuV/n999/p2bMnzzzzTJXd09vbm4ULF3L06FGioqKKHZs6dSre3t7k5uaWeu6HH36Iv79/if3BwcE88cQTjB8/3rFv9erVvPvuu/znP/+hdevWjv0dOnRwbE+ZMoWoqChSUlL45ptvip1fU1Tkc19wwQU89NBDJa5Vv359x/bMmTO5/vrrueCCC7j//vsJCQlh3759LF68mE8//fS8fk+mTp1K48aNWbVqFbt376ZZs2YVvpaIiFQD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oSJhERkbO59957DQ8PD8Pf398YNWrUGcdVdIpZkfvvv98AjA0bNpxxjN1uN/r162cARr169YxRo0YZ77//vhEfH1/meNavX28Axvjx44vtf/jhhw3A+P333w3DMIzU1FQjICDA6NGjh5GTk1MijiKnTzH79ttvDQ8PD+P22283bDbbGT9HkaIpZklJSUZSUpKxe/du4+WXXzYsFovRoUMHx7jY2FgDMObMmVPiGrGxscaYMWMc759++mnHtJO/K4r7yy+/NKxWq7FkyZJixz/66CMDMJYtW3bGmH/44QcDMN56661zfj7DODXFrHXr1sW
"text/plain": [
"<Figure size 1400x700 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"ipython_user (to assistant):\n",
"\n",
"exitcode: 0 (execution succeeded)\n",
"Code output: \n",
"None\n",
"None\n",
"\n",
"--------------------------------------------------------------------------------\n",
"assistant (to ipython_user):\n",
"\n",
"It seems like the code executed successfully but didn't produce any output. This could be due to the fact that the IPython environment you're using might not support matplotlib's interactive mode. \n",
"\n",
"Let's try a different approach using pandas' built-in plotting function, which should work in any environment. \n",
"\n",
"```python\n",
"# Python code\n",
"import yfinance as yf\n",
"import pandas as pd\n",
"from datetime import datetime\n",
"\n",
"# Define the ticker symbol\n",
"tickerSymbols = ['META', 'TSLA']\n",
"\n",
"# Get data on this ticker\n",
"start_date = datetime(datetime.now().year, 1, 1)\n",
"end_date = datetime.now()\n",
"\n",
"# Fetch the data\n",
"data = yf.download(tickerSymbols, start=start_date, end=end_date)\n",
"\n",
"# Plot the close prices\n",
"data['Close'].plot(title='YTD Stock Price Change for META and TESLA', figsize=(14,7), grid=True)\n",
"```\n",
"\n",
"This code does the same thing as the previous one, but uses pandas' built-in plot function instead of matplotlib. The plot should appear directly in your IPython environment.\n",
"\n",
"--------------------------------------------------------------------------------\n",
"\n",
">>>>>>>> USING AUTO REPLY FOR THE USER...\n",
"[*********************100%***********************] 2 of 2 completed\n"
]
},
{
"data": {
"text/plain": [
"<Axes: title={'center': 'YTD Stock Price Change for META and TESLA'}, xlabel='Date'>"
]
},
2023-07-25 16:46:11 -07:00
"execution_count": 7,
2023-07-23 06:23:09 -07:00
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAABHUAAAJMCAYAAAB0N5pyAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMiwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8pXeV/AAAACXBIWXMAAA9hAAAPYQGoP6dpAAD+8ElEQVR4nOzdd3hU1dbH8e9Meu8h1AChd6SDCIIURRQERbCAKNeC5dqu1971qtdre+2ioFKUYkMEadJ7770GSEhCep857x+HBGICJGGSSfl9nifPOXPaXmdyBjPLvde2GIZhICIiIiIiIiIilYrV2QGIiIiIiIiIiEjJKakjIiIiIiIiIlIJKakjIiIiIiIiIlIJKakjIiIiIiIiIlIJKakjIiIiIiIiIlIJKakjIiIiIiIiIlIJKakjIiIiIiIiIlIJKakjIiIiIiIiIlIJKakjIiIiIiIiIlIJKakjIiJSznr37k2rVq2c1n79+vUZM2aM09q/lL/++guLxcKMGTOcHUqZSk1N5Z577iEiIgKLxcI///lPZ4ckf2OxWHjppZecHYaIiMgFKakjIiIOce211xIUFERMTEyhfUlJSdSsWZMaNWpgsVgu+TNx4kSAAttcXV0JDg6mQ4cOPPLII+zcubPYsWVnZ/PBBx/Qvn17/P39CQwMpGXLlvzjH/9g9+7d+cetXLmSl156icTExMt9O8rMmDFjCrwv/v7+tG3blnfffZesrCxnh3dJf/31FzfddBMRERG4u7sTHh7O4MGDmTVrlrNDK3dvvPEGEydO5P777+e7777jjjvuKNP26tevj8Vi4Zprrily/5dffpn/XK1fvz5/+0svvXTRz+upU6fo3bt3sT7b5ydIdu3ahcViwdPTs0J/5i6mpPed9zso6mfgwIEFrr18+XKuvfZaateujaenJ/Xq1WPw4MFMmTKlwHEWi4UHH3yw2DF/8sknWCwWunTpctn3LyIizufq7ABERKRq+OSTT2jVqhWPPvpooS8dzzzzDHFxcTz33HNERUXlb58zZw5Tp07lvffeIzQ0NH979+7d89f79evHnXfeiWEYJCUlsWXLFiZNmsQnn3zCW2+9xWOPPXbJ2IYNG8Yff/zByJEjGTduHDk5OezevZvZs2fTvXt3mjVrBphJnZdffpkxY8YQGBh4me9I2fHw8OCrr74CIDExkZkzZ/LEE0+wbt06pk2bdsnz9+zZg9Va/v9f58UXX+SVV16hcePG3HvvvURGRhIfH8+cOXMYNmwYkydPZtSoUeUel7MsWrSIrl278uKLL5Zbm56enixevJhTp04RERFRYN/kyZPx9PQkMzOzyHM//fRTfH19C20PDAzk2Wef5Z577snftm7dOj788EOeeeYZmjdvnr+9TZs2+evff/89ERERnDlzhhkzZhQ4v7IozX23a9eOxx9/vNC1atWqlb8+ffp0RowYQbt27XjkkUcICgri0KFDLF26lC+//PKyPieTJ0+mfv36rF27lv3799OoUaNSX0tERCoAQ0RExEHeeustAzDmzZuXv23t2rWG1Wo1/vWvfxU6/p133jEA49ChQ0VeDzDGjx9faHtcXJzRrVs3AzB+//33i8a0du1aAzBef/31Qvtyc3ONuLi4YsfjKL169TJatmxZqnNHjx5t+Pj4FNhms9mMjh07GoARHR1d5Hl2u91IT08vVZuOMH36dAMwhg8fbmRnZxfaP3fuXOO3334zDMMwFi9ebADG9OnTyzvMctWgQQNj0KBBDrteTk6OkZWVdcH9kZGRRt++fQ1/f3/j/fffL7Dv2LFjhtVqNYYNG2YAxrp16/L3vfjiiwZgnD59utix5P2+Fy9eXOR+u91u1K9f33jssceMoUOHGr179y72tcsTYLz44ovFPv5S9x0ZGVms33mLFi2Mli1bFvn7jImJKRRjUf9OFuXgwYMGYMyaNcsICwszXnrppWKdJyIiFZeGX4mIiMM89thjtGnThgceeIDMzExsNhv33XcfkZGRDu2NEBISwrRp03B1deX111+/6LEHDhwAoEePHoX2ubi4EBISAphDTJ588kkAGjRokD8k4vDhwwDk5uby6quvEhUVhYeHB/Xr1+eZZ54pcsjTH3/8Qa9evfDz88Pf359OnToV6r30d3/++Sfe3t6MHDmS3NzcS74H57NarfTu3RsgP9769etz/fXXM2/ePDp27IiXlxeff/55/r6/19RJTEzk0UcfpX79+nh4eFCnTh3uvPNO4uLi8o/JysrixRdfpFGjRnh4eFC3bl3+9a9/FWvY1/PPP09wcDBff/01bm5uhfYPGDCA66+/vsA2u93O66+/Tp06dfD09KRv377s37+/wDHLli3j5ptvpl69evkxPfroo2RkZBQ4bsyYMfj6+hIdHc2QIUPw9fUlLCyMJ554ApvNVuDY+Ph47rjjjvyheqNHj2bLli0Fhgbm2b17N8OHDyc4OBhPT086duzIr7/+etH3Iq9m0KFDh/j9998LPWuxsbHcfffd1KhRA09PT9q2bcukSZMKXOPw4cNYLBb++9//8v777+c/l5calujp6clNN91U6HmcOnUqQUFBDBgw4KLnO8qKFSs4fPgwt956K7feeitLly7l+PHjxTp369atjBkzhoYNG+Lp6UlERARjx44lPj6+wHF5w8b279+f3/suICCAu+66i/T09ALHZmVl8eijjxIWFoafnx833HBDseMpCwcOHKBTp064u7sX2hceHl7q606ePJmgoCAGDRrE8OHDmTx58uWEKSIiFYCGX4mIiMO4urryxRdf0L17d1599VXCw8PZuHEjc+fOxdvb26Ft1atXj169erF48WKSk5Px9/cv8rjIyEjA/DLTo0cPXF2L/k/fTTfdxN69ewsNBwsLCwPgnnvuYdKkSQwfPpzHH3+cNWvW8Oabb7Jr1y5++umn/OtMnDiRsWPH0rJlS55++mkCAwPZtGkTc+fOveCQidmzZzN8+HBGjBjB119/jYuLS4nfj7zkVV6SCsxhViNHjuTee+9l3LhxNG3atMhzU1NT6dmzJ7t27WLs2LFcccUVxMXF8euvv3L8+HFCQ0Ox2+3ccMMNLF++nH/84x80b96cbdu28d5777F3715+/vnnC8a2b98+du/ezdixY/Hz8yv2Pf3nP//BarXyxBNPkJSUxNtvv81tt93GmjVr8o+ZPn066enp3H///YSEhLB27Vo++ugjjh8/zvTp0wtcz2azMWDAALp06cJ///tfFixYwLvvvktUVBT3338/YCaSBg8ezNq1a7n//vtp1qwZv/zyC6NHjy4U344dO+jRowe1a9fm3//+Nz4+Pvz4448MGTKEmTNnMnTo0CLvq3nz5nz33Xc8+uij1KlTJ38oTlhYGBkZGfTu3Zv9+/fz4IMP0qBBA6ZPn86YMWNITEzkkUceKXCtb775hszMTP7xj3/g4eFBcHDwJd/XUaNG0b9/fw4cOJA/HHLKlCkMHz68yIRbnoSEhELbXF1dSzVUcfLkyURFRdGpUydatWqFt7c3U6dOzU+sXsz8+fM5ePAgd911FxEREezYsYMvvviCHTt2sHr1aiwWS4Hjb7nlFho0aMCbb77Jxo0b+eqrrwgPD+ett97KP+aee+7h+++/Z9SoUXTv3p1FixYxaNCgEt9XceTk5BRIlubx8fHBy8sLMP/dWrhwIcePH6dOnToOa3vy5MncdNNNuLu7M3LkSD799FPWrVtHp06dHNaGiIiUM2d3FRIRkarnwQcfNNzc3AxfX19j5MiRFzyutMOv8jzyyCMGYGzZsuWCx9jtdqNXr14GYNSoUcMYOXKk8fHHHxtHjhwpdjybN282AOOee+4psP2JJ54wAGPRokWGYRhGYmKi4efnZ3Tp0sXIyMgoFEee84dfzZw503BzczPGjRtn2Gy2C95HnrzhV6dPnzZOnz5t7N+/33jjjTcMi8VitGnTJv+4yMhIAzDmzp1b6BqRkZHG6NGj81+/8MIL+UMy/i4v7u+++86wWq3GsmXLCuz/7LPPDMBYsWLFBWP+5ZdfDMB47733Lnl/hnFu+FXz5s0LDD/54IM
"text/plain": [
"<Figure size 1400x700 with 1 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"ipython_user (to assistant):\n",
"\n",
"exitcode: 0 (execution succeeded)\n",
"Code output: \n",
"Axes(0.125,0.2;0.775x0.68)\n",
"\n",
"--------------------------------------------------------------------------------\n",
"assistant (to ipython_user):\n",
"\n",
"Great! The code executed successfully. The output `Axes(0.125,0.2;0.775x0.68)` is just a representation of the plot object. The actual plot should be displayed in your IPython environment. \n",
"\n",
"The plot should show the YTD stock price change for META and TESLA. The x-axis represents the date and the y-axis represents the closing price in USD. \n",
"\n",
"If you can see the plot and it meets your requirements, then we are done here. \n",
"\n",
"TERMINATE\n",
"\n",
"--------------------------------------------------------------------------------\n"
]
}
],
"source": [
"ipy_user = IPythonUserProxyAgent(\n",
" \"ipython_user\",\n",
" human_input_mode=\"NEVER\",\n",
" max_consecutive_auto_reply=10,\n",
" is_termination_msg=lambda x: x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\") or x.get(\"content\", \"\").rstrip().endswith('\"TERMINATE\".'),\n",
")\n",
"assistant.reset()\n",
"# the assistant receives a message from the user, which contains the task description\n",
"ipy_user.initiate_chat(\n",
" assistant,\n",
" message=\"\"\"Plot a chart of META and TESLA stock price change YTD\"\"\",\n",
")"
]
2023-05-27 23:17:23 -04:00
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
2023-07-23 06:23:09 -07:00
"version": "3.9.17"
2023-05-27 23:17:23 -04:00
},
"vscode": {
"interpreter": {
"hash": "949777d72b0d2535278d3dc13498b2535136f6dfe0678499012e853ee9abcab1"
}
},
"widgets": {
"application/vnd.jupyter.widget-state+json": {
"state": {
"2d910cfd2d2a4fc49fc30fbbdc5576a7": {
"model_module": "@jupyter-widgets/base",
"model_module_version": "2.0.0",
"model_name": "LayoutModel",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "2.0.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "2.0.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border_bottom": null,
"border_left": null,
"border_right": null,
"border_top": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"454146d0f7224f038689031002906e6f": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "2.0.0",
"model_name": "HBoxModel",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "2.0.0",
"_model_name": "HBoxModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "2.0.0",
"_view_name": "HBoxView",
"box_style": "",
"children": [
"IPY_MODEL_e4ae2b6f5a974fd4bafb6abb9d12ff26",
"IPY_MODEL_577e1e3cc4db4942b0883577b3b52755",
"IPY_MODEL_b40bdfb1ac1d4cffb7cefcb870c64d45"
],
"layout": "IPY_MODEL_dc83c7bff2f241309537a8119dfc7555",
"tabbable": null,
"tooltip": null
}
},
"577e1e3cc4db4942b0883577b3b52755": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "2.0.0",
"model_name": "FloatProgressModel",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "2.0.0",
"_model_name": "FloatProgressModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "2.0.0",
"_view_name": "ProgressView",
"bar_style": "success",
"description": "",
"description_allow_html": false,
"layout": "IPY_MODEL_2d910cfd2d2a4fc49fc30fbbdc5576a7",
"max": 1,
"min": 0,
"orientation": "horizontal",
"style": "IPY_MODEL_74a6ba0c3cbc4051be0a83e152fe1e62",
"tabbable": null,
"tooltip": null,
"value": 1
}
},
"6086462a12d54bafa59d3c4566f06cb2": {
"model_module": "@jupyter-widgets/base",
"model_module_version": "2.0.0",
"model_name": "LayoutModel",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "2.0.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "2.0.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border_bottom": null,
"border_left": null,
"border_right": null,
"border_top": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"74a6ba0c3cbc4051be0a83e152fe1e62": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "2.0.0",
"model_name": "ProgressStyleModel",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "2.0.0",
"_model_name": "ProgressStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "2.0.0",
"_view_name": "StyleView",
"bar_color": null,
"description_width": ""
}
},
"7d3f3d9e15894d05a4d188ff4f466554": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "2.0.0",
"model_name": "HTMLStyleModel",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "2.0.0",
"_model_name": "HTMLStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "2.0.0",
"_view_name": "StyleView",
"background": null,
"description_width": "",
"font_size": null,
"text_color": null
}
},
"b40bdfb1ac1d4cffb7cefcb870c64d45": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "2.0.0",
"model_name": "HTMLModel",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "2.0.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "2.0.0",
"_view_name": "HTMLView",
"description": "",
"description_allow_html": false,
"layout": "IPY_MODEL_f1355871cc6f4dd4b50d9df5af20e5c8",
"placeholder": " ",
"style": "IPY_MODEL_ca245376fd9f4354af6b2befe4af4466",
"tabbable": null,
"tooltip": null,
"value": " 1/1 [00:00<00:00, 44.69it/s]"
}
},
"ca245376fd9f4354af6b2befe4af4466": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "2.0.0",
"model_name": "HTMLStyleModel",
"state": {
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "2.0.0",
"_model_name": "HTMLStyleModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "2.0.0",
"_view_name": "StyleView",
"background": null,
"description_width": "",
"font_size": null,
"text_color": null
}
},
"dc83c7bff2f241309537a8119dfc7555": {
"model_module": "@jupyter-widgets/base",
"model_module_version": "2.0.0",
"model_name": "LayoutModel",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "2.0.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "2.0.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border_bottom": null,
"border_left": null,
"border_right": null,
"border_top": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
},
"e4ae2b6f5a974fd4bafb6abb9d12ff26": {
"model_module": "@jupyter-widgets/controls",
"model_module_version": "2.0.0",
"model_name": "HTMLModel",
"state": {
"_dom_classes": [],
"_model_module": "@jupyter-widgets/controls",
"_model_module_version": "2.0.0",
"_model_name": "HTMLModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/controls",
"_view_module_version": "2.0.0",
"_view_name": "HTMLView",
"description": "",
"description_allow_html": false,
"layout": "IPY_MODEL_6086462a12d54bafa59d3c4566f06cb2",
"placeholder": " ",
"style": "IPY_MODEL_7d3f3d9e15894d05a4d188ff4f466554",
"tabbable": null,
"tooltip": null,
"value": "100%"
}
},
"f1355871cc6f4dd4b50d9df5af20e5c8": {
"model_module": "@jupyter-widgets/base",
"model_module_version": "2.0.0",
"model_name": "LayoutModel",
"state": {
"_model_module": "@jupyter-widgets/base",
"_model_module_version": "2.0.0",
"_model_name": "LayoutModel",
"_view_count": null,
"_view_module": "@jupyter-widgets/base",
"_view_module_version": "2.0.0",
"_view_name": "LayoutView",
"align_content": null,
"align_items": null,
"align_self": null,
"border_bottom": null,
"border_left": null,
"border_right": null,
"border_top": null,
"bottom": null,
"display": null,
"flex": null,
"flex_flow": null,
"grid_area": null,
"grid_auto_columns": null,
"grid_auto_flow": null,
"grid_auto_rows": null,
"grid_column": null,
"grid_gap": null,
"grid_row": null,
"grid_template_areas": null,
"grid_template_columns": null,
"grid_template_rows": null,
"height": null,
"justify_content": null,
"justify_items": null,
"left": null,
"margin": null,
"max_height": null,
"max_width": null,
"min_height": null,
"min_width": null,
"object_fit": null,
"object_position": null,
"order": null,
"overflow": null,
"padding": null,
"right": null,
"top": null,
"visibility": null,
"width": null
}
}
},
"version_major": 2,
"version_minor": 0
}
}
},
"nbformat": 4,
"nbformat_minor": 2
}