Spaces:
Sleeping
Sleeping
File size: 14,265 Bytes
5fdb69e |
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 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 |
{
"cells": [
{
"cell_type": "markdown",
"id": "dfe37963-1af6-44fc-a841-8e462443f5e6",
"metadata": {},
"source": [
"## Expert Knowledge Worker\n",
"\n",
"### A question answering agent that is an expert knowledge worker\n",
"### To be used by employees of Insurellm, an Insurance Tech company\n",
"### The agent needs to be accurate and the solution should be low cost.\n",
"\n",
"This project will use RAG (Retrieval Augmented Generation) to ensure our question/answering assistant has high accuracy."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ba2779af-84ef-4227-9e9e-6eaf0df87e77",
"metadata": {},
"outputs": [],
"source": [
"# imports\n",
"\n",
"import os\n",
"import glob\n",
"from dotenv import load_dotenv\n",
"import gradio as gr"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "802137aa-8a74-45e0-a487-d1974927d7ca",
"metadata": {},
"outputs": [],
"source": [
"# imports for langchain and Chroma and plotly\n",
"\n",
"from langchain.document_loaders import DirectoryLoader, TextLoader\n",
"from langchain.text_splitter import CharacterTextSplitter\n",
"from langchain.schema import Document\n",
"from langchain_openai import OpenAIEmbeddings, ChatOpenAI\n",
"from langchain_chroma import Chroma\n",
"import numpy as np\n",
"from sklearn.manifold import TSNE\n",
"import plotly.graph_objects as go"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "58c85082-e417-4708-9efe-81a5d55d1424",
"metadata": {},
"outputs": [],
"source": [
"# price is a factor for our company, so we're going to use a low cost model\n",
"\n",
"MODEL = \"gpt-4o-mini\"\n",
"db_name = \"vector_db\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ee78efcb-60fe-449e-a944-40bab26261af",
"metadata": {},
"outputs": [],
"source": [
"# Load environment variables in a file called .env\n",
"\n",
"load_dotenv()\n",
"os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY', 'your-key-if-not-using-env')"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "730711a9-6ffe-4eee-8f48-d6cfb7314905",
"metadata": {},
"outputs": [],
"source": [
"# Read in documents using LangChain's loaders\n",
"# Take everything in all the sub-folders of our knowledgebase\n",
"\n",
"folders = glob.glob(\"knowledge-base/*\")\n",
"\n",
"# With thanks to Jon R, a student on the course, for this fix needed for some users \n",
"text_loader_kwargs={'autodetect_encoding': True}\n",
"\n",
"documents = []\n",
"for folder in folders:\n",
" doc_type = os.path.basename(folder)\n",
" loader = DirectoryLoader(folder, glob=\"**/*.md\", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)\n",
" folder_docs = loader.load()\n",
" for doc in folder_docs:\n",
" doc.metadata[\"doc_type\"] = doc_type\n",
" documents.append(doc)"
]
},
{
"cell_type": "markdown",
"id": "6717e706",
"metadata": {},
"source": [
"## A Variation to loading the default project files included in the course \n",
"## (a.k.a., how to get your LLM chatbot to talk to your Obsidian files)\n",
"I noticed that Ed (our instructor) had used markdown files (*.md) for the RAG sources. That got me thinking about whether \n",
"I could try these RAG techniques on my Obsidian data, since Obsidian stores all its files as *.md as well. \n",
"\n",
"If you are not familiar with Obsidian, it's a great productivity tool that stores notes that are more in line with how we work. It's similar to Evernote and other tools of this nature. But it's all local (although you can pay for synching to the cloud). Just search on google for Obsidian md.\n",
"\n",
"I did actually try an Obsidian plugin called Smart Second Brain, which is supposed to do something similar directly inside Obsidian. But it was quite buggy. It would take forever on even a small vault (vaults are like new knowledge bases. So you could create vaults on different categories like sports, LLMs, training, etc) I chose instead to try out the techniques taught here, and I now can use that to query my Obsidian vaults.\n",
"\n",
"If you want to give this a go, here is the code change for loading your obsidian files. You will need to locate the directories of your vault (they can exist on multiple folders/drives, etc.)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f634ccb1",
"metadata": {},
"outputs": [],
"source": [
"# If you wish to try your Obsidian vaults, replace the full block for loading documents \n",
"# starting with the comment above # Read in documents using LangChain's loaders. \n",
"# NOTE: If you do not wish to try out connecting the chatbot to your Obsidian, \n",
"# please skip over this entire block up to and include the # End of block for Obsidian\n",
"\n",
"folders = glob.glob(\"{ADD IN YOUR PATH TO THE OBSIDIAN .MD FILES HERE}\") # IMPORTANT: change this to your Obsidian vault folder\n",
"\n",
"# Filter out folders that start with a period (you don't want these to be embedded and indexed)\n",
"folders = [folder for folder in folders if not os.path.basename(folder).startswith('.')]\n",
"\n",
"documents = []\n",
"for folder in folders:\n",
" doc_type = os.path.basename(folder)\n",
" loader = DirectoryLoader(folder, glob=\"**/*.md\", loader_cls=TextLoader)\n",
" folder_docs = loader.load()\n",
" for doc in folder_docs:\n",
" doc.metadata[\"doc_type\"] = doc_type\n",
" documents.append(doc)\n",
"\n",
"# End of block for Obsidian"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7310c9c8-03c1-4efc-a104-5e89aec6db1a",
"metadata": {},
"outputs": [],
"source": [
"text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=200)\n",
"chunks = text_splitter.split_documents(documents)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cd06e02f-6d9b-44cc-a43d-e1faa8acc7bb",
"metadata": {},
"outputs": [],
"source": [
"len(chunks)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2c54b4b6-06da-463d-bee7-4dd456c2b887",
"metadata": {},
"outputs": [],
"source": [
"doc_types = set(chunk.metadata['doc_type'] for chunk in chunks)\n",
"print(f\"Document types found: {', '.join(doc_types)}\")"
]
},
{
"cell_type": "markdown",
"id": "77f7d2a6-ccfa-425b-a1c3-5e55b23bd013",
"metadata": {},
"source": [
"## A sidenote on Embeddings, and \"Auto-Encoding LLMs\"\n",
"\n",
"We will be mapping each chunk of text into a Vector that represents the meaning of the text, known as an embedding.\n",
"\n",
"OpenAI offers a model to do this, which we will use by calling their API with some LangChain code.\n",
"\n",
"This model is an example of an \"Auto-Encoding LLM\" which generates an output given a complete input.\n",
"It's different to all the other LLMs we've discussed today, which are known as \"Auto-Regressive LLMs\", and generate future tokens based only on past context.\n",
"\n",
"Another example of an Auto-Encoding LLMs is BERT from Google. In addition to embedding, Auto-encoding LLMs are often used for classification."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "78998399-ac17-4e28-b15f-0b5f51e6ee23",
"metadata": {},
"outputs": [],
"source": [
"# Put the chunks of data into a Vector Store that associates a Vector Embedding with each chunk\n",
"\n",
"embeddings = OpenAIEmbeddings()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "763e51ff-5787-4a56-8176-36b7c5796fe3",
"metadata": {},
"outputs": [],
"source": [
"# Check if a Chroma Datastore already exists - if so, delete the collection to start from scratch\n",
"\n",
"if os.path.exists(db_name):\n",
" Chroma(persist_directory=db_name, embedding_function=embeddings).delete_collection()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "99fe3a37-480f-4d55-be48-120588d5846b",
"metadata": {},
"outputs": [],
"source": [
"# Create our Chroma vectorstore!\n",
"\n",
"vectorstore = Chroma.from_documents(documents=chunks, embedding=embeddings, persist_directory=db_name)\n",
"print(f\"Vectorstore created with {vectorstore._collection.count()} documents\")"
]
},
{
"cell_type": "markdown",
"id": "00a9c406",
"metadata": {},
"source": [
"## When implementing this outside of Jupyter Notebooks\n",
"Jupyter notebooks are great for learning but when you're ready to put the techniques to use on a project, you'll need to separate out the loading, chunking, embedding and storing in the vector database. Otherwise, if you couple this functionality with your main functionality (like the Gradio chatbot), this processing of vectors will happen for each call. \n",
"\n",
"Ed (creator and instructor of this course) had suggested to me that his company usually breaks out these processes into a pipeline and the main script, which makes total sense. I will call the pipeline the intestion module, but pipeline is perfectly fine. The name is not that important. These scripts are regular python files and would be part of a project in Anaconda or Visual Studio Code, etc.\n",
"\n",
"At this point, the code up to this point will serve as the ingestion script. So, if you were to create a standard python file called ingestion.py, just copy all the code above and then install all the necessary pip packages. (You could use the same requirements.txt)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "057868f6-51a6-4087-94d1-380145821550",
"metadata": {},
"outputs": [],
"source": [
"# Get one vector and find how many dimensions it has\n",
"\n",
"collection = vectorstore._collection\n",
"sample_embedding = collection.get(limit=1, include=[\"embeddings\"])[\"embeddings\"][0]\n",
"dimensions = len(sample_embedding)\n",
"print(f\"The vectors have {dimensions:,} dimensions\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "61e393a0-dd4c-419f-842f-60c1cb3b716b",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "b0d45462-a818-441c-b010-b85b32bcf618",
"metadata": {},
"source": [
"## Visualizing the Vector Store\n",
"\n",
"Let's take a minute to look at the documents and their embedding vectors to see what's going on."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b98adf5e-d464-4bd2-9bdf-bc5b6770263b",
"metadata": {},
"outputs": [],
"source": [
"# Prework\n",
"\n",
"result = collection.get(include=['embeddings', 'documents', 'metadatas'])\n",
"vectors = np.array(result['embeddings'])\n",
"documents = result['documents']\n",
"doc_types = [metadata['doc_type'] for metadata in result['metadatas']]\n",
"colors = [['blue', 'green', 'red', 'orange'][['products', 'employees', 'contracts', 'company'].index(t)] for t in doc_types]"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "427149d5-e5d8-4abd-bb6f-7ef0333cca21",
"metadata": {},
"outputs": [],
"source": [
"# We humans find it easier to visalize things in 2D!\n",
"# Reduce the dimensionality of the vectors to 2D using t-SNE\n",
"# (t-distributed stochastic neighbor embedding)\n",
"\n",
"tsne = TSNE(n_components=2, random_state=42)\n",
"reduced_vectors = tsne.fit_transform(vectors)\n",
"\n",
"# Create the 2D scatter plot\n",
"fig = go.Figure(data=[go.Scatter(\n",
" x=reduced_vectors[:, 0],\n",
" y=reduced_vectors[:, 1],\n",
" mode='markers',\n",
" marker=dict(size=5, color=colors, opacity=0.8),\n",
" text=[f\"Type: {t}<br>Text: {d[:100]}...\" for t, d in zip(doc_types, documents)],\n",
" hoverinfo='text'\n",
")])\n",
"\n",
"fig.update_layout(\n",
" title='2D Chroma Vector Store Visualization',\n",
" scene=dict(xaxis_title='x',yaxis_title='y'),\n",
" width=800,\n",
" height=600,\n",
" margin=dict(r=20, b=10, l=10, t=40)\n",
")\n",
"\n",
"fig.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e1418e88-acd5-460a-bf2b-4e6efc88e3dd",
"metadata": {},
"outputs": [],
"source": [
"# Let's try 3D!\n",
"\n",
"tsne = TSNE(n_components=3, random_state=42)\n",
"reduced_vectors = tsne.fit_transform(vectors)\n",
"\n",
"# Create the 3D scatter plot\n",
"fig = go.Figure(data=[go.Scatter3d(\n",
" x=reduced_vectors[:, 0],\n",
" y=reduced_vectors[:, 1],\n",
" z=reduced_vectors[:, 2],\n",
" mode='markers',\n",
" marker=dict(size=5, color=colors, opacity=0.8),\n",
" text=[f\"Type: {t}<br>Text: {d[:100]}...\" for t, d in zip(doc_types, documents)],\n",
" hoverinfo='text'\n",
")])\n",
"\n",
"fig.update_layout(\n",
" title='3D Chroma Vector Store Visualization',\n",
" scene=dict(xaxis_title='x', yaxis_title='y', zaxis_title='z'),\n",
" width=900,\n",
" height=700,\n",
" margin=dict(r=20, b=10, l=10, t=40)\n",
")\n",
"\n",
"fig.show()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9b3ada26-b4b7-42fc-b943-933c14adf89b",
"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.11"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|