{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ae1f50ec",
   "metadata": {},
   "source": [
    "# Task Solving with Provided Tools as Functions (Asynchronous Function Calls)\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "9a71fa36",
   "metadata": {},
   "source": [
    "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",
    "````{=mdx}\n",
    ":::info Requirements\n",
    "Install `autogen-agentchat`:\n",
    "```bash\n",
    "pip install autogen-agentchat~=0.2\n",
    "```\n",
    "\n",
    "For more information, please refer to the [installation guide](/docs/installation/).\n",
    ":::\n",
    "````\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "dca301a4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\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(env_or_file=\"OAI_CONFIG_LIST\", filter_dict={\"tags\": [\"tool\"]})"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "2b9526e7",
   "metadata": {},
   "source": [
    "````{=mdx}\n",
    ":::tip\n",
    "Learn more about configuring LLMs for agents [here](/docs/topics/llm_configuration).\n",
    ":::\n",
    "````\n",
    "\n",
    "## Making Async and Sync 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`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9fb85afb",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm_config = {\n",
    "    \"config_list\": config_list,\n",
    "}\n",
    "\n",
    "coder = autogen.AssistantAgent(\n",
    "    name=\"chatbot\",\n",
    "    system_message=\"For coding tasks, only use the functions you have been provided with. You have a stopwatch and a timer, these tools can and should be used in parallel. 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",
    "    system_message=\"A proxy for the user for executing code.\",\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={\"work_dir\": \"coding\"},\n",
    ")\n",
    "\n",
    "# define functions according to the function description\n",
    "\n",
    "# An example async function registered using register_for_llm and register_for_execution decorators\n",
    "\n",
    "\n",
    "@user_proxy.register_for_execution()\n",
    "@coder.register_for_llm(description=\"create a timer for N seconds\")\n",
    "async def timer(num_seconds: Annotated[str, \"Number of seconds in the timer.\"]) -> str:\n",
    "    for i in range(int(num_seconds)):\n",
    "        time.sleep(1)\n",
    "        # should print to stdout\n",
    "    return \"Timer is done!\"\n",
    "\n",
    "\n",
    "# An example sync function registered using register_function\n",
    "def stopwatch(num_seconds: Annotated[str, \"Number of seconds in the stopwatch.\"]) -> str:\n",
    "    for i in range(int(num_seconds)):\n",
    "        time.sleep(1)\n",
    "    return \"Stopwatch is done!\"\n",
    "\n",
    "\n",
    "autogen.agentchat.register_function(\n",
    "    stopwatch,\n",
    "    caller=coder,\n",
    "    executor=user_proxy,\n",
    "    description=\"create a stopwatch for N seconds\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "159cd7b6",
   "metadata": {},
   "source": [
    "Start the conversation. `await` is used to pause and resume code execution for async IO operations. Without `await`, an async function returns a coroutine object but doesn't execute the function. With `await`, the async function is executed and the current function is paused until the awaited function returns a result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "37514ea3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33muser_proxy\u001b[0m (to chatbot):\n",
      "\n",
      "Create a timer for 5 seconds and then a stopwatch for 5 seconds.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_h6324df0CdGPDNjPO8GrnAQJ): timer *****\u001b[0m\n",
      "Arguments: \n",
      "{\"num_seconds\":\"5\"}\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING ASYNC FUNCTION timer...\u001b[0m\n"
     ]
    },
    {
     "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_h6324df0CdGPDNjPO8GrnAQJ\" *****\u001b[0m\n",
      "Timer is done!\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_7SzbQxI8Nsl6dPQtScoSGPAu): stopwatch *****\u001b[0m\n",
      "Arguments: \n",
      "{\"num_seconds\":\"5\"}\n",
      "\u001b[32m**************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING ASYNC FUNCTION stopwatch...\u001b[0m\n",
      "\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_7SzbQxI8Nsl6dPQtScoSGPAu\" *****\u001b[0m\n",
      "Stopwatch is done!\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mchatbot\u001b[0m (to user_proxy):\n",
      "\n",
      "TERMINATE\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "with Cache.disk() as cache:\n",
    "    await user_proxy.a_initiate_chat(  # noqa: F704\n",
    "        coder,\n",
    "        message=\"Create a timer for 5 seconds and then a stopwatch for 5 seconds.\",\n",
    "        cache=cache,\n",
    "    )"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "950f3de7",
   "metadata": {},
   "source": [
    "# Async Function Call with Group Chat\n",
    "Sync and async can be used in topologies beyond two agents. Below, we show this feature for a group chat."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2472f95c",
   "metadata": {},
   "outputs": [],
   "source": [
    "markdownagent = autogen.AssistantAgent(\n",
    "    name=\"Markdown_agent\",\n",
    "    system_message=\"Respond in markdown only\",\n",
    "    llm_config=llm_config,\n",
    ")\n",
    "\n",
    "# Add a function for robust group chat termination\n",
    "\n",
    "\n",
    "@user_proxy.register_for_execution()\n",
    "@markdownagent.register_for_llm()\n",
    "@coder.register_for_llm(description=\"terminate the group chat\")\n",
    "def terminate_group_chat(message: Annotated[str, \"Message to be sent to the group chat.\"]) -> str:\n",
    "    return f\"[GROUPCHAT_TERMINATE] {message}\"\n",
    "\n",
    "\n",
    "groupchat = autogen.GroupChat(agents=[user_proxy, coder, markdownagent], messages=[], max_round=12)\n",
    "\n",
    "llm_config_manager = llm_config.copy()\n",
    "llm_config_manager.pop(\"functions\", None)\n",
    "llm_config_manager.pop(\"tools\", None)\n",
    "\n",
    "manager = autogen.GroupChatManager(\n",
    "    groupchat=groupchat,\n",
    "    llm_config=llm_config_manager,\n",
    "    is_termination_msg=lambda x: \"GROUPCHAT_TERMINATE\" in x.get(\"content\", \"\"),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "612bdd22",
   "metadata": {},
   "source": [
    "Finally, we initialize the chat that would use the functions defined above:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "e2c9267a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33muser_proxy\u001b[0m (to chat_manager):\n",
      "\n",
      "\n",
      "1) Create a timer and a stopwatch for 5 seconds each in parallel.\n",
      "2) Pretty print the result as md.\n",
      "3) when 1 and 2 are done, terminate the group chat\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mchatbot\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_qlS3QkcY1NkfgpKtCoR6oGo7): timer *****\u001b[0m\n",
      "Arguments: \n",
      "{\"num_seconds\": \"5\"}\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\u001b[32m***** Suggested tool Call (call_TEHlvMgCp0S3RzBbVsVPXWeL): stopwatch *****\u001b[0m\n",
      "Arguments: \n",
      "{\"num_seconds\": \"5\"}\n",
      "\u001b[32m**************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING ASYNC FUNCTION timer...\u001b[0m\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING ASYNC FUNCTION stopwatch...\u001b[0m\n",
      "\u001b[33muser_proxy\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[33muser_proxy\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_qlS3QkcY1NkfgpKtCoR6oGo7\" *****\u001b[0m\n",
      "Timer is done!\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33muser_proxy\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_TEHlvMgCp0S3RzBbVsVPXWeL\" *****\u001b[0m\n",
      "Stopwatch is done!\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mMarkdown_agent\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Suggested tool Call (call_JuQwvj4FigfvGyBeTMglY2ee): terminate_group_chat *****\u001b[0m\n",
      "Arguments: \n",
      "{\"message\":\"Both timer and stopwatch have completed their countdowns. The group chat is now being terminated.\"}\n",
      "\u001b[32m*************************************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[35m\n",
      ">>>>>>>> EXECUTING ASYNC FUNCTION terminate_group_chat...\u001b[0m\n",
      "\u001b[33muser_proxy\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[33muser_proxy\u001b[0m (to chat_manager):\n",
      "\n",
      "\u001b[32m***** Response from calling tool \"call_JuQwvj4FigfvGyBeTMglY2ee\" *****\u001b[0m\n",
      "[GROUPCHAT_TERMINATE] Both timer and stopwatch have completed their countdowns. The group chat is now being terminated.\n",
      "\u001b[32m**********************************************************************\u001b[0m\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "message = \"\"\"\n",
    "1) Create a timer and a stopwatch for 5 seconds each in parallel.\n",
    "2) Pretty print the result as md.\n",
    "3) when 1 and 2 are done, terminate the group chat\n",
    "\"\"\"\n",
    "\n",
    "with Cache.disk() as cache:\n",
    "    await user_proxy.a_initiate_chat(  # noqa: F704\n",
    "        manager,\n",
    "        message=message,\n",
    "        cache=cache,\n",
    "    )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6d074e51",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "front_matter": {
   "description": "Learn how to implement both synchronous and asynchronous function calls using AssistantAgent and UserProxyAgent in AutoGen, with examples of their application in individual and group chat settings for task execution with language models.",
   "tags": [
    "function call",
    "tool use",
    "async"
   ]
  },
  "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.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
