{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "683953b3",
   "metadata": {},
   "source": [
    "# Chroma\n",
    "\n",
    "This notebook shows how to use functionality related to the Chroma vector database."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "aac9563e",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.embeddings.openai import OpenAIEmbeddings\n",
    "from langchain.text_splitter import CharacterTextSplitter\n",
    "from langchain.vectorstores import Chroma\n",
    "from langchain.document_loaders import TextLoader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a3c3999a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.document_loaders import TextLoader\n",
    "loader = TextLoader('../../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": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running Chroma using direct local API.\n",
      "Using DuckDB in-memory for database. Data will be transient.\n"
     ]
    }
   ],
   "source": [
    "db = Chroma.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": 4,
   "id": "4b172de8",
   "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": "8061454b",
   "metadata": {},
   "source": [
    "## Persistance\n",
    "\n",
    "The below steps cover how to persist a ChromaDB instance"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2b76db26",
   "metadata": {},
   "source": [
    "### Initialize PeristedChromaDB\n",
    "Create embeddings for each chunk and insert into the Chroma vector database. The persist_directory argument tells ChromaDB where to store the database when it's persisted.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "cdb86e0d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running Chroma using direct local API.\n",
      "No existing DB found in db, skipping load\n",
      "No existing DB found in db, skipping load\n"
     ]
    }
   ],
   "source": [
    "# Embed and store the texts\n",
    "# Supplying a persist_directory will store the embeddings on disk\n",
    "persist_directory = 'db'\n",
    "\n",
    "embedding = OpenAIEmbeddings()\n",
    "vectordb = Chroma.from_documents(documents=docs, embedding=embedding, persist_directory=persist_directory)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f568a322",
   "metadata": {},
   "source": [
    "### Persist the Database\n",
    "In a notebook, we should call persist() to ensure the embeddings are written to disk. This isn't necessary in a script - the database will be automatically persisted when the client object is destroyed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "74b08cb4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Persisting DB to disk, putting it in the save folder db\n",
      "PersistentDuckDB del, about to run persist\n",
      "Persisting DB to disk, putting it in the save folder db\n"
     ]
    }
   ],
   "source": [
    "vectordb.persist()\n",
    "vectordb = None"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc9ed900",
   "metadata": {},
   "source": [
    "### Load the Database from disk, and create the chain\n",
    "Be sure to pass the same persist_directory and embedding_function as you did when you instantiated the database. Initialize the chain we will use for question answering."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "31fecfe9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running Chroma using direct local API.\n",
      "loaded in 4 embeddings\n",
      "loaded in 1 collections\n"
     ]
    }
   ],
   "source": [
    "# Now we can load the persisted database from disk, and use it as normal. \n",
    "vectordb = Chroma(persist_directory=persist_directory, embedding_function=embedding)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4dde7a0d",
   "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.9.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
