{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "683953b3",
   "metadata": {},
   "source": [
    "# Supabase (Postgres)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc80fa84-1f2f-48b4-bd39-3e6412f012f1",
   "metadata": {},
   "source": [
    ">[Supabase](https://supabase.com/docs) is an open-source Firebase alternative. `Supabase` is built on top of `PostgreSQL`, which offers strong SQL querying capabilities and enables a simple interface with already-existing tools and frameworks.\n",
    "\n",
    ">[PostgreSQL](https://en.wikipedia.org/wiki/PostgreSQL) also known as `Postgres`, is a free and open-source relational database management system (RDBMS) emphasizing extensibility and SQL compliance.\n",
    "\n",
    "This notebook shows how to use `Supabase` and `pgvector` as your VectorStore.\n",
    "\n",
    "To run this notebook, please ensure:\n",
    "- the `pgvector` extension is enabled\n",
    "- you have installed the `supabase-py` package\n",
    "- that you have created a `match_documents` function in your database\n",
    "- that you have a `documents` table in your `public` schema similar to the one below.\n",
    "\n",
    "The following function determines cosine similarity, but you can adjust to your needs.\n",
    "\n",
    "```sql\n",
    "-- Enable the pgvector extension to work with embedding vectors\n",
    "create extension if not exists vector;\n",
    "\n",
    "-- Create a table to store your documents\n",
    "create table\n",
    "  documents (\n",
    "    id uuid primary key,\n",
    "    content text, -- corresponds to Document.pageContent\n",
    "    metadata jsonb, -- corresponds to Document.metadata\n",
    "    embedding vector (1536) -- 1536 works for OpenAI embeddings, change if needed\n",
    "  );\n",
    "\n",
    "-- Create a function to search for documents\n",
    "create function match_documents (\n",
    "  query_embedding vector (1536),\n",
    "  filter jsonb default '{}'\n",
    ") returns table (\n",
    "  id uuid,\n",
    "  content text,\n",
    "  metadata jsonb,\n",
    "  similarity float\n",
    ") language plpgsql as $$\n",
    "#variable_conflict use_column\n",
    "begin\n",
    "  return query\n",
    "  select\n",
    "    id,\n",
    "    content,\n",
    "    metadata,\n",
    "    1 - (documents.embedding <=> query_embedding) as similarity\n",
    "  from documents\n",
    "  where metadata @> filter\n",
    "  order by documents.embedding <=> query_embedding;\n",
    "end;\n",
    "$$;\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6bd4498b",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# with pip\n",
    "!pip install supabase\n",
    "\n",
    "# with conda\n",
    "# !conda install -c conda-forge supabase"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "69bff365-3039-4ff8-a641-aa190166179d",
   "metadata": {},
   "source": [
    "We want to use `OpenAIEmbeddings` so we have to get the OpenAI API Key."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "19846a7b-99bc-47a7-8e1c-f13c2497f1ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "import getpass\n",
    "import os\n",
    "\n",
    "os.environ[\"OPENAI_API_KEY\"] = getpass.getpass(\"OpenAI API Key:\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "c71c3901-d44b-4d09-92c5-3018628c28fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ[\"SUPABASE_URL\"] = getpass.getpass(\"Supabase URL:\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "8b91ecfa-f61b-489a-a337-dff1f12f6ab2",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ[\"SUPABASE_SERVICE_KEY\"] = getpass.getpass(\"Supabase Service Key:\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "90afc6df",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# If you're storing your Supabase and OpenAI API keys in a .env file, you can load them with dotenv\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "load_dotenv()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "924d4df5",
   "metadata": {},
   "source": [
    "First we'll create a Supabase client and instantiate a OpenAI embeddings class."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "5ce44f7c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "from langchain.embeddings.openai import OpenAIEmbeddings\n",
    "from langchain.vectorstores import SupabaseVectorStore\n",
    "from supabase.client import Client, create_client\n",
    "\n",
    "supabase_url = os.environ.get(\"SUPABASE_URL\")\n",
    "supabase_key = os.environ.get(\"SUPABASE_SERVICE_KEY\")\n",
    "supabase: Client = create_client(supabase_url, supabase_key)\n",
    "\n",
    "embeddings = OpenAIEmbeddings()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c707d4c",
   "metadata": {},
   "source": [
    "Next we'll load and parse some data for our vector store (skip if you already have documents with embeddings stored in your DB)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "aac9563e",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.document_loaders import TextLoader\n",
    "from langchain.text_splitter import CharacterTextSplitter\n",
    "\n",
    "loader = TextLoader(\"../../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)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5abb9b93",
   "metadata": {},
   "source": [
    "Insert the above documents into the database. Embeddings will automatically be generated for each document. You can adjust the chunk_size based on the amount of documents you have. The default is 500 but lowering it may be necessary."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "efec97f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "vector_store = SupabaseVectorStore.from_documents(\n",
    "    docs,\n",
    "    embeddings,\n",
    "    client=supabase,\n",
    "    table_name=\"documents\",\n",
    "    query_name=\"match_documents\",\n",
    "    chunk_size=500,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e169345d",
   "metadata": {},
   "source": [
    "Alternatively if you already have documents with embeddings in your database, simply instantiate a new `SupabaseVectorStore` directly:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "397e3e7d",
   "metadata": {},
   "outputs": [],
   "source": [
    "vector_store = SupabaseVectorStore(\n",
    "    embedding=embeddings,\n",
    "    client=supabase,\n",
    "    table_name=\"documents\",\n",
    "    query_name=\"match_documents\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e28ce092",
   "metadata": {},
   "source": [
    "Finally, test it out by performing a similarity search:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5eabdb75",
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"What did the president say about Ketanji Brown Jackson\"\n",
    "matched_docs = vector_store.similarity_search(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b172de8",
   "metadata": {},
   "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(matched_docs[0].page_content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18152965",
   "metadata": {},
   "source": [
    "## Similarity search with score\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ea13e80a",
   "metadata": {},
   "source": [
    "The returned distance score is cosine distance. Therefore, a lower score is better."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "72aaa9c8",
   "metadata": {},
   "outputs": [],
   "source": [
    "matched_docs = vector_store.similarity_search_with_relevance_scores(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "d88e958e",
   "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.802509746274066)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "matched_docs[0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "794a7552",
   "metadata": {},
   "source": [
    "## Retriever options\n",
    "\n",
    "This section goes over different options for how to use SupabaseVectorStore as a retriever.\n",
    "\n",
    "### Maximal Marginal Relevance Searches\n",
    "\n",
    "In addition to using similarity search in the retriever object, you can also use `mmr`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "96ff911a",
   "metadata": {},
   "outputs": [],
   "source": [
    "retriever = vector_store.as_retriever(search_type=\"mmr\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "f00be6d0",
   "metadata": {},
   "outputs": [],
   "source": [
    "matched_docs = retriever.get_relevant_documents(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "a559c3f1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "## Document 0\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",
      "\n",
      "## Document 1\n",
      "\n",
      "One was stationed at bases and breathing in toxic smoke from “burn pits” that incinerated wastes of war—medical and hazard material, jet fuel, and more. \n",
      "\n",
      "When they came home, many of the world’s fittest and best trained warriors were never the same. \n",
      "\n",
      "Headaches. Numbness. Dizziness. \n",
      "\n",
      "A cancer that would put them in a flag-draped coffin. \n",
      "\n",
      "I know. \n",
      "\n",
      "One of those soldiers was my son Major Beau Biden. \n",
      "\n",
      "We don’t know for sure if a burn pit was the cause of his brain cancer, or the diseases of so many of our troops. \n",
      "\n",
      "But I’m committed to finding out everything we can. \n",
      "\n",
      "Committed to military families like Danielle Robinson from Ohio. \n",
      "\n",
      "The widow of Sergeant First Class Heath Robinson.  \n",
      "\n",
      "He was born a soldier. Army National Guard. Combat medic in Kosovo and Iraq. \n",
      "\n",
      "Stationed near Baghdad, just yards from burn pits the size of football fields. \n",
      "\n",
      "Heath’s widow Danielle is here with us tonight. They loved going to Ohio State football games. He loved building Legos with their daughter.\n",
      "\n",
      "## Document 2\n",
      "\n",
      "And I’m taking robust action to make sure the pain of our sanctions  is targeted at Russia’s economy. And I will use every tool at our disposal to protect American businesses and consumers. \n",
      "\n",
      "Tonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world.  \n",
      "\n",
      "America will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies.  \n",
      "\n",
      "These steps will help blunt gas prices here at home. And I know the news about what’s happening can seem alarming. \n",
      "\n",
      "But I want you to know that we are going to be okay. \n",
      "\n",
      "When the history of this era is written Putin’s war on Ukraine will have left Russia weaker and the rest of the world stronger. \n",
      "\n",
      "While it shouldn’t have taken something so terrible for people around the world to see what’s at stake now everyone sees it clearly.\n",
      "\n",
      "## Document 3\n",
      "\n",
      "We can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together. \n",
      "\n",
      "I recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. \n",
      "\n",
      "They were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. \n",
      "\n",
      "Officer Mora was 27 years old. \n",
      "\n",
      "Officer Rivera was 22. \n",
      "\n",
      "Both Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers. \n",
      "\n",
      "I spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. \n",
      "\n",
      "I’ve worked on these issues a long time. \n",
      "\n",
      "I know what works: Investing in crime prevention and community police officers who’ll walk the beat, who’ll know the neighborhood, and who can restore trust and safety.\n"
     ]
    }
   ],
   "source": [
    "for i, d in enumerate(matched_docs):\n",
    "    print(f\"\\n## Document {i}\\n\")\n",
    "    print(d.page_content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "79b1198e",
   "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.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
