{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "0c3f1df8",
   "metadata": {},
   "source": [
    "# Self-ask with search\n",
    "\n",
    "This walkthrough showcases the self-ask with search chain."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2018da2d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import AgentType, Tool, initialize_agent\n",
    "from langchain.llms import OpenAI\n",
    "from langchain.utilities import SerpAPIWrapper\n",
    "\n",
    "llm = OpenAI(temperature=0)\n",
    "search = SerpAPIWrapper()\n",
    "tools = [\n",
    "    Tool(\n",
    "        name=\"Intermediate Answer\",\n",
    "        func=search.run,\n",
    "        description=\"useful for when you need to ask with search\",\n",
    "    )\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "769c5940",
   "metadata": {},
   "source": [
    "## Using LangChain Expression Language\n",
    "\n",
    "First we will show how to construct this agent from components using LangChain Expression Language"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "6be0e94d",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain import hub\n",
    "from langchain.agents.format_scratchpad import format_log_to_str\n",
    "from langchain.agents.output_parsers import SelfAskOutputParser"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "933ca47b",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt = hub.pull(\"hwchase17/self-ask-with-search\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "d1437a27",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm_with_stop = llm.bind(stop=[\"\\nIntermediate answer:\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "d793401e",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent = (\n",
    "    {\n",
    "        \"input\": lambda x: x[\"input\"],\n",
    "        # Use some custom observation_prefix/llm_prefix for formatting\n",
    "        \"agent_scratchpad\": lambda x: format_log_to_str(\n",
    "            x[\"intermediate_steps\"],\n",
    "            observation_prefix=\"\\nIntermediate answer: \",\n",
    "            llm_prefix=\"\",\n",
    "        ),\n",
    "    }\n",
    "    | prompt\n",
    "    | llm_with_stop\n",
    "    | SelfAskOutputParser()\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "643c3bfa",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.agents import AgentExecutor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "a1bb513c",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "5181f35f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m Yes.\n",
      "Follow up: Who is the reigning men's U.S. Open champion?\u001b[0m\u001b[36;1m\u001b[1;3mMen's US Open Tennis Champions Novak Djokovic earned his 24th major singles title against 2021 US Open champion Daniil Medvedev, 6-3, 7-6 (7-5), 6-3. The victory ties the Serbian player with the legendary Margaret Court for the most Grand Slam wins across both men's and women's singles.\u001b[0m\u001b[32;1m\u001b[1;3m\n",
      "Follow up: Where is Novak Djokovic from?\u001b[0m\u001b[36;1m\u001b[1;3mBelgrade, Serbia\u001b[0m\u001b[32;1m\u001b[1;3m\n",
      "So the final answer is: Belgrade, Serbia\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'input': \"What is the hometown of the reigning men's U.S. Open champion?\",\n",
       " 'output': 'Belgrade, Serbia'}"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "agent_executor.invoke(\n",
    "    {\"input\": \"What is the hometown of the reigning men's U.S. Open champion?\"}\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6556f348",
   "metadata": {},
   "source": [
    "## Use off-the-shelf agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "7e3b513e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m Yes.\n",
      "Follow up: Who is the reigning men's U.S. Open champion?\u001b[0m\n",
      "Intermediate answer: \u001b[36;1m\u001b[1;3mMen's US Open Tennis Champions Novak Djokovic earned his 24th major singles title against 2021 US Open champion Daniil Medvedev, 6-3, 7-6 (7-5), 6-3. The victory ties the Serbian player with the legendary Margaret Court for the most Grand Slam wins across both men's and women's singles.\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3m\n",
      "Follow up: Where is Novak Djokovic from?\u001b[0m\n",
      "Intermediate answer: \u001b[36;1m\u001b[1;3mBelgrade, Serbia\u001b[0m\n",
      "\u001b[32;1m\u001b[1;3mSo the final answer is: Belgrade, Serbia\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'Belgrade, Serbia'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "self_ask_with_search = initialize_agent(\n",
    "    tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True\n",
    ")\n",
    "self_ask_with_search.run(\n",
    "    \"What is the hometown of the reigning men's U.S. Open champion?\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b2e4d6bc",
   "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.10.1"
  },
  "vscode": {
   "interpreter": {
    "hash": "b1677b440931f40d89ef8be7bf03acb108ce003de0ac9b18e8d43753ea2e7103"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
