{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a5cf6c49",
   "metadata": {},
   "source": [
    "# Router\n",
    "\n",
    "This notebook demonstrates how to use the `RouterChain` paradigm to create a chain that dynamically selects the next chain to use for a given input. \n",
    "\n",
    "Router chains are made up of two components:\n",
    "\n",
    "- The `RouterChain` itself (responsible for selecting the next chain to call)\n",
    "- `destination_chains`: chains that the router chain can route to\n",
    "\n",
    "\n",
    "In this notebook, we will focus on the different types of routing chains. We will show these routing chains used in a `MultiPromptChain` to create a question-answering chain that selects the prompt which is most relevant for a given question, and then answers the question using that prompt."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "e8d624d4",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chains.router import MultiPromptChain\n",
    "from langchain.llms import OpenAI\n",
    "from langchain.chains import ConversationChain\n",
    "from langchain.chains.llm import LLMChain\n",
    "from langchain.prompts import PromptTemplate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8d11fa5c",
   "metadata": {},
   "outputs": [],
   "source": [
    "physics_template = \"\"\"You are a very smart physics professor. \\\n",
    "You are great at answering questions about physics in a concise and easy to understand manner. \\\n",
    "When you don't know the answer to a question you admit that you don't know.\n",
    "\n",
    "Here is a question:\n",
    "{input}\"\"\"\n",
    "\n",
    "\n",
    "math_template = \"\"\"You are a very good mathematician. You are great at answering math questions. \\\n",
    "You are so good because you are able to break down hard problems into their component parts, \\\n",
    "answer the component parts, and then put them together to answer the broader question.\n",
    "\n",
    "Here is a question:\n",
    "{input}\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d0b8856e",
   "metadata": {},
   "outputs": [],
   "source": [
    "prompt_infos = [\n",
    "    {\n",
    "        \"name\": \"physics\",\n",
    "        \"description\": \"Good for answering questions about physics\",\n",
    "        \"prompt_template\": physics_template,\n",
    "    },\n",
    "    {\n",
    "        \"name\": \"math\",\n",
    "        \"description\": \"Good for answering math questions\",\n",
    "        \"prompt_template\": math_template,\n",
    "    },\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "de2dc0f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "llm = OpenAI()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "f27c154a",
   "metadata": {},
   "outputs": [],
   "source": [
    "destination_chains = {}\n",
    "for p_info in prompt_infos:\n",
    "    name = p_info[\"name\"]\n",
    "    prompt_template = p_info[\"prompt_template\"]\n",
    "    prompt = PromptTemplate(template=prompt_template, input_variables=[\"input\"])\n",
    "    chain = LLMChain(llm=llm, prompt=prompt)\n",
    "    destination_chains[name] = chain\n",
    "default_chain = ConversationChain(llm=llm, output_key=\"text\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83cea2d5",
   "metadata": {},
   "source": [
    "## LLMRouterChain\n",
    "\n",
    "This chain uses an LLM to determine how to route things."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "60142895",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser\n",
    "from langchain.chains.router.multi_prompt_prompt import MULTI_PROMPT_ROUTER_TEMPLATE"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "60769f96",
   "metadata": {},
   "outputs": [],
   "source": [
    "destinations = [f\"{p['name']}: {p['description']}\" for p in prompt_infos]\n",
    "destinations_str = \"\\n\".join(destinations)\n",
    "router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(destinations=destinations_str)\n",
    "router_prompt = PromptTemplate(\n",
    "    template=router_template,\n",
    "    input_variables=[\"input\"],\n",
    "    output_parser=RouterOutputParser(),\n",
    ")\n",
    "router_chain = LLMRouterChain.from_llm(llm, router_prompt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "db679975",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = MultiPromptChain(\n",
    "    router_chain=router_chain,\n",
    "    destination_chains=destination_chains,\n",
    "    default_chain=default_chain,\n",
    "    verbose=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "90fd594c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n",
      "physics: {'input': 'What is black body radiation?'}\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "\n",
      "\n",
      "Black body radiation is the term used to describe the electromagnetic radiation emitted by a “black body”—an object that absorbs all radiation incident upon it. A black body is an idealized physical body that absorbs all incident electromagnetic radiation, regardless of frequency or angle of incidence. It does not reflect, emit or transmit energy. This type of radiation is the result of the thermal motion of the body's atoms and molecules, and it is emitted at all wavelengths. The spectrum of radiation emitted is described by Planck's law and is known as the black body spectrum.\n"
     ]
    }
   ],
   "source": [
    "print(chain.run(\"What is black body radiation?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "b8c83765",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n",
      "math: {'input': 'What is the first prime number greater than 40 such that one plus the prime number is divisible by 3?'}\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "?\n",
      "\n",
      "The answer is 43. One plus 43 is 44 which is divisible by 3.\n"
     ]
    }
   ],
   "source": [
    "print(\n",
    "    chain.run(\n",
    "        \"What is the first prime number greater than 40 such that one plus the prime number is divisible by 3?\"\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "74c6bba7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n",
      "None: {'input': 'What is the name of the type of cloud that rains?'}\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      " The type of cloud that rains is called a cumulonimbus cloud. It is a tall and dense cloud that is often accompanied by thunder and lightning.\n"
     ]
    }
   ],
   "source": [
    "print(chain.run(\"What is the name of the type of cloud that rains?\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "239d4743",
   "metadata": {},
   "source": [
    "## EmbeddingRouterChain\n",
    "\n",
    "The `EmbeddingRouterChain` uses embeddings and similarity to route between destination chains."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "55c3ed0e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chains.router.embedding_router import EmbeddingRouterChain\n",
    "from langchain.embeddings import CohereEmbeddings\n",
    "from langchain.vectorstores import Chroma"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "572a5082",
   "metadata": {},
   "outputs": [],
   "source": [
    "names_and_descriptions = [\n",
    "    (\"physics\", [\"for questions about physics\"]),\n",
    "    (\"math\", [\"for questions about math\"]),\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "50221efe",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using embedded DuckDB without persistence: data will be transient\n"
     ]
    }
   ],
   "source": [
    "router_chain = EmbeddingRouterChain.from_names_and_descriptions(\n",
    "    names_and_descriptions, Chroma, CohereEmbeddings(), routing_keys=[\"input\"]\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "ff7996a0",
   "metadata": {},
   "outputs": [],
   "source": [
    "chain = MultiPromptChain(\n",
    "    router_chain=router_chain,\n",
    "    destination_chains=destination_chains,\n",
    "    default_chain=default_chain,\n",
    "    verbose=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "99270cc9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n",
      "physics: {'input': 'What is black body radiation?'}\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "\n",
      "\n",
      "Black body radiation is the emission of energy from an idealized physical body (known as a black body) that is in thermal equilibrium with its environment. It is emitted in a characteristic pattern of frequencies known as a black-body spectrum, which depends only on the temperature of the body. The study of black body radiation is an important part of astrophysics and atmospheric physics, as the thermal radiation emitted by stars and planets can often be approximated as black body radiation.\n"
     ]
    }
   ],
   "source": [
    "print(chain.run(\"What is black body radiation?\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "b5ce6238",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new MultiPromptChain chain...\u001b[0m\n",
      "math: {'input': 'What is the first prime number greater than 40 such that one plus the prime number is divisible by 3?'}\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "?\n",
      "\n",
      "Answer: The first prime number greater than 40 such that one plus the prime number is divisible by 3 is 43.\n"
     ]
    }
   ],
   "source": [
    "print(\n",
    "    chain.run(\n",
    "        \"What is the first prime number greater than 40 such that one plus the prime number is divisible by 3?\"\n",
    "    )\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20f3d047",
   "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.11.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
