{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ae1f50ec",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/microsoft/autogen/blob/main/notebook/agentchat_function_call.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "9a71fa36",
   "metadata": {},
   "source": [
    "# Auto Generated Agent Chat: Task Solving with Provided Tools as Functions\n",
    "\n",
    "AutoGen offers conversable agents powered by LLM, tool, or human, which can be used to perform tasks collectively via automated chat. This framework allows tool use and human participation through multi-agent conversation. Please find documentation about this feature [here](https://microsoft.github.io/autogen/docs/Use-Cases/agent_chat).\n",
    "\n",
    "In this notebook, we demonstrate how to use `AssistantAgent` and `UserProxyAgent` to make function calls with the new feature of OpenAI models (in model version 0613). A specified prompt and function configs must be passed to `AssistantAgent` to initialize the agent. The corresponding functions must be passed to `UserProxyAgent`, which will execute any function calls made by `AssistantAgent`. Besides this requirement of matching descriptions with functions, we recommend checking the system message in the `AssistantAgent` to ensure the instructions align with the function call descriptions.\n",
    "\n",
    "## Requirements\n",
    "\n",
    "AutoGen requires `Python>=3.8`. To run this notebook example, please Install `autogen-agentchat`:\n",
    "```bash\n",
    "pip install autogen-agentchat~=0.2\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "2b803c17",
   "metadata": {},
   "outputs": [],
   "source": [
    "# %pip install \"autogen-agentchat~=0.2\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "5ebd2397",
   "metadata": {},
   "source": [
    "## Set your API Endpoint\n",
    "\n",
    "The [`config_list_from_json`](https://microsoft.github.io/autogen/docs/reference/oai/openai_utils#config_list_from_json) function loads a list of configurations from an environment variable or a json file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "dca301a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython import get_ipython\n",
    "from typing_extensions import Annotated\n",
    "\n",
    "import autogen\n",
    "from autogen.cache import Cache\n",
    "\n",
    "config_list = autogen.config_list_from_json(\n",
    "    \"OAI_CONFIG_LIST\",\n",
    "    filter_dict={\"tags\": [\"tool\"]},  # comment out to get all\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "92fde41f",
   "metadata": {},
   "source": [
    "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 tags (you can filter by other keys as well). Only the configs with matching tags are kept in the list based on the filter condition.\n",
    "\n",
    "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",
    "        'tags': ['tool', 'gpt-4'],\n",
    "    },\n",
    "    {\n",
    "        'model': 'gpt-3.5-turbo',\n",
    "        'api_key': '<your Azure OpenAI API key here>',\n",
    "        'base_url': '<your Azure OpenAI API base here>',\n",
    "        'api_type': 'azure',\n",
    "        'api_version': '2024-02-01\n",
    "        'tags': ['tool', 'gpt-3.5-turbo'],\n",
    "    },\n",
    "    {\n",
    "        'model': 'gpt-3.5-turbo-16k',\n",
    "        'api_key': '<your Azure OpenAI API key here>',\n",
    "        'base_url': '<your Azure OpenAI API base here>',\n",
    "        'api_type': 'azure',\n",
    "        'api_version': '2024-02-01\n",
    "        'tags': ['tool', 'gpt-3.5-turbo-16k'],\n",
    "    },\n",
    "]\n",
    "```\n",
    "\n",
    "You can set the value of config_list in any way you prefer. Please refer to this [notebook](https://github.com/microsoft/autogen/blob/0.2/website/docs/topics/llm_configuration.ipynb) for full code examples of the different methods."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "2b9526e7",
   "metadata": {},
   "source": [
    "## Making Function Calls\n",
    "\n",
    "In this example, we demonstrate function call execution with `AssistantAgent` and `UserProxyAgent`. With the default system prompt of `AssistantAgent`, we allow the LLM assistant to perform tasks with code, and the `UserProxyAgent` would extract code blocks from the LLM response and execute them. With the new \"function_call\" feature, we define functions and specify the description of the function in the OpenAI config for the `AssistantAgent`. Then we register the functions in `UserProxyAgent`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "9fb85afb",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm_config = {\n",
    "    \"config_list\": config_list,\n",
    "    \"timeout\": 120,\n",
    "}\n",
    "chatbot = autogen.AssistantAgent(\n",
    "    name=\"chatbot\",\n",
    "    system_message=\"For coding tasks, only use the functions you have been provided with. Reply TERMINATE when the task is done.\",\n",
    "    llm_config=llm_config,\n",
    ")\n",
    "\n",
    "# create a UserProxyAgent instance named \"user_proxy\"\n",
    "user_proxy = autogen.UserProxyAgent(\n",
    "    name=\"user_proxy\",\n",
    "    is_termination_msg=lambda x: x.get(\"content\", \"\") and x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n",
    "    human_input_mode=\"NEVER\",\n",
    "    max_consecutive_auto_reply=10,\n",
    "    code_execution_config={\n",
    "        \"work_dir\": \"coding\",\n",
    "        \"use_docker\": False,\n",
    "    },  # Please set use_docker=True if docker is available to run the generated code. Using docker is safer than running the generated code directly.\n",
    ")\n",
    "\n",
    "\n",
    "# define functions according to the function description\n",
    "\n",
    "\n",
    "# one way of registering functions is to use the register_for_llm and register_for_execution decorators\n",
    "@user_proxy.register_for_execution()\n",
    "@chatbot.register_for_llm(name=\"python\", description=\"run cell in ipython and return the execution result.\")\n",
    "def exec_python(cell: Annotated[str, \"Valid Python cell to execute.\"]) -> str:\n",
    "    ipython = get_ipython()\n",
    "    result = ipython.run_cell(cell)\n",
    "    log = str(result.result)\n",
    "    if result.error_before_exec is not None:\n",
    "        log += f\"\\n{result.error_before_exec}\"\n",
    "    if result.error_in_exec is not None:\n",
    "        log += f\"\\n{result.error_in_exec}\"\n",
    "    return log\n",
    "\n",
    "\n",
    "# another way of registering functions is to use the register_function\n",
    "def exec_sh(script: Annotated[str, \"Valid Python cell to execute.\"]) -> str:\n",
    "    return user_proxy.execute_code_blocks([(\"sh\", script)])\n",
    "\n",
    "\n",
    "autogen.agentchat.register_function(\n",
    "    exec_python,\n",
    "    caller=chatbot,\n",
    "    executor=user_proxy,\n",
    "    name=\"sh\",\n",
    "    description=\"run a shell script and return the execution result.\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f6952220",
   "metadata": {},
   "source": [
    "Finally, we initialize the chat that would use the functions defined above:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "27d3e43a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
      "\n",
      "Draw two agents chatting with each other with an example dialog. Don't add plt.show().\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
      "\n",
      "\u001b[32m***** Suggested tool call (call_BiLzujDvfB7WMZ0hqcgBdjN2): python *****\u001b[0m\n",
      "Arguments: \n",
      "{\"cell\":\"import matplotlib.pyplot as plt\\nimport numpy as np\\n\\n# Create a simple representation of two agents\\nagent1_x, agent1_y = [1, 2], [1, 1]\\nagent2_x, agent2_y = [4, 3], [1, 1]\\n\\n# Create dialog bubbles\\nbubble1_x = np.linspace(1.5, 2.5, 100)\\nbubble1_y = np.sin(np.pi * (bubble1_x - 1.5)) + 1.2\\nbubble2_x = np.linspace(3.5, 2.5, 100)\\nbubble2_y = np.sin(np.pi * (bubble2_x - 2.5)) + 1.2\\n\\n# Drawing agents and dialog bubbles\\nplt.figure(figsize=(6, 3))\\nplt.plot(agent1_x, agent1_y, 'ko-', markersize=20)\\nplt.plot(agent2_x, agent2_y, 'ko-', markersize=20)\\nplt.plot(bubble1_x, bubble1_y, 'k')\\nplt.plot(bubble2_x, bubble2_y, 'k')\\nplt.fill_between(bubble1_x, 1, bubble1_y, color = 'grey', alpha = 0.5)\\nplt.fill_between(bubble2_x, 1, bubble2_y, color = 'grey', alpha = 0.5)\\n\\n# Example Dialog\\nplt.text(1.5, 1.5, 'Hi!', fontsize=12)\\nplt.text(3.5, 1.5, 'Hello!', fontsize=12)\\n\\nplt.xlim(0, 5)\\nplt.ylim(0, 2.5)\\nplt.axis('off')\\n\"}\n",
      "\u001b[32m***********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING FUNCTION python...\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "(0.0, 5.0, 0.0, 2.5)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 10128 characters]",
      "text/plain": [
       "<Figure size 600x300 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
      "\n",
      "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
      "\n",
      "\u001b[32m***** Response from calling tool (call_BiLzujDvfB7WMZ0hqcgBdjN2) *****\u001b[0m\n",
      "(0.0, 5.0, 0.0, 2.5)\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
      "\n",
      "I've drawn two agents chatting with each other, including example dialogues saying \"Hi!\" and \"Hello!\" within their speech bubbles. This visualization is created using matplotlib, and the conversation is represented graphically with the agents and their dialogue bubbles placed on a 2D plot. The drawing does not include `plt.show()`, adhering to your instruction.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
      "\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
      "\n",
      "It seems your last message was empty. How can I assist you further?\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "with Cache.disk() as cache:\n",
    "    # start the conversation\n",
    "    user_proxy.initiate_chat(\n",
    "        chatbot,\n",
    "        message=\"Draw two agents chatting with each other with an example dialog. Don't add plt.show().\",\n",
    "        cache=cache,\n",
    "        max_turns=3,\n",
    "    )"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "flaml_dev",
   "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.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
