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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "683953b3",
   "metadata": {},
   "source": [
    "# SupabaseVectorStore"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc80fa84-1f2f-48b4-bd39-3e6412f012f1",
   "metadata": {},
   "source": [
    ">[Supabase](https://supabase.com/docs) is an open source Firebase alternative.\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 vector;\n",
    "\n",
    "       -- Create a table to store your documents\n",
    "       create table documents (\n",
    "       id bigserial 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 FUNCTION match_documents(query_embedding vector(1536), match_count int)\n",
    "           RETURNS TABLE(\n",
    "               id bigint,\n",
    "               content text,\n",
    "               metadata jsonb,\n",
    "               -- we return matched vectors to enable maximal marginal relevance searches\n",
    "               embedding vector(1536),\n",
    "               similarity float)\n",
    "           LANGUAGE plpgsql\n",
    "           AS $$\n",
    "           # variable_conflict use_column\n",
    "       BEGIN\n",
    "           RETURN query\n",
    "           SELECT\n",
    "               id,\n",
    "               content,\n",
    "               metadata,\n",
    "               embedding,\n",
    "               1 -(documents.embedding <=> query_embedding) AS similarity\n",
    "           FROM\n",
    "               documents\n",
    "           ORDER BY\n",
    "               documents.embedding <=> query_embedding\n",
    "           LIMIT match_count;\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": null,
   "id": "19846a7b-99bc-47a7-8e1c-f13c2497f1ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import getpass\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c71c3901-d44b-4d09-92c5-3018628c28fa",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ['SUPABASE_URL'] = getpass.getpass('Supabase URL:')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b91ecfa-f61b-489a-a337-dff1f12f6ab2",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ['SUPABASE_SERVICE_KEY'] = getpass.getpass('Supabase Service Key:')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "90afc6df",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "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": "code",
   "execution_count": 3,
   "id": "5ce44f7c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\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)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "aac9563e",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2023-04-19 20:12:28,593:INFO - NumExpr defaulting to 8 threads.\n"
     ]
    }
   ],
   "source": [
    "from langchain.embeddings.openai import OpenAIEmbeddings\n",
    "from langchain.text_splitter import CharacterTextSplitter\n",
    "from langchain.vectorstores import SupabaseVectorStore\n",
    "from langchain.document_loaders import TextLoader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "a3c3999a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.document_loaders import TextLoader\n",
    "\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": 6,
   "id": "efec97f8",
   "metadata": {},
   "outputs": [],
   "source": [
    "# We're using the default `documents` table here. You can modify this by passing in a `table_name` argument to the `from_documents` method.\n",
    "vector_store = SupabaseVectorStore.from_documents(\n",
    "    docs, embeddings, client=supabase\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "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": 8,
   "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": "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 preventionand 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.10.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}