{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# User Defined Functions\n",
    "\n",
    "````{=mdx}\n",
    ":::note\n",
    "This is experimental and not *yet* supported by all executors. At this stage only [`LocalCommandLineCodeExecutor`](/docs/reference/coding/local_commandline_code_executor#localcommandlinecodeexecutor) is supported.\n",
    "\n",
    "\n",
    "Currently, the method of registering tools and using this feature are different. We would like to unify them. See Github issue [here](https://github.com/microsoft/autogen/issues/2101)\n",
    ":::\n",
    "````\n",
    "\n",
    "User defined functions allow you to define Python functions in your AutoGen program and then provide these to be used by your executor. This allows you to provide your agents with tools without using traditional tool calling APIs. Currently only Python is supported for this feature.\n",
    "\n",
    "There are several steps involved:\n",
    "\n",
    "1. Define the function\n",
    "2. Provide the function to the executor\n",
    "3. Explain to the code writing agent how to use the function\n",
    "\n",
    "\n",
    "## Define the function\n",
    "\n",
    "````{=mdx}\n",
    ":::warning\n",
    "Keep in mind that the entire source code of these functions will be available to the executor. This means that you should not include any sensitive information in the function as an LLM agent may be able to access it.\n",
    ":::\n",
    "````\n",
    "\n",
    "If the function does not require any external imports or dependencies then you can simply use the function. For example:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def add_two_numbers(a: int, b: int) -> int:\n",
    "    \"\"\"Add two numbers together.\"\"\"\n",
    "    return a + b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This would be a valid standalone function.\n",
    "\n",
    "````{=mdx}\n",
    ":::tip\n",
    "Using type hints and docstrings are not required but are highly recommended. They will help the code writing agent understand the function and how to use it.\n",
    ":::\n",
    "````\n",
    "\n",
    "If the function requires external imports or dependencies then you can use the `@with_requirements` decorator to specify the requirements. For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas\n",
    "\n",
    "from autogen.coding.func_with_reqs import with_requirements\n",
    "\n",
    "\n",
    "@with_requirements(python_packages=[\"pandas\"], global_imports=[\"pandas\"])\n",
    "def load_data() -> pandas.DataFrame:\n",
    "    \"\"\"Load some sample data.\n",
    "\n",
    "    Returns:\n",
    "        pandas.DataFrame: A DataFrame with the following columns: name(str), location(str), age(int)\n",
    "    \"\"\"\n",
    "    data = {\n",
    "        \"name\": [\"John\", \"Anna\", \"Peter\", \"Linda\"],\n",
    "        \"location\": [\"New York\", \"Paris\", \"Berlin\", \"London\"],\n",
    "        \"age\": [24, 13, 53, 33],\n",
    "    }\n",
    "    return pandas.DataFrame(data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you wanted to rename `pandas` to `pd` or import `DataFrame` directly you could do the following:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from pandas import DataFrame\n",
    "from pandas import DataFrame as df\n",
    "\n",
    "from autogen.coding.func_with_reqs import Alias, ImportFromModule, with_requirements\n",
    "\n",
    "\n",
    "@with_requirements(python_packages=[\"pandas\"], global_imports=[Alias(\"pandas\", \"pd\")])\n",
    "def some_func1() -> pd.DataFrame: ...\n",
    "\n",
    "\n",
    "@with_requirements(python_packages=[\"pandas\"], global_imports=[ImportFromModule(\"pandas\", \"DataFrame\")])\n",
    "def some_func2() -> DataFrame: ...\n",
    "\n",
    "\n",
    "@with_requirements(python_packages=[\"pandas\"], global_imports=[ImportFromModule(\"pandas\", Alias(\"DataFrame\", \"df\"))])\n",
    "def some_func3() -> df: ..."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Provide the function to the executor\n",
    "\n",
    "Functions can be loaded into the executor in its constructor. For example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "\n",
    "from autogen.coding import CodeBlock, LocalCommandLineCodeExecutor\n",
    "\n",
    "work_dir = Path(\"coding\")\n",
    "work_dir.mkdir(exist_ok=True)\n",
    "\n",
    "executor = LocalCommandLineCodeExecutor(work_dir=work_dir, functions=[add_two_numbers, load_data])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Before we get an agent involved, we can sanity check that when the agent writes code that looks like this the executor will be able to handle it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "exit_code=0 output='3\\n' code_file='/Users/jackgerrits/w/autogen/website/docs/topics/code-execution/coding/tmp_code_1958fe3aea3e8e3c6e907fe951b5f6ab.py'\n"
     ]
    }
   ],
   "source": [
    "code = f\"\"\"\n",
    "from {executor.functions_module} import add_two_numbers\n",
    "\n",
    "print(add_two_numbers(1, 2))\n",
    "\"\"\"\n",
    "\n",
    "print(\n",
    "    executor.execute_code_blocks(\n",
    "        code_blocks=[\n",
    "            CodeBlock(language=\"python\", code=code),\n",
    "        ]\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And we can try the function that required a dependency and import too."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    name  location  age\n",
      "0   John  New York   24\n",
      "1   Anna     Paris   13\n",
      "2  Peter    Berlin   53\n",
      "3  Linda    London   33\n",
      "\n"
     ]
    }
   ],
   "source": [
    "code = f\"\"\"\n",
    "from {executor.functions_module} import load_data\n",
    "\n",
    "print(load_data())\n",
    "\"\"\"\n",
    "\n",
    "result = executor.execute_code_blocks(\n",
    "    code_blocks=[\n",
    "        CodeBlock(language=\"python\", code=code),\n",
    "    ]\n",
    ")\n",
    "\n",
    "print(result.output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Limitations\n",
    "\n",
    "- Only Python is supported currently\n",
    "- The function must not depend on any globals or external state as it is loaded as source code \n",
    "\n",
    "## Explain to the code writing agent how to use the function\n",
    "\n",
    "Now that the function is available to be called by the executor, you can explain to the code writing agent how to use the function. This step is very important as by default it will not know about it.\n",
    "\n",
    "There is a utility function that you can use to generate a default prompt that describes the available functions and how to use them. This function can have its template overridden to provide a custom message, or you can use a different prompt all together.\n",
    "\n",
    "For example, you could extend the system message from the page about local execution with a new section that describes the functions available."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "You have been given coding capability to solve tasks using Python code.\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",
      "You have access to the following user defined functions. They can be accessed from the module called `functions` by their function names.\n",
      "\n",
      "For example, if there was a function called `foo` you could import it by writing `from functions import foo`\n",
      "\n",
      "def add_two_numbers(a: int, b: int) -> int:\n",
      "    \"\"\"Add two numbers together.\"\"\"\n",
      "    ...\n",
      "\n",
      "def load_data() -> pandas.core.frame.DataFrame:\n",
      "    \"\"\"Load some sample data.\n",
      "\n",
      "        Returns:\n",
      "            pandas.DataFrame: A DataFrame with the following columns: name(str), location(str), age(int)\n",
      "    \"\"\"\n",
      "    ...\n",
      "\n"
     ]
    }
   ],
   "source": [
    "nlnl = \"\\n\\n\"\n",
    "code_writer_system_message = \"\"\"\n",
    "You have been given coding capability to solve tasks using Python code.\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",
    "\"\"\"\n",
    "\n",
    "# Add on the new functions\n",
    "code_writer_system_message += executor.format_functions_for_prompt()\n",
    "\n",
    "print(code_writer_system_message)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then you can use this system message for your code writing agent."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "from autogen import ConversableAgent\n",
    "\n",
    "code_writer_agent = ConversableAgent(\n",
    "    \"code_writer\",\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",
    "    max_consecutive_auto_reply=2,\n",
    "    human_input_mode=\"NEVER\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we can setup the code execution agent using the local command line executor we defined earlier."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "code_executor_agent = ConversableAgent(\n",
    "    name=\"code_executor_agent\",\n",
    "    llm_config=False,\n",
    "    code_execution_config={\n",
    "        \"executor\": executor,\n",
    "    },\n",
    "    human_input_mode=\"NEVER\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then, we can start the conversation and get the agent to process the dataframe we provided."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001B[33mcode_executor_agent\u001B[0m (to code_writer):\n",
      "\n",
      "Please use the load_data function to load the data and please calculate the average age of all people.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001B[33mcode_writer\u001B[0m (to code_executor_agent):\n",
      "\n",
      "Below is the python code to load the data using the `load_data()` function and calculate the average age of all people. \n",
      "\n",
      "```python\n",
      "# python code\n",
      "from functions import load_data\n",
      "import numpy as np\n",
      "\n",
      "# Load the data\n",
      "df = load_data()\n",
      "\n",
      "# Calculate the average age\n",
      "avg_age = np.mean(df['age'])\n",
      "\n",
      "print(\"The average age is\", avg_age)\n",
      "```\n",
      "\n",
      "This code starts by importing the `load_data()` function. It then uses this function to load the data into a variable `df`. Afterwards, it calculates the average (mean) of the 'age' column in the DataFrame, before printing the result.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001B[31m\n",
      ">>>>>>>> EXECUTING CODE BLOCK (inferred language is python)...\u001B[0m\n",
      "\u001B[33mcode_executor_agent\u001B[0m (to code_writer):\n",
      "\n",
      "exitcode: 0 (execution succeeded)\n",
      "Code output: The average age is 30.75\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001B[33mcode_writer\u001B[0m (to code_executor_agent):\n",
      "\n",
      "Great! The code worked fine. So, the average age of all people in the dataset is 30.75 years.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001B[33mcode_executor_agent\u001B[0m (to code_writer):\n",
      "\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "chat_result = code_executor_agent.initiate_chat(\n",
    "    code_writer_agent,\n",
    "    message=\"Please use the load_data function to load the data and please calculate the average age of all people.\",\n",
    "    summary_method=\"reflection_with_llm\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can see the summary of the calculation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The average age of all people in the dataset is 30.75 years.\n"
     ]
    }
   ],
   "source": [
    "print(chat_result.summary)"
   ]
  }
 ],
 "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.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
