{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Code Executors\n",
    "\n",
    "In the last chapter, \n",
    "we used two agents powered by a large language model (LLM) to play a game\n",
    "by exchanging messages.\n",
    "In this chapter, we introduce code executors, which enable agents to not just chat\n",
    "but also\n",
    "to interact with an environment and perform useful computations and take actions.\n",
    "\n",
    "## Overview\n",
    "\n",
    "In AutoGen, a code executor is a component that\n",
    "takes input messages (e.g., those containing code blocks), performs execution, and outputs messages\n",
    "with the results.\n",
    "AutoGen provides two types of built-in code executors, one is \n",
    "command line code executor, which runs code in a command line environment\n",
    "such as a UNIX shell, and the other is Jupyter executor, which runs code\n",
    "in an interactive [Jupyter kernel](https://github.com/jupyter/jupyter/wiki/Jupyter-kernels).\n",
    "\n",
    "For each type of executor, AutoGen provides two ways to execute code: locally and in a Docker container.\n",
    "One way is to execute\n",
    "code directly in the same host platform where AutoGen is running, i.e.,\n",
    "the local operating system.\n",
    "It is for development and testing, but it is not ideal for production\n",
    "as LLM can generate arbitrary code.\n",
    "The other way is to execute code in a Docker container.\n",
    "The table below shows the combinations of code executors and execution\n",
    "environments.\n",
    "\n",
    "| Code Executor (`autogen.coding`) | Environment | Platform |\n",
    "| ---------------------------- | ----------- | -------- |\n",
    "| [`LocalCommandLineCodeExecutor`](/docs/reference/coding/local_commandline_code_executor#localcommandlinecodeexecutor)  | Shell       | Local  |\n",
    "| [`DockerCommandLineCodeExecutor`](/docs/reference/coding/docker_commandline_code_executor#dockercommandlinecodeexecutor) | Shell       | Docker |\n",
    "| [`jupyter.JupyterCodeExecutor`](/docs/reference/coding/jupyter/jupyter_code_executor#jupytercodeexecutor)           | Jupyter Kernel (e.g., python3) | Local/Docker |\n",
    "\n",
    "In this chapter, we will focus on the command line code executors.\n",
    "For the Jupyter code executor, please refer to the topic page for \n",
    "[Jupyter Code Executor](/docs/topics/code-execution/jupyter-code-executor)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Local Execution\n",
    "\n",
    "The figure below shows the architecture of the local command line code executor\n",
    "([`autogen.coding.LocalCommandLineCodeExecutor`](/docs/reference/coding/local_commandline_code_executor#localcommandlinecodeexecutor)).\n",
    "\n",
    "````mdx-code-block\n",
    ":::danger\n",
    "Executing LLM-generated code poses a security risk to your host environment.\n",
    ":::\n",
    "````\n",
    "\n",
    "```{=mdx}\n",
    "![Code Executor No Docker](./assets/code-executor-no-docker.png)\n",
    "```\n",
    "\n",
    "Upon receiving a message with a code block, the local command line code executor\n",
    "first writes the code block to a code file, then starts a new subprocess to\n",
    "execute the code file. The executor reads the console output of the \n",
    "code execution and sends it back as a reply message.\n",
    "\n",
    "Here is an example of using the code executor to run a Python\n",
    "code block that prints a random number.\n",
    "First we create an agent with the code executor\n",
    "that uses a temporary directory to store the code files.\n",
    "We specify `human_input_mode=\"ALWAYS\"` to manually validate the safety of the the code being \n",
    "executed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tempfile\n",
    "\n",
    "from autogen import ConversableAgent\n",
    "from autogen.coding import LocalCommandLineCodeExecutor\n",
    "\n",
    "# Create a temporary directory to store the code files.\n",
    "temp_dir = tempfile.TemporaryDirectory()\n",
    "\n",
    "# Create a local command line code executor.\n",
    "executor = LocalCommandLineCodeExecutor(\n",
    "    timeout=10,  # Timeout for each code execution in seconds.\n",
    "    work_dir=temp_dir.name,  # Use the temporary directory to store the code files.\n",
    ")\n",
    "\n",
    "# Create an agent with code executor configuration.\n",
    "code_executor_agent = ConversableAgent(\n",
    "    \"code_executor_agent\",\n",
    "    llm_config=False,  # Turn off LLM for this agent.\n",
    "    code_execution_config={\"executor\": executor},  # Use the local command line code executor.\n",
    "    human_input_mode=\"ALWAYS\",  # Always take human input for this agent for safety.\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Before running this example, we need to make sure the `matplotlib` and `numpy`\n",
    "are installed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "! pip install -qqq matplotlib numpy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we have the agent generate a reply given a message with a Python code block."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[31m\n",
      ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> EXECUTING CODE BLOCK (inferred language is python)...\u001b[0m\n",
      "exitcode: 0 (execution succeeded)\n",
      "Code output: \n",
      "Scatter plot saved to scatter.png\n",
      "\n"
     ]
    }
   ],
   "source": [
    "message_with_code_block = \"\"\"This is a message with code block.\n",
    "The code block is below:\n",
    "```python\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "x = np.random.randint(0, 100, 100)\n",
    "y = np.random.randint(0, 100, 100)\n",
    "plt.scatter(x, y)\n",
    "plt.savefig('scatter.png')\n",
    "print('Scatter plot saved to scatter.png')\n",
    "```\n",
    "This is the end of the message.\n",
    "\"\"\"\n",
    "\n",
    "# Generate a reply for the given code.\n",
    "reply = code_executor_agent.generate_reply(messages=[{\"role\": \"user\", \"content\": message_with_code_block}])\n",
    "print(reply)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "During the generation of response, a human input is requested to give an opportunity\n",
    "to intercept the code execution.\n",
    "In this case, we choose to continue the execution, \n",
    "and the agent's reply contains the output of the code execution.\n",
    "\n",
    "We can take a look at the generated plot in the temporary directory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['scatter.png', '6507ea07b63b45aabb027ade4e213de6.py']\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "print(os.listdir(temp_dir.name))\n",
    "# We can see the output scatter.png and the code file generated by the agent."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Clean up the working directory to avoid affecting future conversations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "temp_dir.cleanup()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Docker Execution\n",
    "\n",
    "To mitigate the security risk of running LLM-generated code locally, \n",
    "we can use the docker command line code executor \n",
    "([`autogen.coding.DockerCommandLineCodeExecutor`](/docs/reference/coding/docker_commandline_code_executor#dockercommandlinecodeexecutor))\n",
    "to execute code in a docker container.\n",
    "This way, the generated code can only access resources that are explicitly \n",
    "given to it.\n",
    "\n",
    "The figure below illustrates how does the docker execution works.\n",
    "\n",
    "```{=mdx}\n",
    "![Code Executor Docker](./assets/code-executor-docker.png)\n",
    "```\n",
    "\n",
    "Similar to the local command line code executor, the docker executor \n",
    "extracts code blocks from input messages, writes them to code files.\n",
    "For each code file, it starts a docker container to execute the code file,\n",
    "and reads the console output of the code execution."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To use docker execution, you need to [install Docker](https://docs.docker.com/engine/install/) on your machine.\n",
    "Once you have Docker installed and running, you can set up your code executor agent as follow:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "from autogen.coding import DockerCommandLineCodeExecutor\n",
    "\n",
    "# Create a temporary directory to store the code files.\n",
    "temp_dir = tempfile.TemporaryDirectory()\n",
    "\n",
    "# Create a Docker command line code executor.\n",
    "executor = DockerCommandLineCodeExecutor(\n",
    "    image=\"python:3.12-slim\",  # Execute code using the given docker image name.\n",
    "    timeout=10,  # Timeout for each code execution in seconds.\n",
    "    work_dir=temp_dir.name,  # Use the temporary directory to store the code files.\n",
    ")\n",
    "\n",
    "# Create an agent with code executor configuration that uses docker.\n",
    "code_executor_agent_using_docker = ConversableAgent(\n",
    "    \"code_executor_agent_docker\",\n",
    "    llm_config=False,  # Turn off LLM for this agent.\n",
    "    code_execution_config={\"executor\": executor},  # Use the docker command line code executor.\n",
    "    human_input_mode=\"ALWAYS\",  # Always take human input for this agent for safety.\n",
    ")\n",
    "\n",
    "# When the code executor is no longer used, stop it to release the resources.\n",
    "# executor.stop()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The `work_dir` in the constructor points to a local file system directory just like in the local execution case.\n",
    "The docker container will mount this directory and the executor write code files\n",
    "and output to it."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Use Code Execution in Conversation\n",
    "\n",
    "Writing and executing code is necessary for many tasks such as \n",
    "data analysis, machine learning, and mathematical modeling.\n",
    "In AutoGen, coding can be a conversation between a code writer agent and a \n",
    "code executor agent, mirroring the interaction between a programmer and a\n",
    "code interpreter.\n",
    "\n",
    "```{=mdx}\n",
    "![Code Writer and Code Executor](./assets/code-execution-in-conversation.png)\n",
    "```\n",
    "\n",
    "The code writer agent can be powered by an LLM such as GPT-4 with code-writing\n",
    "capability.\n",
    "And the code executor agent is powered by a code executor.\n",
    "\n",
    "The following is an agent with a code writer role specified \n",
    "using `system_message`. The system message contains important instruction\n",
    "on how to use the code executor in the code executor agent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# The code writer agent's system message is to instruct the LLM on how to use\n",
    "# the code executor in the code executor agent.\n",
    "code_writer_system_message = \"\"\"You are a helpful AI assistant.\n",
    "Solve tasks using your coding and language skills.\n",
    "In the following cases, suggest python code (in a python coding block) or shell script (in a sh coding block) for the user to execute.\n",
    "1. When you need to collect info, use the code to output the info you need, for example, browse or search the web, download/read a file, print the content of a webpage or a file, get the current date/time, check the operating system. After sufficient info is printed and the task is ready to be solved based on your language skill, you can solve the task by yourself.\n",
    "2. When you need to perform some task with code, use the code to perform the task and output the result. Finish the task smartly.\n",
    "Solve the task step by step if you need to. If a plan is not provided, explain your plan first. Be clear which step uses code, and which step uses your language skill.\n",
    "When using code, you must indicate the script type in the code block. The user cannot provide any other feedback or perform any other action beyond executing the code you suggest. The user can't modify your code. So do not suggest incomplete code which requires users to modify. Don't use a code block if it's not intended to be executed by the user.\n",
    "If you want the user to save the code in a file before executing it, put # filename: <filename> inside the code block as the first line. Don't include multiple code blocks in one response. Do not ask users to copy and paste the result. Instead, use 'print' function for the output when relevant. Check the execution result returned by the user.\n",
    "If the result indicates there is an error, fix the error and output the code again. Suggest the full code instead of partial code or code changes. If the error can't be fixed or if the task is not solved even after the code is executed successfully, analyze the problem, revisit your assumption, collect additional info you need, and think of a different approach to try.\n",
    "When you find an answer, verify the answer carefully. Include verifiable evidence in your response if possible.\n",
    "Reply 'TERMINATE' in the end when everything is done.\n",
    "\"\"\"\n",
    "\n",
    "code_writer_agent = ConversableAgent(\n",
    "    \"code_writer_agent\",\n",
    "    system_message=code_writer_system_message,\n",
    "    llm_config={\"config_list\": [{\"model\": \"gpt-4\", \"api_key\": os.environ[\"OPENAI_API_KEY\"]}]},\n",
    "    code_execution_config=False,  # Turn off code execution for this agent.\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here is an example of solving a math problem through a conversation\n",
    "between the code writer agent and the code executor agent (created above)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mcode_executor_agent\u001b[0m (to code_writer_agent):\n",
      "\n",
      "Write Python code to calculate the 14th Fibonacci number.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[33mcode_writer_agent\u001b[0m (to code_executor_agent):\n",
      "\n",
      "Sure, here is a Python code snippet to calculate the 14th Fibonacci number. The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1.\n",
      "\n",
      "```python\n",
      "def fibonacci(n):\n",
      "    if(n <= 0):\n",
      "        return \"Input should be a positive integer.\"\n",
      "    elif(n == 1):\n",
      "        return 0\n",
      "    elif(n == 2):\n",
      "        return 1\n",
      "    else:\n",
      "        fib = [0, 1]\n",
      "        for i in range(2, n):\n",
      "            fib.append(fib[i-1] + fib[i-2])\n",
      "        return fib[n-1]\n",
      "\n",
      "print(fibonacci(14))\n",
      "```\n",
      "\n",
      "This Python code defines a function `fibonacci(n)` which computes the n-th Fibonacci number. The function uses a list `fib` to store the Fibonacci numbers as they are computed, and then returns the (n-1)-th element as the n-th Fibonacci number due to zero-indexing in Python lists.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> EXECUTING CODE BLOCK (inferred language is python)...\u001b[0m\n",
      "\u001b[33mcode_executor_agent\u001b[0m (to code_writer_agent):\n",
      "\n",
      "exitcode: 0 (execution succeeded)\n",
      "Code output: \n",
      "233\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[33mcode_writer_agent\u001b[0m (to code_executor_agent):\n",
      "\n",
      "Great, the execution was successful and the 14th Fibonacci number is 233. The sequence goes as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233... and so on, where each number is the sum of the previous two. Therefore, the 14th number in the Fibonacci series is 233. \n",
      "\n",
      "I hope this meets your expectations. If you have any other concerns or need further computations, feel free to ask.\n",
      "\n",
      "TERMINATE\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "chat_result = code_executor_agent.initiate_chat(\n",
    "    code_writer_agent,\n",
    "    message=\"Write Python code to calculate the 14th Fibonacci number.\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "During the previous chat session, human input was requested each time\n",
    "the code executor agent responded to ensure that the code was safe to execute."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can try a more complex example that involves querying the web.\n",
    "Let's say we want to get the the stock price gains year-to-date for\n",
    "Tesla and Meta (formerly Facebook). We can also use the two agents\n",
    "with several iterations of conversation.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mcode_executor_agent\u001b[0m (to code_writer_agent):\n",
      "\n",
      "Today is 2024-02-28. Write Python code to plot TSLA's and META's stock price gains YTD, and save the plot to a file named 'stock_gains.png'.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[33mcode_writer_agent\u001b[0m (to code_executor_agent):\n",
      "\n",
      "This task requires retrieving the historical data of the stocks from a reliable data source and calculating the Year-To-Date (YTD) gain values, and then plotting them. pandas_datareader library will be used for data retrieval, pandas will be used for data manipulation, and matplotlib for plotting. \n",
      "\n",
      "Below is the Python code to achieve this. To start, please install the required libraries by running to the following command:\n",
      "```sh\n",
      "pip install yfinance pandas matplotlib\n",
      "```\n",
      "Then run the python code:\n",
      "\n",
      "```python\n",
      "# filename: stock_gains.py\n",
      "\n",
      "import yfinance as yf\n",
      "import pandas as pd\n",
      "import matplotlib.pyplot as plt\n",
      "from datetime import datetime\n",
      "\n",
      "# define the tickers\n",
      "tickers = ['TSLA', 'META'] \n",
      "\n",
      "# define the start and end dates\n",
      "start_date = datetime(2024, 1, 1)\n",
      "end_date = datetime(2024, 2, 28)\n",
      "\n",
      "# dictionary to hold dataframes\n",
      "dfs = {}\n",
      "\n",
      "for ticker in tickers:\n",
      "    # get the data for the stocks\n",
      "    df = yf.download(ticker, start_date, end_date)\n",
      "\n",
      "    # get the close price and calculate the cumulative percentage gain\n",
      "    df['Gain'] = df['Close'].pct_change().cumsum()\n",
      "\n",
      "    # add to dictionary\n",
      "    dfs[ticker] = df    \n",
      "\n",
      "# plot\n",
      "plt.figure(figsize=(10, 5))\n",
      "for ticker, df in dfs.items():\n",
      "    plt.plot(df.index, df['Gain'], label=ticker)\n",
      "\n",
      "plt.title('YTD Stock Price Gain')\n",
      "plt.xlabel('Date')\n",
      "plt.ylabel('Percentage Gain')\n",
      "plt.legend()\n",
      "\n",
      "plt.grid(True)\n",
      "plt.savefig('stock_gains.png')\n",
      "plt.close()\n",
      "\n",
      "print(\"The 'stock_gains.png' file has been successfully saved\")\n",
      "```\n",
      "This script will download the historical data for TSLA and META from the start of the year to the specified date and calculates the YTD gains. It then generates the plot showing these gains and saves it to 'stock_gains.png'.\n",
      "\n",
      "Please save the script to a file named 'stock_gains.py' and run it using Python. Remember to have the correct start and end dates for the YTD value when running the script. If your Python version is below 3.8, you should update it to execute this code perfectly.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> NO HUMAN INPUT RECEIVED.\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is sh)...\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> EXECUTING CODE BLOCK 1 (inferred language is python)...\u001b[0m\n",
      "\u001b[33mcode_executor_agent\u001b[0m (to code_writer_agent):\n",
      "\n",
      "exitcode: 0 (execution succeeded)\n",
      "Code output: \n",
      "Requirement already satisfied: yfinance in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (0.2.36)\n",
      "Requirement already satisfied: pandas in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (2.1.4)\n",
      "Requirement already satisfied: matplotlib in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (3.8.2)\n",
      "Requirement already satisfied: numpy>=1.16.5 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (1.26.2)\n",
      "Requirement already satisfied: requests>=2.31 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (2.31.0)\n",
      "Requirement already satisfied: multitasking>=0.0.7 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (0.0.11)\n",
      "Requirement already satisfied: lxml>=4.9.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (5.0.1)\n",
      "Requirement already satisfied: appdirs>=1.4.4 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (1.4.4)\n",
      "Requirement already satisfied: pytz>=2022.5 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (2023.3.post1)\n",
      "Requirement already satisfied: frozendict>=2.3.4 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (2.4.0)\n",
      "Requirement already satisfied: peewee>=3.16.2 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (3.17.0)\n",
      "Requirement already satisfied: beautifulsoup4>=4.11.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (4.12.2)\n",
      "Requirement already satisfied: html5lib>=1.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from yfinance) (1.1)\n",
      "Requirement already satisfied: python-dateutil>=2.8.2 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from pandas) (2.8.2)\n",
      "Requirement already satisfied: tzdata>=2022.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from pandas) (2023.4)\n",
      "Requirement already satisfied: contourpy>=1.0.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from matplotlib) (1.2.0)\n",
      "Requirement already satisfied: cycler>=0.10 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from matplotlib) (0.12.1)\n",
      "Requirement already satisfied: fonttools>=4.22.0 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from matplotlib) (4.47.2)\n",
      "Requirement already satisfied: kiwisolver>=1.3.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from matplotlib) (1.4.5)\n",
      "Requirement already satisfied: packaging>=20.0 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from matplotlib) (23.2)\n",
      "Requirement already satisfied: pillow>=8 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from matplotlib) (10.2.0)\n",
      "Requirement already satisfied: pyparsing>=2.3.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from matplotlib) (3.1.1)\n",
      "Requirement already satisfied: soupsieve>1.2 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from beautifulsoup4>=4.11.1->yfinance) (2.5)\n",
      "Requirement already satisfied: six>=1.9 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from html5lib>=1.1->yfinance) (1.16.0)\n",
      "Requirement already satisfied: webencodings in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from html5lib>=1.1->yfinance) (0.5.1)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from requests>=2.31->yfinance) (3.3.2)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from requests>=2.31->yfinance) (3.6)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from requests>=2.31->yfinance) (2.1.0)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /Users/ekzhu/miniconda3/envs/autogen/lib/python3.11/site-packages (from requests>=2.31->yfinance) (2024.2.2)\n",
      "\n",
      "The 'stock_gains.png' file has been successfully saved\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> USING AUTO REPLY...\u001b[0m\n",
      "\u001b[33mcode_writer_agent\u001b[0m (to code_executor_agent):\n",
      "\n",
      "Great! The code executed successfully and the 'stock_gains.png' file has been saved successfully. This file contains the plot of TSLA's and META's stock price gains from the start of the year until February 28, 2024. You should now be able to view this image file in the same directory that you ran the script from. \n",
      "\n",
      "Please make sure to verify this image file. It should contain two plotted lines, each representing the percentage gain over the time for each stock (TSLA and META). The x-axis represents the date, and the y-axis represents the percentage gain. If everything looks correct, this would be the end of the task.\n",
      "\n",
      "TERMINATE\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "import datetime\n",
    "\n",
    "today = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n",
    "chat_result = code_executor_agent.initiate_chat(\n",
    "    code_writer_agent,\n",
    "    message=f\"Today is {today}. Write Python code to plot TSLA's and META's \"\n",
    "    \"stock price gains YTD, and save the plot to a file named 'stock_gains.png'.\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In the previous conversation, the code writer agent generated a code block\n",
    "to install necessary packages and another code block for a script to \n",
    "fetch the stock price and calculate gains year-to-date for Tesla and Meta.\n",
    "The code executor agent installed the packages, executed the script, \n",
    "and returned the results.\n",
    "\n",
    "Let's take a look at the chart that was generated."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 54828 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from IPython.display import Image\n",
    "\n",
    "Image(os.path.join(temp_dir, \"stock_gains.png\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Because code execution leave traces like code files and output in the file system, \n",
    "we may want to clean up the working directory after each conversation concludes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "temp_dir.cleanup()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Stop the docker command line executor to clean up the docker container."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "executor.stop()  # Stop the docker command line code executor."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Command Line or Jupyter Code Executor?\n",
    "\n",
    "The command line code executor does not keep any state in memory between\n",
    "executions of different code blocks it receives, as it writes each code block to\n",
    "a separate file and executes the code block in a new process.\n",
    "\n",
    "Contrast to the command line code executor, the Jupyter code executor\n",
    "runs all code blocks in the same Jupyter kernel, which keeps the state\n",
    "in memory between executions.\n",
    "See the topic page for [Jupyter Code Executor](/docs/topics/code-execution/jupyter-code-executor).\n",
    "\n",
    "The choice between command line and Jupyter code executor depends on the\n",
    "nature of the code blocks in agents' conversation.\n",
    "If each code block is a \"script\" that does not use variables from\n",
    "previous code blocks, the command line code executor is a good choice.\n",
    "If some code blocks contain expensive computations (e.g., training a\n",
    "machine learning model and loading a large amount of data), and you want to\n",
    "keep the state in memory to avoid repeated computations,\n",
    "the Jupyter code executor is a better choice."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Note on User Proxy Agent and Assistant Agent\n",
    "\n",
    "### User Proxy Agent\n",
    "\n",
    "In the previous examples, we create the code executor agent directly using\n",
    "the [`ConversableAgent`](/docs/reference/agentchat/conversable_agent#conversableagent) class. Existing AutoGen examples often create \n",
    "code executor agent using the [`UserProxyAgent`](/docs/reference/agentchat/user_proxy_agent#userproxyagent) class, \n",
    "which is a subclass of\n",
    "[`ConversableAgent`](/docs/reference/agentchat/conversable_agent#conversableagent) with `human_input_mode=ALWAYS` and `llm_config=False` --\n",
    "it always requests human input for every message and does not use LLM.\n",
    "It also comes with default `description` field for each of the\n",
    "`human_input_mode` setting.\n",
    "This class is a convenient short-cut for creating an agent that is\n",
    "intended to be used as a code executor."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "### Assistant Agent\n",
    "\n",
    "In the previous examples, we created the code writer agent directly using\n",
    "the [`ConversableAgent`](/docs/reference/agentchat/conversable_agent#conversableagent) class. Existing AutoGen examples often create the code writer\n",
    "agent using the [`AssistantAgent`](/docs/reference/agentchat/assistant_agent#assistantagent) class, which is a subclass of\n",
    "[`ConversableAgent`](/docs/reference/agentchat/conversable_agent#conversableagent) with `human_input_mode=NEVER` and `code_execution_config=False` \n",
    "-- it never requests human input and does not use code executor.\n",
    "It also comes with default `system_message` and `description` fields.\n",
    "This class is a convenient short-cut for creating an agent that is\n",
    "intended to be used as a code writer and does not execute code.\n",
    "\n",
    "In fact, in the previous example we use the default `system_message` field\n",
    "of the [`AssistantAgent`](/docs/reference/agentchat/assistant_agent#assistantagent) class to instruct the code writer agent how to use\n",
    "code executor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('You are a helpful AI assistant.\\n'\n",
      " 'Solve tasks using your coding and language skills.\\n'\n",
      " 'In the following cases, suggest python code (in a python coding block) or '\n",
      " 'shell script (in a sh coding block) for the user to execute.\\n'\n",
      " '    1. When you need to collect info, use the code to output the info you '\n",
      " 'need, for example, browse or search the web, download/read a file, print the '\n",
      " 'content of a webpage or a file, get the current date/time, check the '\n",
      " 'operating system. After sufficient info is printed and the task is ready to '\n",
      " 'be solved based on your language skill, you can solve the task by yourself.\\n'\n",
      " '    2. When you need to perform some task with code, use the code to perform '\n",
      " 'the task and output the result. Finish the task smartly.\\n'\n",
      " 'Solve the task step by step if you need to. If a plan is not provided, '\n",
      " 'explain your plan first. Be clear which step uses code, and which step uses '\n",
      " 'your language skill.\\n'\n",
      " 'When using code, you must indicate the script type in the code block. The '\n",
      " 'user cannot provide any other feedback or perform any other action beyond '\n",
      " \"executing the code you suggest. The user can't modify your code. So do not \"\n",
      " \"suggest incomplete code which requires users to modify. Don't use a code \"\n",
      " \"block if it's not intended to be executed by the user.\\n\"\n",
      " 'If you want the user to save the code in a file before executing it, put # '\n",
      " \"filename: <filename> inside the code block as the first line. Don't include \"\n",
      " 'multiple code blocks in one response. Do not ask users to copy and paste the '\n",
      " \"result. Instead, use 'print' function for the output when relevant. Check \"\n",
      " 'the execution result returned by the user.\\n'\n",
      " 'If the result indicates there is an error, fix the error and output the code '\n",
      " 'again. Suggest the full code instead of partial code or code changes. If the '\n",
      " \"error can't be fixed or if the task is not solved even after the code is \"\n",
      " 'executed successfully, analyze the problem, revisit your assumption, collect '\n",
      " 'additional info you need, and think of a different approach to try.\\n'\n",
      " 'When you find an answer, verify the answer carefully. Include verifiable '\n",
      " 'evidence in your response if possible.\\n'\n",
      " 'Reply \"TERMINATE\" in the end when everything is done.\\n'\n",
      " '    ')\n"
     ]
    }
   ],
   "source": [
    "import pprint\n",
    "\n",
    "from autogen import AssistantAgent\n",
    "\n",
    "pprint.pprint(AssistantAgent.DEFAULT_SYSTEM_MESSAGE)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Best Practice\n",
    "\n",
    "It is very important to note that the [`UserProxyAgent`](/docs/reference/agentchat/user_proxy_agent#userproxyagent) and [`AssistantAgent`](/docs/reference/agentchat/assistant_agent#assistantagent)\n",
    "are meant to be shortcuts to avoid writing the `system_message` instructions\n",
    "for the [`ConversableAgent`](/docs/reference/agentchat/conversable_agent#conversableagent) class. \n",
    "They are not suitable for all use cases.\n",
    "As we will show in the next chapter, tuning the \n",
    "`system_message` field\n",
    "is vital for agent to work properly in more complex conversation patterns\n",
    "beyond two-agent chat.\n",
    "\n",
    "As a best practice, always tune your agent's `system_message` instructions\n",
    "for your specific use case and avoid subclassing [`UserProxyAgent`](/docs/reference/agentchat/user_proxy_agent#userproxyagent) and\n",
    "[`AssistantAgent`](/docs/reference/agentchat/assistant_agent#assistantagent)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "In this chapter, we introduced code executors, how to set up Docker and local\n",
    "execution, and how to use code execution in a conversation to solve tasks.\n",
    "In the next chapter, we will introduce tool use, which is similar to code\n",
    "executors but restricts what code an agent can execute."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "autogen",
   "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",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
