{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7ef4d402-6662-4a26-b612-35b542066487",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "#  VectorStores\n",
    "\n",
    "This notebook show cases how to use VectorStores. A key part of working with vectorstores is creating the vector to put in them, which is usually created via embeddings. Therefor, it is recommended that you familiarize yourself with the [embedding notebook](embeddings.ipynb) before diving into this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "965eecee",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "from langchain.embeddings.openai import OpenAIEmbeddings\n",
    "from langchain.text_splitter import CharacterTextSplitter\n",
    "from langchain.vectorstores import ElasticVectorSearch, Pinecone, Weaviate, FAISS, Qdrant"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "68481687",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "with open('../../state_of_the_union.txt') as f:\n",
    "    state_of_the_union = f.read()\n",
    "text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)\n",
    "texts = text_splitter.split_text(state_of_the_union)\n",
    "\n",
    "embeddings = OpenAIEmbeddings()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "015f4ff5",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "docsearch = FAISS.from_texts(texts, embeddings)\n",
    "\n",
    "query = \"What did the president say about Ketanji Brown Jackson\"\n",
    "docs = docsearch.similarity_search(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "67baf32e",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \n",
      "\n",
      "We cannot let this happen. \n",
      "\n",
      "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": "bbf5ec44",
   "metadata": {},
   "source": [
    "## From Documents\n",
    "We can also initialize a vectorstore from documents directly. This is useful when we use the method on the text splitter to get documents directly (handy when the original documents have associated metadata)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "df4a459c",
   "metadata": {},
   "outputs": [],
   "source": [
    "documents = text_splitter.create_documents([state_of_the_union], metadatas=[{\"source\": \"State of the Union\"}])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "4b480245",
   "metadata": {},
   "outputs": [],
   "source": [
    "docsearch = FAISS.from_documents(documents, embeddings)\n",
    "\n",
    "query = \"What did the president say about Ketanji Brown Jackson\"\n",
    "docs = docsearch.similarity_search(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "86aa4cda",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \n",
      "\n",
      "We cannot let this happen. \n",
      "\n",
      "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": "2445a5e6",
   "metadata": {},
   "source": [
    "## FAISS-specific\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 similarity score of the query to them."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "b4f49314",
   "metadata": {},
   "outputs": [],
   "source": [
    "docs_and_scores = docsearch.similarity_search_with_score(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "86f78ab1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(Document(page_content='In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \\n\\nWe cannot let this happen. \\n\\nTonight. 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.', lookup_str='', metadata={}, lookup_index=0),\n",
       " 0.40834612)"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docs_and_scores[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b386dbb8",
   "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": 4,
   "id": "b58b3955",
   "metadata": {},
   "outputs": [],
   "source": [
    "docsearch.save_local(\"faiss_index\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "ca72c650",
   "metadata": {},
   "outputs": [],
   "source": [
    "new_docsearch = FAISS.load_local(\"faiss_index\", embeddings)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "5bf2ee24",
   "metadata": {},
   "outputs": [],
   "source": [
    "docs = new_docsearch.similarity_search(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "edc2aad1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Document(page_content='In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \\n\\nWe cannot let this happen. \\n\\nTonight. 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.', lookup_str='', metadata={}, lookup_index=0)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docs[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eea6e627",
   "metadata": {},
   "source": [
    "## Requires having ElasticSearch setup"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "4906b8a3",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "docsearch = ElasticVectorSearch.from_texts(texts, embeddings, elasticsearch_url=\"http://localhost:9200\")\n",
    "\n",
    "query = \"What did the president say about Ketanji Brown Jackson\"\n",
    "docs = docsearch.similarity_search(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "95f9eee9",
   "metadata": {
    "pycharm": {
     "name": "#%%\n"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "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",
      "\n",
      "A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \n",
      "\n",
      "And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. \n"
     ]
    }
   ],
   "source": [
    "print(docs[0].page_content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f9cb9e7",
   "metadata": {},
   "source": [
    "## Weaviate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "1037a85e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import weaviate\n",
    "import os\n",
    "\n",
    "WEAVIATE_URL = \"\"\n",
    "client = weaviate.Client(\n",
    "    url=WEAVIATE_URL,\n",
    "    additional_headers={\n",
    "        'X-OpenAI-Api-Key': os.environ[\"OPENAI_API_KEY\"]\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "b9043766",
   "metadata": {},
   "outputs": [],
   "source": [
    "client.schema.delete_all()\n",
    "client.schema.get()\n",
    "schema = {\n",
    "    \"classes\": [\n",
    "        {\n",
    "            \"class\": \"Paragraph\",\n",
    "            \"description\": \"A written paragraph\",\n",
    "            \"vectorizer\": \"text2vec-openai\",\n",
    "              \"moduleConfig\": {\n",
    "                \"text2vec-openai\": {\n",
    "                  \"model\": \"babbage\",\n",
    "                  \"type\": \"text\"\n",
    "                }\n",
    "              },\n",
    "            \"properties\": [\n",
    "                {\n",
    "                    \"dataType\": [\"text\"],\n",
    "                    \"description\": \"The content of the paragraph\",\n",
    "                    \"moduleConfig\": {\n",
    "                        \"text2vec-openai\": {\n",
    "                          \"skip\": False,\n",
    "                          \"vectorizePropertyName\": False\n",
    "                        }\n",
    "                      },\n",
    "                    \"name\": \"content\",\n",
    "                },\n",
    "            ],\n",
    "        },\n",
    "    ]\n",
    "}\n",
    "\n",
    "client.schema.create(schema)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "ac20d99c",
   "metadata": {},
   "outputs": [],
   "source": [
    "with client.batch as batch:\n",
    "    for text in texts:\n",
    "        batch.add_data_object({\"content\": text}, \"Paragraph\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "01645d61",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.vectorstores.weaviate import Weaviate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "bdd97d29",
   "metadata": {},
   "outputs": [],
   "source": [
    "vectorstore = Weaviate(client, \"Paragraph\", \"content\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "b70c0f98",
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"What did the president say about Ketanji Brown Jackson\"\n",
    "docs = vectorstore.similarity_search(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "07533e40",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \n",
      "\n",
      "We cannot let this happen. \n",
      "\n",
      "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": "007f3102",
   "metadata": {},
   "source": [
    "## Pinecone"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "7f6047e5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pinecone \n",
    "\n",
    "# initialize pinecone\n",
    "pinecone.init(\n",
    "    api_key=\"YOUR_API_KEY\",  # find at app.pinecone.io\n",
    "    environment=\"YOUR_ENV\"  # next to api key in console\n",
    ")\n",
    "\n",
    "index_name = \"langchain-demo\"\n",
    "\n",
    "docsearch = Pinecone.from_texts(texts, embeddings, index_name=index_name)\n",
    "\n",
    "query = \"What did the president say about Ketanji Brown Jackson\"\n",
    "docs = docsearch.similarity_search(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "8e81f1f0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Document(page_content='A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans. \\n\\nAnd if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. \\n\\nWe can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling.  \\n\\nWe’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers.  \\n\\nWe’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. \\n\\nWe’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders. ', lookup_str='', metadata={}, lookup_index=0)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docs[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9b852079",
   "metadata": {},
   "source": [
    "## Qdrant"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e5ec70ce",
   "metadata": {},
   "outputs": [],
   "source": [
    "host = \"<---host name here --->\"\n",
    "api_key = \"<---api key here--->\"\n",
    "qdrant = Qdrant.from_texts(texts, embeddings, host=host, prefer_grpc=True, api_key=api_key)\n",
    "query = \"What did the president say about Ketanji Brown Jackson\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "9805ad1f",
   "metadata": {},
   "outputs": [],
   "source": [
    "docs = qdrant.similarity_search(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "bd097a0e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Document(page_content='In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \\n\\nWe cannot let this happen. \\n\\nTonight. 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.', lookup_str='', metadata={}, lookup_index=0)"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docs[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6c3ec797",
   "metadata": {},
   "source": [
    "## Milvus\n",
    "To run, you should have a Milvus instance up and running: https://milvus.io/docs/install_standalone-docker.md"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "be347313",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.vectorstores import Milvus"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f2eee23f",
   "metadata": {},
   "outputs": [],
   "source": [
    "vector_db = Milvus.from_texts(\n",
    "    texts,\n",
    "    embeddings,\n",
    "    connection_args={\"host\": \"127.0.0.1\", \"port\": \"19530\"},\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "06bdb701",
   "metadata": {},
   "outputs": [],
   "source": [
    "docs = vector_db.similarity_search(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "7b3e94aa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Document(page_content='In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. \\n\\nWe cannot let this happen. \\n\\nTonight. 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.', lookup_str='', metadata={}, lookup_index=0)"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docs[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4af5a071",
   "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.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
