{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "683953b3",
   "metadata": {},
   "source": [
    "# Faiss (Async)\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 using `asyncio`.\n",
    "LangChain implemented the synchronous and asynchronous vector store functions.\n",
    "\n",
    "See `synchronous` version [here](https://python.langchain.com/docs/integrations/vectorstores/faiss)."
   ]
  },
  {
   "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": null,
   "id": "971a172a-2d87-4eec-be92-87aa174fec30",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import getpass\n",
    "import os\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'\n",
    "\n",
    "from langchain.document_loaders import TextLoader\n",
    "from langchain.embeddings.openai import OpenAIEmbeddings\n",
    "from langchain.text_splitter import CharacterTextSplitter\n",
    "from langchain.vectorstores import FAISS\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()\n",
    "\n",
    "db = await FAISS.afrom_documents(docs, embeddings)\n",
    "\n",
    "query = \"What did the president say about Ketanji Brown Jackson\"\n",
    "docs = await db.asimilarity_search(query)\n",
    "\n",
    "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": null,
   "id": "30bf7c85-a273-45dc-ae9e-f138e330b42e",
   "metadata": {},
   "outputs": [],
   "source": [
    "docs_and_scores = await db.asimilarity_search_with_score(query)\n",
    "\n",
    "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": 10,
   "id": "b558ebb7",
   "metadata": {},
   "outputs": [],
   "source": [
    "embedding_vector = await embeddings.aembed_query(query)\n",
    "docs_and_scores = await db.asimilarity_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": null,
   "id": "88e11f08-1ac8-45aa-8bc0-56439ef87256",
   "metadata": {},
   "outputs": [],
   "source": [
    "db.save_local(\"faiss_index\")\n",
    "\n",
    "new_db = FAISS.load_local(\"faiss_index\", embeddings, asynchronous=True)\n",
    "\n",
    "docs = await new_db.asimilarity_search(query)\n",
    "\n",
    "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": "e36e220b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.embeddings.huggingface import HuggingFaceEmbeddings\n",
    "\n",
    "pkl = db.serialize_to_bytes()  # serializes the faiss index\n",
    "embeddings = HuggingFaceEmbeddings(model_name=\"all-MiniLM-L6-v2\")\n",
    "db = FAISS.deserialize_from_bytes(\n",
    "    embeddings=embeddings, serialized=pkl, asynchronous=True\n",
    ")  # Load the index"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "57da60d4",
   "metadata": {},
   "source": [
    "## Merging\n",
    "You can also merge two FAISS vectorstores"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "6dfd2b78",
   "metadata": {},
   "outputs": [],
   "source": [
    "db1 = await FAISS.afrom_texts([\"foo\"], embeddings)\n",
    "db2 = await FAISS.afrom_texts([\"bar\"], embeddings)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "29960da7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'8164a453-9643-4959-87f7-9ba79f9e8fb0': Document(page_content='foo')}"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "db1.docstore._dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "83392605",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'4fbcf8a2-e80f-4f65-9308-2f4cb27cb6e7': Document(page_content='bar')}"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "db2.docstore._dict"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "a3fcc1c7",
   "metadata": {},
   "outputs": [],
   "source": [
    "db1.merge_from(db2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "41c51f89",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'8164a453-9643-4959-87f7-9ba79f9e8fb0': Document(page_content='foo'),\n",
       " '4fbcf8a2-e80f-4f65-9308-2f4cb27cb6e7': Document(page_content='bar')}"
      ]
     },
     "execution_count": 23,
     "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": null,
   "id": "6740107a",
   "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 = await db.asimilarity_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 = await db.amax_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 = await db.asimilarity_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
}
