{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9502d5b0",
   "metadata": {},
   "source": [
    "# OpenAI Multi Functions Agent\n",
    "\n",
    "This notebook showcases using an agent that uses the OpenAI functions ability to respond to the prompts of the user using a Large Language Model\n",
    "\n",
    "Install openai,google-search-results packages which are required as the langchain packages call them internally\n",
    "\n",
    ">pip install openai google-search-results\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c0a83623",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import SerpAPIWrapper\n",
    "from langchain.agents import initialize_agent, Tool\n",
    "from langchain.agents import AgentType\n",
    "from langchain.chat_models import ChatOpenAI"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "86198d9c",
   "metadata": {},
   "source": [
    "The agent is given ability to perform search functionalities with the respective tool\n",
    "\n",
    "SerpAPIWrapper:\n",
    ">This initializes the SerpAPIWrapper for search functionality (search).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "6fefaba2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize the OpenAI language model\n",
    "#Replace <your_api_key> in openai_api_key=\"<your_api_key>\" with your actual OpenAI key.\n",
    "llm = ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo-0613\")\n",
    "\n",
    "# Initialize the SerpAPIWrapper for search functionality\n",
    "#Replace <your_api_key> in openai_api_key=\"<your_api_key>\" with your actual SerpAPI key.\n",
    "search = SerpAPIWrapper()\n",
    "\n",
    "# Define a list of tools offered by the agent\n",
    "tools = [\n",
    "    Tool(\n",
    "        name=\"Search\",\n",
    "        func=search.run,\n",
    "        description=\"Useful when you need to answer questions about current events. You should ask targeted questions.\"\n",
    "    ),\n",
    "]\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9ff6cee9",
   "metadata": {},
   "outputs": [],
   "source": [
    "mrkl = initialize_agent(tools, llm, agent=AgentType.OPENAI_MULTI_FUNCTIONS, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "cbe95c81",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Do this so we can see exactly what's going on under the hood\n",
    "import langchain\n",
    "langchain.debug = True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "ba8e4cbe",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32;1m\u001b[1;3m[chain/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor] Entering Chain run with input:\n",
      "\u001b[0m{\n",
      "  \"input\": \"What is the weather in LA and SF?\"\n",
      "}\n",
      "\u001b[32;1m\u001b[1;3m[llm/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 2:llm:ChatOpenAI] Entering LLM run with input:\n",
      "\u001b[0m{\n",
      "  \"prompts\": [\n",
      "    \"System: You are a helpful AI assistant.\\nHuman: What is the weather in LA and SF?\"\n",
      "  ]\n",
      "}\n",
      "\u001b[36;1m\u001b[1;3m[llm/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 2:llm:ChatOpenAI] [2.91s] Exiting LLM run with output:\n",
      "\u001b[0m{\n",
      "  \"generations\": [\n",
      "    [\n",
      "      {\n",
      "        \"text\": \"\",\n",
      "        \"generation_info\": null,\n",
      "        \"message\": {\n",
      "          \"content\": \"\",\n",
      "          \"additional_kwargs\": {\n",
      "            \"function_call\": {\n",
      "              \"name\": \"tool_selection\",\n",
      "              \"arguments\": \"{\\n  \\\"actions\\\": [\\n    {\\n      \\\"action_name\\\": \\\"Search\\\",\\n      \\\"action\\\": {\\n        \\\"tool_input\\\": \\\"weather in Los Angeles\\\"\\n      }\\n    },\\n    {\\n      \\\"action_name\\\": \\\"Search\\\",\\n      \\\"action\\\": {\\n        \\\"tool_input\\\": \\\"weather in San Francisco\\\"\\n      }\\n    }\\n  ]\\n}\"\n",
      "            }\n",
      "          },\n",
      "          \"example\": false\n",
      "        }\n",
      "      }\n",
      "    ]\n",
      "  ],\n",
      "  \"llm_output\": {\n",
      "    \"token_usage\": {\n",
      "      \"prompt_tokens\": 81,\n",
      "      \"completion_tokens\": 75,\n",
      "      \"total_tokens\": 156\n",
      "    },\n",
      "    \"model_name\": \"gpt-3.5-turbo-0613\"\n",
      "  },\n",
      "  \"run\": null\n",
      "}\n",
      "\u001b[32;1m\u001b[1;3m[tool/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 3:tool:Search] Entering Tool run with input:\n",
      "\u001b[0m\"{'tool_input': 'weather in Los Angeles'}\"\n",
      "\u001b[36;1m\u001b[1;3m[tool/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 3:tool:Search] [608.693ms] Exiting Tool run with output:\n",
      "\u001b[0m\"Mostly cloudy early, then sunshine for the afternoon. High 76F. Winds SW at 5 to 10 mph. Humidity59%.\"\n",
      "\u001b[32;1m\u001b[1;3m[tool/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 4:tool:Search] Entering Tool run with input:\n",
      "\u001b[0m\"{'tool_input': 'weather in San Francisco'}\"\n",
      "\u001b[36;1m\u001b[1;3m[tool/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 4:tool:Search] [517.475ms] Exiting Tool run with output:\n",
      "\u001b[0m\"Partly cloudy this evening, then becoming cloudy after midnight. Low 53F. Winds WSW at 10 to 20 mph. Humidity83%.\"\n",
      "\u001b[32;1m\u001b[1;3m[llm/start]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 5:llm:ChatOpenAI] Entering LLM run with input:\n",
      "\u001b[0m{\n",
      "  \"prompts\": [\n",
      "    \"System: You are a helpful AI assistant.\\nHuman: What is the weather in LA and SF?\\nAI: {'name': 'tool_selection', 'arguments': '{\\\\n  \\\"actions\\\": [\\\\n    {\\\\n      \\\"action_name\\\": \\\"Search\\\",\\\\n      \\\"action\\\": {\\\\n        \\\"tool_input\\\": \\\"weather in Los Angeles\\\"\\\\n      }\\\\n    },\\\\n    {\\\\n      \\\"action_name\\\": \\\"Search\\\",\\\\n      \\\"action\\\": {\\\\n        \\\"tool_input\\\": \\\"weather in San Francisco\\\"\\\\n      }\\\\n    }\\\\n  ]\\\\n}'}\\nFunction: Mostly cloudy early, then sunshine for the afternoon. High 76F. Winds SW at 5 to 10 mph. Humidity59%.\\nAI: {'name': 'tool_selection', 'arguments': '{\\\\n  \\\"actions\\\": [\\\\n    {\\\\n      \\\"action_name\\\": \\\"Search\\\",\\\\n      \\\"action\\\": {\\\\n        \\\"tool_input\\\": \\\"weather in Los Angeles\\\"\\\\n      }\\\\n    },\\\\n    {\\\\n      \\\"action_name\\\": \\\"Search\\\",\\\\n      \\\"action\\\": {\\\\n        \\\"tool_input\\\": \\\"weather in San Francisco\\\"\\\\n      }\\\\n    }\\\\n  ]\\\\n}'}\\nFunction: Partly cloudy this evening, then becoming cloudy after midnight. Low 53F. Winds WSW at 10 to 20 mph. Humidity83%.\"\n",
      "  ]\n",
      "}\n",
      "\u001b[36;1m\u001b[1;3m[llm/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor > 5:llm:ChatOpenAI] [2.33s] Exiting LLM run with output:\n",
      "\u001b[0m{\n",
      "  \"generations\": [\n",
      "    [\n",
      "      {\n",
      "        \"text\": \"The weather in Los Angeles is mostly cloudy with a high of 76°F and a humidity of 59%. The weather in San Francisco is partly cloudy in the evening, becoming cloudy after midnight, with a low of 53°F and a humidity of 83%.\",\n",
      "        \"generation_info\": null,\n",
      "        \"message\": {\n",
      "          \"content\": \"The weather in Los Angeles is mostly cloudy with a high of 76°F and a humidity of 59%. The weather in San Francisco is partly cloudy in the evening, becoming cloudy after midnight, with a low of 53°F and a humidity of 83%.\",\n",
      "          \"additional_kwargs\": {},\n",
      "          \"example\": false\n",
      "        }\n",
      "      }\n",
      "    ]\n",
      "  ],\n",
      "  \"llm_output\": {\n",
      "    \"token_usage\": {\n",
      "      \"prompt_tokens\": 307,\n",
      "      \"completion_tokens\": 54,\n",
      "      \"total_tokens\": 361\n",
      "    },\n",
      "    \"model_name\": \"gpt-3.5-turbo-0613\"\n",
      "  },\n",
      "  \"run\": null\n",
      "}\n",
      "\u001b[36;1m\u001b[1;3m[chain/end]\u001b[0m \u001b[1m[1:chain:AgentExecutor] [6.37s] Exiting Chain run with output:\n",
      "\u001b[0m{\n",
      "  \"output\": \"The weather in Los Angeles is mostly cloudy with a high of 76°F and a humidity of 59%. The weather in San Francisco is partly cloudy in the evening, becoming cloudy after midnight, with a low of 53°F and a humidity of 83%.\"\n",
      "}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'The weather in Los Angeles is mostly cloudy with a high of 76°F and a humidity of 59%. The weather in San Francisco is partly cloudy in the evening, becoming cloudy after midnight, with a low of 53°F and a humidity of 83%.'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mrkl.run(\n",
    "    \"What is the weather in LA and SF?\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f5f6743",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.9.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
