" 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",
"\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",
"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",
"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",
"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",
"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",
"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",
"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](../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 the some conde blocks contain expensive computation (e.g., training a\n",
"machine learning model and loading large amount of data), and you want to\n",
"keep the state in memory to avoid repeated computation,\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",
"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",