{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "683953b3",
   "metadata": {},
   "source": [
    "# Faiss\n",
    "\n",
    ">[Facebook AI Similarity Search (Faiss)](https://engineering.fb.com/2017/03/29/data-infrastructure/faiss-a-library-for-efficient-similarity-search/) is a library for efficient similarity search and clustering of dense vectors. It contains algorithms that search in sets of vectors of any size, up to ones that possibly do not fit in RAM. It also contains supporting code for evaluation and parameter tuning.\n",
    "\n",
    "[Faiss documentation](https://faiss.ai/).\n",
    "\n",
    "This notebook shows how to use functionality related to the `FAISS` vector database."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "497fcd89-e832-46a7-a74a-c71199666206",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "!pip install faiss-gpu # For CUDA 7.5+ Supported GPU's.\n",
    "# OR\n",
    "!pip install faiss-cpu # For CPU Installation"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "38237514-b3fa-44a4-9cff-30cd6bf50073",
   "metadata": {},
   "source": [
    "We want to use OpenAIEmbeddings so we have to get the OpenAI API Key. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "47f9b495-88f1-4286-8d5d-1416103931a7",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import getpass\n",
    "\n",
    "os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")\n",
    "\n",
    "# Uncomment the following line if you need to initialize FAISS with no AVX2 optimization\n",
    "# os.environ['FAISS_NO_AVX2'] = '1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "aac9563e",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.embeddings.openai import OpenAIEmbeddings\n",
    "from langchain.text_splitter import CharacterTextSplitter\n",
    "from langchain.vectorstores import FAISS\n",
    "from langchain.document_loaders import TextLoader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a3c3999a",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.document_loaders import TextLoader\n",
    "\n",
    "loader = TextLoader(\"../../../extras/modules/state_of_the_union.txt\")\n",
    "documents = loader.load()\n",
    "text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n",
    "docs = text_splitter.split_documents(documents)\n",
    "\n",
    "embeddings = OpenAIEmbeddings()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "5eabdb75",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "db = FAISS.from_documents(docs, embeddings)\n",
    "\n",
    "query = \"What did the president say about Ketanji Brown Jackson\"\n",
    "docs = db.similarity_search(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "4b172de8",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \n",
      "\n",
      "Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \n",
      "\n",
      "One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
      "\n",
      "And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.\n"
     ]
    }
   ],
   "source": [
    "print(docs[0].page_content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f13473b5",
   "metadata": {},
   "source": [
    "## Similarity Search with score\n",
    "There are some FAISS specific methods. One of them is `similarity_search_with_score`, which allows you to return not only the documents but also the distance score of the query to them. The returned distance score is L2 distance. Therefore, a lower score is better."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "186ee1d8",
   "metadata": {},
   "outputs": [],
   "source": [
    "docs_and_scores = db.similarity_search_with_score(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "284e04b5",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'}),\n",
       " 0.36913747)"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docs_and_scores[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f34420cf",
   "metadata": {},
   "source": [
    "It is also possible to do a search for documents similar to a given embedding vector using `similarity_search_by_vector` which accepts an embedding vector as a parameter instead of a string."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "b558ebb7",
   "metadata": {},
   "outputs": [],
   "source": [
    "embedding_vector = embeddings.embed_query(query)\n",
    "docs_and_scores = db.similarity_search_by_vector(embedding_vector)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31bda7fd",
   "metadata": {},
   "source": [
    "## Saving and loading\n",
    "You can also save and load a FAISS index. This is useful so you don't have to recreate it everytime you use it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "428a6816",
   "metadata": {},
   "outputs": [],
   "source": [
    "db.save_local(\"faiss_index\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "56d1841c",
   "metadata": {},
   "outputs": [],
   "source": [
    "new_db = FAISS.load_local(\"faiss_index\", embeddings)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "39055525",
   "metadata": {},
   "outputs": [],
   "source": [
    "docs = new_db.similarity_search(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "98378c4e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Document(page_content='Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. \\n\\nOne of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \\n\\nAnd I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'})"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docs[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "30c8f57b",
   "metadata": {},
   "source": [
    "# Serializing and De-Serializing to bytes\n",
    "\n",
    "you can pickle the FAISS Index by these functions. If you use embeddings model which is of 90 mb (sentence-transformers/all-MiniLM-L6-v2 or any other model), the resultant pickle size would be more than 90 mb. the size of the model is also included in the overall size. To overcome this, use the below functions. These functions only serializes FAISS index and size would be much lesser. this can be helpful if you wish to store the index in database like sql."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d8faead5",
   "metadata": {},
   "outputs": [],
   "source": [
    "pkl = db.serialize_to_bytes() # serializes the faiss index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb083247",
   "metadata": {
    "vscode": {
     "languageId": "r"
    }
   },
   "outputs": [],
   "source": [
    "embeddings = HuggingFaceEmbeddings(model_name=\"all-MiniLM-L6-v2\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e36e220b",
   "metadata": {},
   "outputs": [],
   "source": [
    "db = FAISS.deserialize_from_bytes(embeddings = embeddings, serialized = pkl) # Load the index"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57da60d4",
   "metadata": {},
   "source": [
    "## Merging\n",
    "You can also merge two FAISS vectorstores"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "6dfd2b78",
   "metadata": {},
   "outputs": [],
   "source": [
    "db1 = FAISS.from_texts([\"foo\"], embeddings)\n",
    "db2 = FAISS.from_texts([\"bar\"], embeddings)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "29960da7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'068c473b-d420-487a-806b-fb0ccea7f711': Document(page_content='foo', metadata={})}"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "db1.docstore._dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "83392605",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'807e0c63-13f6-4070-9774-5c6f0fbb9866': Document(page_content='bar', metadata={})}"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "db2.docstore._dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "a3fcc1c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "db1.merge_from(db2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "41c51f89",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'068c473b-d420-487a-806b-fb0ccea7f711': Document(page_content='foo', metadata={}),\n",
       " '807e0c63-13f6-4070-9774-5c6f0fbb9866': Document(page_content='bar', metadata={})}"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "db1.docstore._dict"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4294b96",
   "metadata": {},
   "source": [
    "## Similarity Search with filtering\n",
    "FAISS vectorstore can also support filtering, since the FAISS does not natively support filtering we have to do it manually. This is done by first fetching more results than `k` and then filtering them. You can filter the documents based on metadata. You can also set the `fetch_k` parameter when calling any search method to set how many documents you want to fetch before filtering. Here is a small example:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d5bf812c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Content: foo, Metadata: {'page': 1}, Score: 5.159960813797904e-15\n",
      "Content: foo, Metadata: {'page': 2}, Score: 5.159960813797904e-15\n",
      "Content: foo, Metadata: {'page': 3}, Score: 5.159960813797904e-15\n",
      "Content: foo, Metadata: {'page': 4}, Score: 5.159960813797904e-15\n"
     ]
    }
   ],
   "source": [
    "from langchain.schema import Document\n",
    "\n",
    "list_of_documents = [\n",
    "    Document(page_content=\"foo\", metadata=dict(page=1)),\n",
    "    Document(page_content=\"bar\", metadata=dict(page=1)),\n",
    "    Document(page_content=\"foo\", metadata=dict(page=2)),\n",
    "    Document(page_content=\"barbar\", metadata=dict(page=2)),\n",
    "    Document(page_content=\"foo\", metadata=dict(page=3)),\n",
    "    Document(page_content=\"bar burr\", metadata=dict(page=3)),\n",
    "    Document(page_content=\"foo\", metadata=dict(page=4)),\n",
    "    Document(page_content=\"bar bruh\", metadata=dict(page=4)),\n",
    "]\n",
    "db = FAISS.from_documents(list_of_documents, embeddings)\n",
    "results_with_scores = db.similarity_search_with_score(\"foo\")\n",
    "for doc, score in results_with_scores:\n",
    "    print(f\"Content: {doc.page_content}, Metadata: {doc.metadata}, Score: {score}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d33c126",
   "metadata": {},
   "source": [
    "Now we make the same query call but we filter for only `page = 1` "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "83159330",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Content: foo, Metadata: {'page': 1}, Score: 5.159960813797904e-15\n",
      "Content: bar, Metadata: {'page': 1}, Score: 0.3131446838378906\n"
     ]
    }
   ],
   "source": [
    "results_with_scores = db.similarity_search_with_score(\"foo\", filter=dict(page=1))\n",
    "for doc, score in results_with_scores:\n",
    "    print(f\"Content: {doc.page_content}, Metadata: {doc.metadata}, Score: {score}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0be136e0",
   "metadata": {},
   "source": [
    "Same thing can be done with the `max_marginal_relevance_search` as well."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "432c6980",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Content: foo, Metadata: {'page': 1}\n",
      "Content: bar, Metadata: {'page': 1}\n"
     ]
    }
   ],
   "source": [
    "results = db.max_marginal_relevance_search(\"foo\", filter=dict(page=1))\n",
    "for doc in results:\n",
    "    print(f\"Content: {doc.page_content}, Metadata: {doc.metadata}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b4ecd86",
   "metadata": {},
   "source": [
    "Here is an example of how to set `fetch_k` parameter when calling `similarity_search`. Usually you would want the `fetch_k` parameter >> `k` parameter. This is because the `fetch_k` parameter is the number of documents that will be fetched before filtering. If you set `fetch_k` to a low number, you might not get enough documents to filter from."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "1fd60fd1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Content: foo, Metadata: {'page': 1}\n"
     ]
    }
   ],
   "source": [
    "results = db.similarity_search(\"foo\", filter=dict(page=1), k=1, fetch_k=4)\n",
    "for doc in results:\n",
    "    print(f\"Content: {doc.page_content}, Metadata: {doc.metadata}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1becca53",
   "metadata": {},
   "source": [
    "## Delete\n",
    "\n",
    "You can also delete ids. Note that the ids to delete should be the ids in the docstore."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "1408b870",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "db.delete([db.index_to_docstore_id[0]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d13daf33",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Is now missing\n",
    "0 in db.index_to_docstore_id"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30ace43e",
   "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.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
