{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3bbf49ee-f3f1-40c1-b48a-828e4166bfe0",
   "metadata": {},
   "source": [
    "# Map re-rank\n",
    "\n",
    "The map re-rank documents chain runs an initial prompt on each document, that not only tries to complete a task but also gives a score for how certain it is in its answer. The highest scoring response is returned.\n",
    "\n",
    "![map_rerank_diagram](/img/map_rerank.jpg)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d4cfac68-f2c4-49bf-9aad-d3e07eb9ee53",
   "metadata": {},
   "source": [
    "## Recreating with LCEL\n",
    "\n",
    "With [LangChain Expression Language](/docs/expression_language) we can recreate the `MapRerankDocumentsChain` functionality, with the additional benefit of getting all the built-in LCEL features (batch, async, etc.) and with much more ability to customize specific parts of the chain."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "27c523f9-f9f1-4ad5-8bdb-38f8faa9c6e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.chat_models import ChatOpenAI\n",
    "from langchain.output_parsers.openai_functions import PydanticOutputFunctionsParser\n",
    "from langchain.prompts import PromptTemplate\n",
    "from langchain.pydantic_v1 import BaseModel, Field\n",
    "from langchain.schema.prompt_template import format_document\n",
    "from langchain.utils.openai_functions import convert_pydantic_to_openai_function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "ea687400-9410-445c-9adc-f8c8b9f66327",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Chain to apply to each individual document. Chain\n",
    "# provides an answer to the question based on the document\n",
    "# and scores it's confidence in the answer.\n",
    "\n",
    "map_prompt = PromptTemplate.from_template(\n",
    "    \"Answer the user question using the context.\"\n",
    "    \"\\n\\nContext:\\n\\n{context}\\n\\nQuestion: {question}\"\n",
    ")\n",
    "\n",
    "\n",
    "class AnswerAndScore(BaseModel):\n",
    "    \"\"\"Return the answer to the question and a relevance score.\"\"\"\n",
    "\n",
    "    answer: str = Field(\n",
    "        description=\"The answer to the question, which is based ONLY on the provided context.\"\n",
    "    )\n",
    "    score: float = Field(\n",
    "        decsription=\"A 0.0-1.0 relevance score, where 1.0 indicates the provided context answers the question completely and 0.0 indicates the provided context does not answer the question at all.\"\n",
    "    )\n",
    "\n",
    "\n",
    "function = convert_pydantic_to_openai_function(AnswerAndScore)\n",
    "map_chain = (\n",
    "    map_prompt\n",
    "    | ChatOpenAI().bind(\n",
    "        temperature=0, functions=[function], function_call={\"name\": \"AnswerAndScore\"}\n",
    "    )\n",
    "    | PydanticOutputFunctionsParser(pydantic_schema=AnswerAndScore)\n",
    ").with_config(run_name=\"Map\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ace2b1d5-a9ea-4a70-8d39-2826a5445aa7",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Final chain, which after answer and scoring based on\n",
    "# each doc return the answer with the highest score.\n",
    "\n",
    "\n",
    "def top_answer(scored_answers):\n",
    "    return max(scored_answers, key=lambda x: x.score).answer\n",
    "\n",
    "\n",
    "document_prompt = PromptTemplate.from_template(\"{page_content}\")\n",
    "map_rerank_chain = (\n",
    "    (\n",
    "        lambda x: [\n",
    "            {\n",
    "                \"context\": format_document(doc, document_prompt),\n",
    "                \"question\": x[\"question\"],\n",
    "            }\n",
    "            for doc in x[\"docs\"]\n",
    "        ]\n",
    "    )\n",
    "    | map_chain.map()\n",
    "    | top_answer\n",
    ").with_config(run_name=\"Map rerank\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62b863c9-2316-42ad-9581-ebc688889855",
   "metadata": {},
   "source": [
    "## Example run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "7b46c373-64c9-4b69-b64f-9bc6e52ae91c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.schema import Document\n",
    "\n",
    "text = \"\"\"Nuclear power in space is the use of nuclear power in outer space, typically either small fission systems or radioactive decay for electricity or heat. Another use is for scientific observation, as in a Mössbauer spectrometer. The most common type is a radioisotope thermoelectric generator, which has been used on many space probes and on crewed lunar missions. Small fission reactors for Earth observation satellites, such as the TOPAZ nuclear reactor, have also been flown.[1] A radioisotope heater unit is powered by radioactive decay and can keep components from becoming too cold to function, potentially over a span of decades.[2]\n",
    "\n",
    "The United States tested the SNAP-10A nuclear reactor in space for 43 days in 1965,[3] with the next test of a nuclear reactor power system intended for space use occurring on 13 September 2012 with the Demonstration Using Flattop Fission (DUFF) test of the Kilopower reactor.[4]\n",
    "\n",
    "After a ground-based test of the experimental 1965 Romashka reactor, which used uranium and direct thermoelectric conversion to electricity,[5] the USSR sent about 40 nuclear-electric satellites into space, mostly powered by the BES-5 reactor. The more powerful TOPAZ-II reactor produced 10 kilowatts of electricity.[3]\n",
    "\n",
    "Examples of concepts that use nuclear power for space propulsion systems include the nuclear electric rocket (nuclear powered ion thruster(s)), the radioisotope rocket, and radioisotope electric propulsion (REP).[6] One of the more explored concepts is the nuclear thermal rocket, which was ground tested in the NERVA program. Nuclear pulse propulsion was the subject of Project Orion.[7]\n",
    "\n",
    "Regulation and hazard prevention[edit]\n",
    "After the ban of nuclear weapons in space by the Outer Space Treaty in 1967, nuclear power has been discussed at least since 1972 as a sensitive issue by states.[8] Particularly its potential hazards to Earth's environment and thus also humans has prompted states to adopt in the U.N. General Assembly the Principles Relevant to the Use of Nuclear Power Sources in Outer Space (1992), particularly introducing safety principles for launches and to manage their traffic.[8]\n",
    "\n",
    "Benefits\n",
    "\n",
    "Both the Viking 1 and Viking 2 landers used RTGs for power on the surface of Mars. (Viking launch vehicle pictured)\n",
    "While solar power is much more commonly used, nuclear power can offer advantages in some areas. Solar cells, although efficient, can only supply energy to spacecraft in orbits where the solar flux is sufficiently high, such as low Earth orbit and interplanetary destinations close enough to the Sun. Unlike solar cells, nuclear power systems function independently of sunlight, which is necessary for deep space exploration. Nuclear-based systems can have less mass than solar cells of equivalent power, allowing more compact spacecraft that are easier to orient and direct in space. In the case of crewed spaceflight, nuclear power concepts that can power both life support and propulsion systems may reduce both cost and flight time.[9]\n",
    "\n",
    "Selected applications and/or technologies for space include:\n",
    "\n",
    "Radioisotope thermoelectric generator\n",
    "Radioisotope heater unit\n",
    "Radioisotope piezoelectric generator\n",
    "Radioisotope rocket\n",
    "Nuclear thermal rocket\n",
    "Nuclear pulse propulsion\n",
    "Nuclear electric rocket\n",
    "\"\"\"\n",
    "\n",
    "docs = [\n",
    "    Document(\n",
    "        page_content=split,\n",
    "        metadata={\"source\": \"https://en.wikipedia.org/wiki/Nuclear_power_in_space\"},\n",
    "    )\n",
    "    for split in text.split(\"\\n\\n\")\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d1998c41-1ebb-4d55-9c28-d2f3feb12657",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The Viking missions were powered by radioisotope thermoelectric generators (RTGs). These generators used the heat produced by the natural decay of plutonium-238 to generate electricity.\n"
     ]
    }
   ],
   "source": [
    "print(\n",
    "    map_rerank_chain.invoke({\"docs\": docs, \"question\": \"How were the vikings powered\"})\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "poetry-venv",
   "language": "python",
   "name": "poetry-venv"
  },
  "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
}
