File size: 10,544 Bytes
cfd3735
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "683953b3",
   "metadata": {},
   "source": [
    "# Chroma\n",
    "\n",
    ">[Chroma](https://docs.trychroma.com/getting-started) is a database for building AI applications with embeddings.\n",
    "\n",
    "This notebook shows how to use functionality related to the `Chroma` vector database."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0825fa4a-d950-4e78-8bba-20cfcc347765",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "!pip install chromadb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "42080f37-8fd1-4cec-acd9-15d2b03b2f4d",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      " 路路路路路路路路\n"
     ]
    }
   ],
   "source": [
    "# get a token: https://platform.openai.com/account/api-keys\n",
    "\n",
    "from getpass import getpass\n",
    "\n",
    "OPENAI_API_KEY = getpass()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c7a94d6c-b4d4-4498-9bdd-eb50c92b85c5",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"OPENAI_API_KEY\"] = OPENAI_API_KEY"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "aac9563e",
   "metadata": {
    "tags": []
   },
   "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": 8,
   "id": "a3c3999a",
   "metadata": {
    "tags": []
   },
   "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": 9,
   "id": "5eabdb75",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using embedded DuckDB without persistence: 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": [
      "Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you鈥檙e at it, pass the Disclose Act so Americans can know who is funding our elections. \n",
      "\n",
      "Tonight, I鈥檇 like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer鈥攁n 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鈥檚 top legal minds, who will continue Justice Breyer鈥檚 legacy of excellence.\n"
     ]
    }
   ],
   "source": [
    "print(docs[0].page_content)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18152965",
   "metadata": {},
   "source": [
    "## Similarity search with score"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "72aaa9c8",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "docs = db.similarity_search_with_score(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "d88e958e",
   "metadata": {
    "tags": []
   },
   "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鈥檙e at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I鈥檇 like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer鈥攁n 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鈥檚 top legal minds, who will continue Justice Breyer鈥檚 legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'}),\n",
       " 0.3949805498123169)"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "docs[0]"
   ]
  },
  {
   "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",
    "We should call persist() to ensure the embeddings are written to disk."
   ]
  },
  {
   "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": "markdown",
   "id": "794a7552",
   "metadata": {},
   "source": [
    "## Retriever options\n",
    "\n",
    "This section goes over different options for how to use Chroma as a retriever.\n",
    "\n",
    "### MMR\n",
    "\n",
    "In addition to using similarity search in the retriever object, you can also use `mmr`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "96ff911a",
   "metadata": {},
   "outputs": [],
   "source": [
    "retriever = db.as_retriever(search_type=\"mmr\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "f00be6d0",
   "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鈥檙e at it, pass the Disclose Act so Americans can know who is funding our elections. \\n\\nTonight, I鈥檇 like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer鈥攁n 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鈥檚 top legal minds, who will continue Justice Breyer鈥檚 legacy of excellence.', metadata={'source': '../../../state_of_the_union.txt'})"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "retriever.get_relevant_documents(query)[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a559c3f1",
   "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
}