|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "markdown", |
| 5 | + "id": "430bd0198f228af0", |
| 6 | + "metadata": {}, |
| 7 | + "source": [ |
| 8 | + "# RAG with Elastic ELSER and Llama3 using Langchain\n", |
| 9 | + "\n", |
| 10 | + "This interactive notebook uses `Langchain` to process fictional workplace documents and uses `ELSER v2` running in `Elasticsearch` to transform these documents into embeddings and store them into `Elasticsearch`. We then ask a question, retrieve the relevant documents from `Elasticsearch` and use `Llama3` running locally using `Ollama` to provide a response. \n", |
| 11 | + "\n", |
| 12 | + "**_Note_** : _`Llama3` is expected to be running using `Ollama` on the same machine where you will be running this notebook._" |
| 13 | + ] |
| 14 | + }, |
| 15 | + { |
| 16 | + "cell_type": "markdown", |
| 17 | + "id": "fc4d3a839afa5bf1", |
| 18 | + "metadata": {}, |
| 19 | + "source": [ |
| 20 | + "## Requirements\n", |
| 21 | + "\n", |
| 22 | + "For this example, you will need:\n", |
| 23 | + "\n", |
| 24 | + "- An Elastic deployment\n", |
| 25 | + " - We'll be using [Elastic Cloud](https://www.elastic.co/guide/en/cloud/current/ec-getting-started.html) for this example (available with a [free trial](https://cloud.elastic.co/registration?utm_source=github&utm_content=elasticsearch-labs-notebook))\n", |
| 26 | + " - For LLM we will be using [Ollama](https://ollama.com/) and [Llama3](https://ollama.com/library/llama3) configured locally. \n", |
| 27 | + "\n", |
| 28 | + "### Use Elastic Cloud\n", |
| 29 | + "\n", |
| 30 | + "If you don't have an Elastic Cloud deployment, follow these steps to create one.\n", |
| 31 | + "\n", |
| 32 | + "1. Go to [Elastic cloud Registration](https://cloud.elastic.co/registration?utm_source=github&utm_content=elasticsearch-labs-notebook) and sign up for a free trial\n", |
| 33 | + "2. Select **Create Deployment** and follow the instructions" |
| 34 | + ] |
| 35 | + }, |
| 36 | + { |
| 37 | + "cell_type": "markdown", |
| 38 | + "id": "7497ed11046b9a21", |
| 39 | + "metadata": {}, |
| 40 | + "source": [ |
| 41 | + "## Install required dependencies\n", |
| 42 | + "First we install the packages we need for this example." |
| 43 | + ] |
| 44 | + }, |
| 45 | + { |
| 46 | + "cell_type": "code", |
| 47 | + "execution_count": null, |
| 48 | + "id": "a0c049f18215f065", |
| 49 | + "metadata": {}, |
| 50 | + "outputs": [], |
| 51 | + "source": [ |
| 52 | + "!pip install langchain langchain-elasticsearch langchain-community tiktoken" |
| 53 | + ] |
| 54 | + }, |
| 55 | + { |
| 56 | + "cell_type": "markdown", |
| 57 | + "id": "e97921e3cf79cc71", |
| 58 | + "metadata": {}, |
| 59 | + "source": [ |
| 60 | + "## Import packages\n", |
| 61 | + "Next we import the required packages as required. The imports are placed in the cells as required." |
| 62 | + ] |
| 63 | + }, |
| 64 | + { |
| 65 | + "cell_type": "markdown", |
| 66 | + "id": "96d6fab134fd493d", |
| 67 | + "metadata": {}, |
| 68 | + "source": [ |
| 69 | + "## Prompt user to provide Cloud ID and API Key\n", |
| 70 | + "We now prompt the user to provide us Cloud ID and API Key using `getpass`. We get these details from the deployment." |
| 71 | + ] |
| 72 | + }, |
| 73 | + { |
| 74 | + "cell_type": "code", |
| 75 | + "execution_count": null, |
| 76 | + "id": "5be75ecc855e59b9", |
| 77 | + "metadata": { |
| 78 | + "ExecuteTime": { |
| 79 | + "end_time": "2024-06-04T11:36:07.879351Z", |
| 80 | + "start_time": "2024-06-04T11:35:57.006555Z" |
| 81 | + } |
| 82 | + }, |
| 83 | + "outputs": [], |
| 84 | + "source": [ |
| 85 | + "from getpass import getpass\n", |
| 86 | + "\n", |
| 87 | + "# https://www.elastic.co/search-labs/tutorials/install-elasticsearch/elastic-cloud#finding-your-cloud-id\n", |
| 88 | + "ELASTIC_CLOUD_ID = getpass(\"Elastic Cloud ID: \")\n", |
| 89 | + "\n", |
| 90 | + "# https://www.elastic.co/search-labs/tutorials/install-elasticsearch/elastic-cloud#creating-an-api-key\n", |
| 91 | + "ELASTIC_API_KEY = getpass(\"Elastic Api Key: \")" |
| 92 | + ] |
| 93 | + }, |
| 94 | + { |
| 95 | + "cell_type": "markdown", |
| 96 | + "id": "84f107432173d8df", |
| 97 | + "metadata": {}, |
| 98 | + "source": [ |
| 99 | + "## Prepare documents for chunking and ingestion\n", |
| 100 | + "We now prepare the data to be ingested into `Elasticsearch`. We use `LangChain`'s `RecursiveCharacterTextSplitter` and split the documents' text at 512 characters with an overlap of 256 characters. " |
| 101 | + ] |
| 102 | + }, |
| 103 | + { |
| 104 | + "cell_type": "code", |
| 105 | + "execution_count": null, |
| 106 | + "id": "4f949859a20b22d6", |
| 107 | + "metadata": { |
| 108 | + "ExecuteTime": { |
| 109 | + "end_time": "2024-06-04T11:36:11.046835Z", |
| 110 | + "start_time": "2024-06-04T11:36:10.641480Z" |
| 111 | + } |
| 112 | + }, |
| 113 | + "outputs": [], |
| 114 | + "source": [ |
| 115 | + "from urllib.request import urlopen\n", |
| 116 | + "import json\n", |
| 117 | + "from langchain.text_splitter import RecursiveCharacterTextSplitter\n", |
| 118 | + "\n", |
| 119 | + "\n", |
| 120 | + "url = \"https://raw.githubusercontent.com/elastic/elasticsearch-labs/main/datasets/workplace-documents.json\"\n", |
| 121 | + "\n", |
| 122 | + "response = urlopen(url)\n", |
| 123 | + "\n", |
| 124 | + "workplace_docs = json.loads(response.read())\n", |
| 125 | + "metadata = []\n", |
| 126 | + "content = []\n", |
| 127 | + "for doc in workplace_docs:\n", |
| 128 | + " content.append(doc[\"content\"])\n", |
| 129 | + " metadata.append(\n", |
| 130 | + " {\n", |
| 131 | + " \"name\": doc[\"name\"],\n", |
| 132 | + " \"summary\": doc[\"summary\"],\n", |
| 133 | + " \"rolePermissions\": doc[\"rolePermissions\"],\n", |
| 134 | + " }\n", |
| 135 | + " )\n", |
| 136 | + "\n", |
| 137 | + "text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(\n", |
| 138 | + " chunk_size=512, chunk_overlap=256\n", |
| 139 | + ")\n", |
| 140 | + "docs = text_splitter.create_documents(content, metadatas=metadata)" |
| 141 | + ] |
| 142 | + }, |
| 143 | + { |
| 144 | + "cell_type": "markdown", |
| 145 | + "id": "a52ec8a0a663f581", |
| 146 | + "metadata": {}, |
| 147 | + "source": [ |
| 148 | + "## Define Elasticsearch Vector Store\n", |
| 149 | + "We define `ElasticsearchStore` as the vector store with [SparseVectorStrategy](https://python.langchain.com/v0.2/docs/integrations/vectorstores/elasticsearch/#sparsevectorstrategy-elser).`SparseVectorStrategy` converts each document into tokens and would be stored in vector field with datatype `rank_features`.\n", |
| 150 | + "We will be using text embedding from [ELSER v2](https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-elser.html#elser-v2) model `.elser_model_2_linux-x86_64`\n", |
| 151 | + "\n", |
| 152 | + "Note: Before we begin indexing, ensure you have [downloaded and deployed ELSER v2 model](https://www.elastic.co/guide/en/machine-learning/current/ml-nlp-elser.html#download-deploy-elser) in your deployment and is running in ml node. " |
| 153 | + ] |
| 154 | + }, |
| 155 | + { |
| 156 | + "cell_type": "code", |
| 157 | + "execution_count": null, |
| 158 | + "id": "fc52a85c69f6e9fb", |
| 159 | + "metadata": { |
| 160 | + "ExecuteTime": { |
| 161 | + "end_time": "2024-06-04T11:36:33.046663Z", |
| 162 | + "start_time": "2024-06-04T11:36:32.381802Z" |
| 163 | + } |
| 164 | + }, |
| 165 | + "outputs": [], |
| 166 | + "source": [ |
| 167 | + "from langchain_elasticsearch import ElasticsearchStore\n", |
| 168 | + "from langchain_elasticsearch import SparseVectorStrategy\n", |
| 169 | + "\n", |
| 170 | + "es_vector_store = ElasticsearchStore(\n", |
| 171 | + " es_cloud_id=ELASTIC_CLOUD_ID,\n", |
| 172 | + " es_api_key=ELASTIC_API_KEY,\n", |
| 173 | + " index_name=\"workplace_index_elser\",\n", |
| 174 | + " strategy=SparseVectorStrategy(model_id=\".elser_model_2_linux-x86_64\"),\n", |
| 175 | + ")" |
| 176 | + ] |
| 177 | + }, |
| 178 | + { |
| 179 | + "cell_type": "markdown", |
| 180 | + "id": "7f38b91b2a358994", |
| 181 | + "metadata": {}, |
| 182 | + "source": [ |
| 183 | + "## Add docs processed above. \n", |
| 184 | + "The document has already been chunked. We do not use any specific embedding function here, since the tokens are inferred at index time and at query time within Elasticsearch. \n", |
| 185 | + "This requires that the `ELSER v2` model to be loaded and running in Elasticsearch." |
| 186 | + ] |
| 187 | + }, |
| 188 | + { |
| 189 | + "cell_type": "code", |
| 190 | + "execution_count": null, |
| 191 | + "id": "5ee38329856ea47c", |
| 192 | + "metadata": {}, |
| 193 | + "outputs": [], |
| 194 | + "source": [ |
| 195 | + "es_vector_store.add_documents(documents=docs)" |
| 196 | + ] |
| 197 | + }, |
| 198 | + { |
| 199 | + "cell_type": "markdown", |
| 200 | + "id": "8a5a628abfb6a5a", |
| 201 | + "metadata": {}, |
| 202 | + "source": [ |
| 203 | + "## LLM Configuration\n", |
| 204 | + "This connects to your local LLM. Please refer to https://ollama.com/library/llama3 for details on steps to run Llama3 locally. \n", |
| 205 | + "\n", |
| 206 | + "_If you have sufficient resources (atleast >64 GB Ram and GPU available) then you could try the 70B parameter version of Llama3_\n" |
| 207 | + ] |
| 208 | + }, |
| 209 | + { |
| 210 | + "cell_type": "code", |
| 211 | + "execution_count": null, |
| 212 | + "id": "23e35e152e9a2714", |
| 213 | + "metadata": { |
| 214 | + "ExecuteTime": { |
| 215 | + "end_time": "2024-06-04T11:36:40.306996Z", |
| 216 | + "start_time": "2024-06-04T11:36:40.302460Z" |
| 217 | + } |
| 218 | + }, |
| 219 | + "outputs": [], |
| 220 | + "source": [ |
| 221 | + "from langchain_community.llms import Ollama\n", |
| 222 | + "\n", |
| 223 | + "llm = Ollama(model=\"llama3\")" |
| 224 | + ] |
| 225 | + }, |
| 226 | + { |
| 227 | + "cell_type": "markdown", |
| 228 | + "id": "dbca801f2aae187", |
| 229 | + "metadata": {}, |
| 230 | + "source": [ |
| 231 | + "## Semantic Search using Elasticsearch ELSER v2 and Llama3\n", |
| 232 | + "\n", |
| 233 | + "We will perform a semantic search on query with `ELSER v2` as the model. The contextually relevant answer is then composed into a template along with the users original query. \n", |
| 234 | + "\n", |
| 235 | + "We then user `Llama3` to answer your questions with contextually relevant data fetched earlier from Elasticsearch using the retriever. " |
| 236 | + ] |
| 237 | + }, |
| 238 | + { |
| 239 | + "cell_type": "code", |
| 240 | + "execution_count": null, |
| 241 | + "id": "d348766295f19e35", |
| 242 | + "metadata": {}, |
| 243 | + "outputs": [], |
| 244 | + "source": [ |
| 245 | + "from langchain.prompts import ChatPromptTemplate\n", |
| 246 | + "from langchain.schema.output_parser import StrOutputParser\n", |
| 247 | + "from langchain.schema.runnable import RunnablePassthrough\n", |
| 248 | + "\n", |
| 249 | + "\n", |
| 250 | + "def format_docs(docs):\n", |
| 251 | + " return \"\\n\\n\".join(doc.page_content for doc in docs)\n", |
| 252 | + "\n", |
| 253 | + "\n", |
| 254 | + "retriever = es_vector_store.as_retriever()\n", |
| 255 | + "template = \"\"\"Answer the question based only on the following context:\\n\n", |
| 256 | + "\n", |
| 257 | + " {context}\n", |
| 258 | + " \n", |
| 259 | + " Question: {question}\n", |
| 260 | + " \"\"\"\n", |
| 261 | + "prompt = ChatPromptTemplate.from_template(template)\n", |
| 262 | + "chain = (\n", |
| 263 | + " {\"context\": retriever | format_docs, \"question\": RunnablePassthrough()}\n", |
| 264 | + " | prompt\n", |
| 265 | + " | llm\n", |
| 266 | + " | StrOutputParser()\n", |
| 267 | + ")\n", |
| 268 | + "\n", |
| 269 | + "a = chain.invoke(\"What are the organizations sales goals?\")\n", |
| 270 | + "\n", |
| 271 | + "print(a)" |
| 272 | + ] |
| 273 | + }, |
| 274 | + { |
| 275 | + "cell_type": "markdown", |
| 276 | + "id": "1e855e64da97b052", |
| 277 | + "metadata": {}, |
| 278 | + "source": [ |
| 279 | + "_You could now try experimenting with other questions._\n" |
| 280 | + ] |
| 281 | + } |
| 282 | + ], |
| 283 | + "metadata": { |
| 284 | + "kernelspec": { |
| 285 | + "display_name": "Python 3 (ipykernel)", |
| 286 | + "language": "python", |
| 287 | + "name": "python3" |
| 288 | + }, |
| 289 | + "language_info": { |
| 290 | + "codemirror_mode": { |
| 291 | + "name": "ipython", |
| 292 | + "version": 3 |
| 293 | + }, |
| 294 | + "file_extension": ".py", |
| 295 | + "mimetype": "text/x-python", |
| 296 | + "name": "python", |
| 297 | + "nbconvert_exporter": "python", |
| 298 | + "pygments_lexer": "ipython3", |
| 299 | + "version": "3.10.12" |
| 300 | + } |
| 301 | + }, |
| 302 | + "nbformat": 4, |
| 303 | + "nbformat_minor": 5 |
| 304 | +} |
0 commit comments