├── .gitignore
├── Dataset
└── starwars_small_sample_data.pickle
├── LICENSE
├── Notebooks
└── Privacy_first_AI_search_using_LangChain_and_Elasticsearch.ipynb
├── README.md
├── lib_embeddings.py
├── lib_es_bulk.py
├── lib_llm.py
├── lib_vectordb.py
├── requirements.txt
├── run-full-scrape.sh
├── run-hosted-vectorize.sh
├── run-local-vectorize.sh
├── run-trivia.sh
├── run-upload-model.sh
├── step-1A-scrape-urls.py
├── step-1B-scrape-content.py
├── step-2A-local-embeddings.py
├── step-3A-upload-model.py
├── step-3B-batch-hosted-vectorize.py
├── step-4-win-at-trivia.py
└── terminal.jpg
/.gitignore:
--------------------------------------------------------------------------------
1 | venv
2 | env
3 | data
4 | __pycache__
5 | .DS_Store
6 | .env
7 | models
8 | cache
9 | Dataset/test
10 | Dataset/starwars_all_*
--------------------------------------------------------------------------------
/Dataset/starwars_small_sample_data.pickle:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elastic/blog-langchain-elasticsearch/e6f0ade92a33096ca3e2b6f386d851071def4e40/Dataset/starwars_small_sample_data.pickle
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # blog-langchain-elasticsearch
2 | *Experiment using elastic vector search and langchain*
3 |
4 | To run at small scale, check out this google colab [
](https://colab.research.google.com/github/elastic/blog-langchain-elasticsearch/blob/main/Notebooks/Privacy_first_AI_search_using_LangChain_and_Elasticsearch.ipynb)
5 |
6 | Those who remember the early days of Elasticsearch will remember that ES nodes were spawned with random superhero names that may or may not have come from a wiki scrape of super heros from a certain marvellous comic book universe. Personally, I was always more of a Star Wars fan. In celebration of May the 4th, and amid all the excitement of the rapidly evolving world of AI and Large Language Models, here's an experiment using Star Wars data to create a trivia bot that can answer Star Wars questions.
7 |
8 | The general design:
9 | 1. Scrape data from Wookieepedia
10 | 2. Insert that data into Elasticsearch along with a vector embedding for semantic search
11 | 3. create a simple chat loop with a local LLM.
12 | 4. Given a user's question, get the #1 most relevant paragraph from wookiepedia based on vector similarity
13 | 5. get the LLM to answer the question using some 'prompt engineering' shoving the paragraph into a context section of the call to the LLM.
14 |
15 | 
16 |
17 |
18 | # Setup
19 | ```sh
20 | python3 -m venv venv
21 | source venv/bin/activate
22 | pip install --upgrade pip
23 | pip install -r requirements.txt
24 | ```
25 |
26 | Or to directly install the libraries we'll need:
27 | ```sh
28 | pip install beautifulsoup4 eland elasticsearch huggingface-hub langchain tqdm torch requests sentence_transformers
29 | ```
30 |
31 | Now create a .env file in the root of this project with the following conent to protect your keys and passwords. You can create a free account at HuggingFace. Elastic Cloud is a great place to spin up a cluster for a short experiment, especially since in step 3 I'll be throwing some horsepower behind creating vector embeddings.
32 | ```sh
33 | export ES_SERVER="YOURDESSERVERNAME.es.us-central1.gcp.cloud.es.io"
34 | export ES_USERNAME="YOUR READ WRITE AND INDEX CREATING USER"
35 | export ES_PASSWORD="YOUR PASSWORD"
36 | ```
37 |
38 | # Step 1 - Pulling data from Wookiepedia
39 | You can skip this step as I've left a smaller sample with all the paragrpahs from a few key fresh star wars aritcles (Mandalorian Spoliers ahead) in starwars_small_canon_data.pickle
40 |
41 | Note ... unless you want the absolute freshest of Star Wars content, the first paragraphs of all of canon articles from Wookieepedia can be found in the inspriation for this blog post here: https://github.com/dennisbakhuis/wookieepediascience.
42 |
43 | Let's go easy on Wookieepedia's hosting company and not have every vector curious star wars fan scraping the data on the same day. If you do want to do a fresh scrape. The following code should first load up a list of the page URLs we want and 2nd a series of .pickle files containing the full page contents of each of those URLs. See Dennis Bakhuis' excellent blog for more on this code https://towardsdatascience.com/star-wars-data-science-d32acde3432d
44 |
45 | ```sh
46 | bash run-full-scrape.sh
47 | ```
48 |
49 | Expect to be throttled. For me, the full scrape was an overnight run. The script saves the pulled content as python dict objects (one serialization step away from JSON) to a set of .pickle files so you won't have to do this more than once.
50 |
51 |
52 | # Step 2 - Vectorizing the data locally
53 |
54 | We'll use a sentence transformer from huggingface hub "[sentence-transformers/all-mpnet-base-v2](https://huggingface.co/sentence-transformers/all-mpnet-base-v2)" to create a vector per paragraph
55 |
56 | ```sh
57 | bash run-local-vectorize.sh
58 | ```
59 |
60 | # Step 2 Alternative - let's do that faster in Elastic Cloud
61 |
62 | Step 2 may take a long time as there are some 180k+ paragraphs of text in Wookieepedia. As an alternative to step 2 we can push the compute to the cloud.
63 |
64 | The full blog post has instructions on how to get the vector load to run with more compute than a single laptop may be able to muster using Elastic Cloud. The setup of that is described onthe blog, but the code for the final load is here:
65 |
66 | ```sh
67 | bash run-hosted-vectorize.sh
68 | ```
69 |
70 | # Step 3 - Win at Star Wars trivia
71 |
72 | With the data loaded (it tool 30 minutes and about $25 of cloud compute for me). Scale your Cloud ML back down to zero or something more reasonable using the cloud console.
73 |
74 | Next let's play with some AI
75 |
76 | ```sh
77 | bash run-trivia.sh
78 | ```
79 |
80 | ## License
81 |
82 | The example: `blog-langchain-elasticsearch` is available under the Apache 2.0 license.
83 | For more details see [LICENSE](LICENSE).
84 |
--------------------------------------------------------------------------------
/lib_embeddings.py:
--------------------------------------------------------------------------------
1 | ## for embeddings
2 | from langchain.embeddings import HuggingFaceEmbeddings
3 |
4 | def setup_embeddings():
5 | # Huggingface embedding setup
6 | print(">> Prep. Huggingface embedding setup")
7 | model_name = "sentence-transformers/all-mpnet-base-v2"
8 | return HuggingFaceEmbeddings(model_name=model_name)
--------------------------------------------------------------------------------
/lib_es_bulk.py:
--------------------------------------------------------------------------------
1 | from elasticsearch import Elasticsearch, helpers
2 | import os
3 |
4 | es_server = os.environ.get("ES_SERVER")
5 | es_username = os.environ.get("ES_USERNAME")
6 | es_password = os.environ.get("ES_PASSWORD")
7 |
8 | batch_size = 25 # Set your desired batch size here
9 |
10 | def batchify(docs, batch_size):
11 | for i in range(0, len(docs), batch_size):
12 | yield docs[i:i + batch_size]
13 |
14 | def bulkLoadIndexPipeline( json_docs, index_name, pipeline):
15 | url = f"https://{es_username}:{es_password}@{es_server}:443"
16 | with Elasticsearch([url], verify_certs=True) as es:
17 |
18 | # doc_type = "_doc"
19 |
20 | # Create the index with the mapping if it doesn't exist
21 | # if not es.indices.exists(index=index_name):
22 | # es.indices.create(index=index_name, body=mapping)
23 |
24 | batches = list(batchify(json_docs, batch_size))
25 |
26 | for batch in batches:
27 | # Convert the JSON documents to the format required for bulk insertion
28 | bulk_docs = [
29 | {
30 | "_op_type": "index",
31 | "_index": index_name,
32 | "_source": doc,
33 | "pipeline": pipeline
34 | }
35 | for doc in batch
36 | ]
37 |
38 | # Perform bulk insertion
39 | success, errors = helpers.bulk(es, bulk_docs, raise_on_error=False)
40 | if errors:
41 | for error in errors:
42 | print(error)
43 | # print(f"Error in document {error['_id']}: {error['index']['error']}")
44 | # else:
45 | # print(f"Successfully inserted {success} documents.")
--------------------------------------------------------------------------------
/lib_llm.py:
--------------------------------------------------------------------------------
1 | ## for conversation LLM
2 | from langchain import PromptTemplate, HuggingFaceHub, LLMChain
3 | from langchain.llms import HuggingFacePipeline
4 | # import torch
5 | from transformers import AutoTokenizer, pipeline, AutoModelForSeq2SeqLM
6 | import os
7 |
8 | # from lib_webLLM import WebLLM
9 |
10 | OPTION_CUDA_USE_GPU = os.getenv('OPTION_CUDA_USE_GPU', 'False') == "True"
11 | cache_dir = "./cache"
12 |
13 |
14 | def getFlanLarge():
15 |
16 | model_id = 'google/flan-t5-large'
17 | print(f">> Prep. Get {model_id} ready to go")
18 | # model_id = 'google/flan-t5-large'# go for a smaller model if you dont have the VRAM
19 | tokenizer = AutoTokenizer.from_pretrained(model_id)
20 | if OPTION_CUDA_USE_GPU:
21 | model = AutoModelForSeq2SeqLM.from_pretrained(model_id, cache_dir=cache_dir, load_in_8bit=True, device_map='auto')
22 | model.cuda()
23 | else:
24 | model = AutoModelForSeq2SeqLM.from_pretrained(model_id, cache_dir=cache_dir)
25 |
26 | pipe = pipeline(
27 | "text2text-generation",
28 | model=model,
29 | tokenizer=tokenizer,
30 | max_length=100
31 | )
32 | llm = HuggingFacePipeline(pipeline=pipe)
33 | return llm
34 |
35 | ## options are flan and stablelm
36 | MODEL = "flan"
37 | local_llm = getFlanLarge()
38 |
39 |
40 | def make_the_llm():
41 | template_informed = """
42 | I am a helpful AI that answers questions. When I don't know the answer I say I don't know.
43 | I know context: {context}
44 | when asked: {question}
45 | my response using only information in the context is: """
46 |
47 | prompt_informed = PromptTemplate(template=template_informed, input_variables=["context", "question"])
48 |
49 | return LLMChain(prompt=prompt_informed, llm=local_llm)
--------------------------------------------------------------------------------
/lib_vectordb.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 |
4 | ## for vector store
5 | from langchain.vectorstores import ElasticVectorSearch
6 |
7 | def setup_vectordb(hf,index_name):
8 | # Elasticsearch URL setup
9 | print(">> Prep. Elasticsearch config setup")
10 | endpoint = os.getenv('ES_SERVER', 'ERROR')
11 | username = os.getenv('ES_USERNAME', 'ERROR')
12 | password = os.getenv('ES_PASSWORD', 'ERROR')
13 |
14 | url = f"https://{username}:{password}@{endpoint}:443"
15 |
16 | return ElasticVectorSearch(embedding=hf, elasticsearch_url=url, index_name=index_name), url
17 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | aiohttp==3.8.4
2 | aiosignal==1.3.1
3 | async-timeout==4.0.2
4 | attrs==23.1.0
5 | beautifulsoup4==4.12.2
6 | certifi==2022.12.7
7 | charset-normalizer==3.1.0
8 | click==8.1.3
9 | contourpy==1.0.7
10 | cycler==0.11.0
11 | dataclasses-json==0.5.7
12 | eland==8.7.0
13 | elastic-transport==8.4.0
14 | elasticsearch==8.7.0
15 | filelock==3.12.0
16 | fonttools==4.39.3
17 | frozenlist==1.3.3
18 | fsspec==2023.4.0
19 | huggingface-hub==0.14.1
20 | idna==3.4
21 | Jinja2==3.1.2
22 | joblib==1.2.0
23 | kiwisolver==1.4.4
24 | langchain==0.0.157
25 | MarkupSafe==2.1.2
26 | marshmallow==3.19.0
27 | marshmallow-enum==1.5.1
28 | matplotlib==3.7.1
29 | mpmath==1.3.0
30 | multidict==6.0.4
31 | mypy-extensions==1.0.0
32 | networkx==3.1
33 | nltk==3.8.1
34 | numexpr==2.8.4
35 | numpy==1.24.3
36 | openapi-schema-pydantic==1.2.4
37 | packaging==23.1
38 | pandas==2.0.1
39 | Pillow==9.5.0
40 | pydantic==1.10.7
41 | pyparsing==3.0.9
42 | python-dateutil==2.8.2
43 | pytz==2023.3
44 | PyYAML==6.0
45 | regex==2023.5.4
46 | requests==2.29.0
47 | scikit-learn==1.2.2
48 | scipy==1.10.1
49 | sentence-transformers==2.2.2
50 | sentencepiece==0.1.99
51 | six==1.16.0
52 | soupsieve==2.4.1
53 | SQLAlchemy==2.0.12
54 | sympy==1.11.1
55 | tenacity==8.2.2
56 | threadpoolctl==3.1.0
57 | tokenizers==0.13.3
58 | torch==2.0.0
59 | torchvision==0.15.1
60 | tqdm==4.65.0
61 | transformers==4.28.1
62 | typing-inspect==0.8.0
63 | typing_extensions==4.5.0
64 | tzdata==2023.3
65 | urllib3==1.26.15
66 | yarl==1.9.2
67 |
--------------------------------------------------------------------------------
/run-full-scrape.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | ## load the environment variables
4 | source .env
5 |
6 | python3 step-1A-scrape-urls.py
7 | python3 step-1B-scrape-content.py
8 |
--------------------------------------------------------------------------------
/run-hosted-vectorize.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | ## load the environment variables
4 | source .env
5 |
6 | python3 step-3B-batch-hosted-vectorize.py
--------------------------------------------------------------------------------
/run-local-vectorize.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | ## load the environment variables
4 | source .env
5 |
6 | python3 step-2A-local-embeddings.py
--------------------------------------------------------------------------------
/run-trivia.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | ## load the environment variables
4 | source .env
5 |
6 | python3 step-4-win-at-trivia.py
--------------------------------------------------------------------------------
/run-upload-model.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | ## load the environment variables
4 | source .env
5 |
6 | python3 step-3A-upload-model.py
--------------------------------------------------------------------------------
/step-1A-scrape-urls.py:
--------------------------------------------------------------------------------
1 | import requests
2 | from bs4 import BeautifulSoup
3 | import pickle
4 |
5 | print("""
6 | _______. ______ .______ ___ .______ _______
7 | / | / || _ \ / \ | _ \ | ____|
8 | | (----`| ,----'| |_) | / ^ \ | |_) | | |__
9 | \ \ | | | / / /_\ \ | ___/ | __|
10 | .----) | | `----.| |\ \----./ _____ \ | | | |____
11 | |_______/ \______|| _| `._____/__/ \__\ | _| |_______|
12 |
13 | """)
14 |
15 |
16 | page_url = 'https://starwars.fandom.com/wiki/Category:Canon_articles' # all canon articles
17 | base_url = 'https://starwars.fandom.com'
18 |
19 | pages = {}
20 | page_num = 1
21 | while page_url is not None:
22 | result = requests.get(page_url)
23 | content = result.content
24 | soup = BeautifulSoup(content, "html.parser")
25 |
26 | # extract urls
27 | links = soup.find_all('a', class_='category-page__member-link')
28 | links_before = len(pages)
29 | if links:
30 | for link in links:
31 | url = base_url + link.get('href')
32 | key = link.get('href').split('/')[-1]
33 | if 'Category:' not in key:
34 | pages[key] = url
35 | new_links = len(pages) - links_before
36 | print(f'Page {page_num} - {new_links} new links ({page_url})')
37 | page_num += 1
38 | # get next page button
39 | next_urls = soup.find_all("a", class_='category-page__pagination-next')
40 | if next_urls:
41 | new_url = next_urls[0].get('href')
42 | if new_url == page_url:
43 | break
44 | else:
45 | page_url = new_url
46 | else:
47 | page_url = None
48 |
49 |
50 |
51 | print(f'Number of pages: {len(pages)}')
52 |
53 | # Save to disk
54 | with open('./Dataset/starwars_all_canon_dict.pickle', 'wb') as f:
55 | pickle.dump(pages, f, protocol=pickle.HIGHEST_PROTOCOL)
--------------------------------------------------------------------------------
/step-1B-scrape-content.py:
--------------------------------------------------------------------------------
1 | import re
2 | from tqdm import tqdm
3 | import requests
4 | from bs4 import BeautifulSoup
5 | import pickle
6 | import json
7 |
8 | print("""
9 | ______ ______ .__ __. .___________. _______ .__ __. .___________.
10 | / | / __ \ | \ | | | || ____|| \ | | | |
11 | | ,----'| | | | | \| | `---| |----`| |__ | \| | `---| |----`
12 | | | | | | | | . ` | | | | __| | . ` | | |
13 | | `----.| `--' | | |\ | | | | |____ | |\ | | |
14 | \______| \______/ |__| \__| |__| |_______||__| \__| |__|
15 |
16 | """)
17 |
18 |
19 | scraped = {}
20 | failed = {}
21 | partition_size = 5000
22 | folder = './Dataset/'
23 |
24 | with open('./Dataset/starwars_all_canon_dict.pickle', 'rb') as f:
25 | pages = pickle.load(f)
26 |
27 | last_number = 0
28 | for ix, (key, page_url) in tqdm(enumerate(pages.items()), total=(len(pages))):
29 | try:
30 |
31 | # Get page
32 | result = requests.get(page_url)
33 | content = result.content
34 | soup = BeautifulSoup(content, "html.parser")
35 |
36 | # Get title
37 | heading = soup.find('h1', id='firstHeading')
38 | if heading is None: continue
39 | heading = heading.text
40 |
41 | # Extract Sidebar
42 | is_character = False
43 | side_bar = {}
44 | sec = soup.find_all('section', class_='pi-item')
45 | for s in sec:
46 | title = s.find('h2')
47 | if title is None:
48 | title = ''
49 | else:
50 | title = title.text
51 | side_bar[title] = {}
52 | items = s.find_all('div', class_='pi-item')
53 | for item in items:
54 | attr = item.find('h3', class_='pi-data-label')
55 | if attr is None:
56 | attr = ''
57 | else:
58 | attr = attr.text
59 | if attr == 'Species': is_character = True
60 | value = re.sub("[\(\[].*?[\)\]]" ,'', '], '.join(item.find('div', class_='pi-data-value').text.split(']')))
61 | value = value.strip()[:-1].replace(',,', ',')
62 | if ',' in value:
63 | value = [i.strip() for i in value.split(',') if i.strip() != '']
64 | side_bar[title][attr] = value
65 |
66 | # Raw page content
67 | raw_content = soup.find('div', class_='mw-parser-output')
68 | if raw_content is not None:
69 | content_pgs = []
70 | for raw_paragraph in raw_content.find_all('p', recursive=False):
71 | if 'aside' in str(raw_paragraph): continue
72 | content_pgs.append(re.sub("[\(\[].*?[\)\]]" ,'', raw_paragraph.text) )
73 | # paragraph = value = re.sub("[\(\[].*?[\)\]]" ,'', raw_paragraph.text)
74 |
75 | # cross-links
76 | keywords = []
77 | for link in raw_content.find_all('a'):
78 | part = link.get('href')
79 | if part is not None:
80 | part = part.split('/')[-1]
81 | if part in pages.keys() and part != key:
82 | keywords.append(part)
83 | keywords = list(set(keywords))
84 | else:
85 | # Empty page
86 | keywords = []
87 | paragraph = ''
88 |
89 | # Data object
90 | scraped[key] = {
91 | 'url': page_url,
92 | 'title': heading,
93 | 'is_character': is_character,
94 | 'side_bar': side_bar,
95 | 'paragraph': content_pgs,
96 | 'crosslinks': keywords,
97 | }
98 |
99 | # print(json.dumps(scraped[key],indent=4))
100 |
101 |
102 | # save partition
103 | if (ix + 1) % partition_size == 0:
104 | last_number = (ix+1) // partition_size
105 | fn = folder + f'starwars_all_canon_data_{last_number}.pickle'
106 | with open(fn, 'wb') as f:
107 | pickle.dump(scraped, f, protocol=pickle.HIGHEST_PROTOCOL)
108 | scraped = {}
109 | except:
110 | print('Failed!')
111 | failed[key] = page_url
112 |
113 | # Save final part to disk
114 | if 'last_number' not in locals():
115 | last_number = 0
116 | fn = folder + f'starwars_all_canon_data_{last_number + 1}.pickle'
117 | with open(fn, 'wb') as f:
118 | pickle.dump(scraped, f, protocol=pickle.HIGHEST_PROTOCOL)
--------------------------------------------------------------------------------
/step-2A-local-embeddings.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import lib_embeddings
4 | import lib_vectordb
5 |
6 | from pathlib import Path
7 | import pickle
8 |
9 | from elasticsearch import Elasticsearch
10 | from tqdm import tqdm
11 |
12 | print("""
13 | ____ ____ _______ ______ .___________. ______ .______
14 | \ \ / / | ____| / || | / __ \ | _ \
15 | \ \/ / | |__ | ,----'`---| |----`| | | | | |_) |
16 | \ / | __| | | | | | | | | | /
17 | \ / | |____ | `----. | | | `--' | | |\ \----.
18 | \__/ |_______| \______| |__| \______/ | _| `._____|
19 |
20 | """)
21 |
22 |
23 | bookFilePath = "starwars_all_canon_data_*.pickle"
24 | index_name = "book_wookieepedia_test"
25 |
26 | ## Prepp the local transformer
27 | hf = lib_embeddings.setup_embeddings()
28 |
29 | ## Elasticsearch as a vector db
30 | db, url = lib_vectordb.setup_vectordb(hf,index_name)
31 |
32 | count = 0
33 | files = sorted(Path('./Dataset').glob(bookFilePath))
34 | for fn in files:
35 | print(f"Starting book: {fn}")
36 | with open(fn,'rb') as f:
37 | part = pickle.load(f)
38 | batchtext = []
39 | for ix, (key, value) in tqdm(enumerate(part.items()), total=len(part)):
40 | title = value['title'].strip()
41 | sw_url = value['url']
42 | paragraphs = value['paragraph']
43 | for px, p in enumerate(paragraphs):
44 | # print(f"{ix} {px} {title}")
45 | batchtext.append(p)
46 | count = count + 1
47 | if len(batchtext) >= 100:
48 | db.from_texts(batchtext, embedding=hf, elasticsearch_url=url, index_name=index_name)
49 | batchtext = []
50 | db.from_texts(batchtext, embedding=hf, elasticsearch_url=url, index_name=index_name)
51 | batchtext = []
52 | print(f"Count {count}")
53 |
54 |
55 |
--------------------------------------------------------------------------------
/step-3A-upload-model.py:
--------------------------------------------------------------------------------
1 |
2 | import elasticsearch
3 | from pathlib import Path
4 | from eland.ml.pytorch import PyTorchModel
5 | from eland.ml.pytorch.transformers import TransformerModel
6 | import requests
7 | import os
8 |
9 | print("""
10 | __ __ .______ __ ______ ___ _______
11 | | | | | | _ \ | | / __ \ / \ | \
12 | | | | | | |_) | | | | | | | / ^ \ | .--. |
13 | | | | | | ___/ | | | | | | / /_\ \ | | | |
14 | | `--' | | | | `----.| `--' | / _____ \ | '--' |
15 | \______/ | _| |_______| \______/ /__/ \__\ |_______/
16 |
17 | """)
18 |
19 |
20 | model_id= "sentence-transformers/all-mpnet-base-v2"
21 |
22 | endpoint = os.getenv('ES_SERVER', 'ERROR')
23 | username = os.getenv('ES_USERNAME', 'ERROR')
24 | password = os.getenv('ES_PASSWORD', 'ERROR')
25 |
26 | es_url = f"https://{username}:{password}@{endpoint}:443"
27 |
28 | # Load a Hugging Face transformers model directly from the model hub
29 | tm = TransformerModel(f"{model_id}", "text_embedding")
30 |
31 | tmp_path = "models"
32 | Path(tmp_path).mkdir(parents=True, exist_ok=True)
33 | model_path, config, vocab_path = tm.save(tmp_path)
34 |
35 | es = elasticsearch.Elasticsearch(es_url, timeout=300) # 5 minute timeout
36 | ptm = PyTorchModel(es, tm.elasticsearch_model_id())
37 | try:
38 | ptm.import_model(model_path=model_path, config_path=None, vocab_path=vocab_path, config=config)
39 | except Exception as error:
40 | # Handle the BadRequestError exception here
41 | if error.meta.status == 400 and error.message == "resource_already_exists_exception":
42 | print("Done -- the model was already loaded")
43 | else:
44 | print("An error occurred:", str(error))
45 |
46 |
47 | # def deploy_model(model_id,es_url):
48 | # url = f"{es_url}/_ml/trained_models/{model_id}/deployment/_start"
49 | # response = requests.post(url)
50 | # if response.status_code == 200:
51 | # print("Model Deployed")
52 | # else:
53 | # print("Error deploying model: ", response.text)
54 |
55 | # deploy_model(es_model_id,es_url)
56 |
57 | # mapping = {
58 | # "mappings": {
59 | # "properties": {
60 | # "metadata": {
61 | # "type": "object"
62 | # },
63 | # "text": {
64 | # "type": "text"
65 | # },
66 | # "vector": {
67 | # "type": "dense_vector",
68 | # "dims": 768
69 | # }
70 | # }
71 | # }
72 | # }
--------------------------------------------------------------------------------
/step-3B-batch-hosted-vectorize.py:
--------------------------------------------------------------------------------
1 |
2 | from lib_es_bulk import bulkLoadIndexPipeline
3 |
4 | import os
5 |
6 | from pathlib import Path
7 | import pickle
8 |
9 | from elasticsearch import Elasticsearch
10 |
11 | from tqdm import tqdm
12 |
13 | print("""
14 | ______ __ ______ __ __ _______
15 | / || | / __ \ | | | | | \
16 | | ,----'| | | | | | | | | | | .--. |
17 | | | | | | | | | | | | | | | | |
18 | | `----.| `----.| `--' | | `--' | | '--' |
19 | \______||_______| \______/ \______/ |_______/
20 |
21 | """)
22 |
23 |
24 | bookName = "Wookieepedia",
25 | bookFilePath = "starwars_all_canon_data_*.pickle"
26 | index_name = "book_wookieepedia_mpnet"
27 |
28 | endpoint = os.getenv('ES_SERVER', 'ERROR')
29 | username = os.getenv('ES_USERNAME', 'ERROR')
30 | password = os.getenv('ES_PASSWORD', 'ERROR')
31 |
32 | url = f"https://{username}:{password}@{endpoint}:443"
33 |
34 |
35 | ## Load the book
36 |
37 | count = 0
38 | with Elasticsearch([url], verify_certs=True) as es:
39 | files = sorted(Path('./Dataset').glob(bookFilePath))
40 | for fn in files:
41 | print(f"Starting book: {fn}")
42 | with open(fn,'rb') as f:
43 | part = pickle.load(f)
44 | batch = []
45 | for ix, (key, value) in tqdm(enumerate(part.items()), total=len(part)):
46 | title = value['title'].strip()
47 | sw_url = value['url']
48 | paragraphs = value['paragraph']
49 | for px, p in enumerate(paragraphs):
50 | payload = {
51 | "text": p,
52 | "metadata":{
53 | "title": title,
54 | "url": sw_url,
55 | "pg_num": px
56 | }
57 | }
58 | # print(f"{ix} {px} {title}")
59 | batch.append(payload)
60 | count = count + 1
61 | if len(batch) >= 100:
62 | bulkLoadIndexPipeline(batch,index_name,"sw-embeddings")
63 | batch = []
64 |
65 | bulkLoadIndexPipeline(batch,index_name,"sw-embeddings")
66 | print(f"Count {count}")
67 |
68 |
69 |
--------------------------------------------------------------------------------
/step-4-win-at-trivia.py:
--------------------------------------------------------------------------------
1 | import lib_llm
2 | import lib_embeddings
3 | import lib_vectordb
4 |
5 |
6 | print("""
7 | .___ ___. ___ ____ ____ .___________. __ __ _______ _ _ .___________. __ __
8 | | \/ | / \ \ \ / / | || | | | | ____| | || | | || | | |
9 | | \ / | / ^ \ \ \/ / `---| |----`| |__| | | |__ | || |_ `---| |----`| |__| |
10 | | |\/| | / /_\ \ \_ _/ | | | __ | | __| |__ _| | | | __ |
11 | | | | | / _____ \ | | | | | | | | | |____ | | | | | | | |
12 | |__| |__| /__/ \__\ |__| |__| |__| |__| |_______| |_| |__| |__| |__|
13 |
14 | .______ _______ ____ __ ____ __ .___________. __ __ ____ ____ ______ __ __
15 | | _ \ | ____| \ \ / \ / / | | | || | | | \ \ / / / __ \ | | | |
16 | | |_) | | |__ \ \/ \/ / | | `---| |----`| |__| | \ \/ / | | | | | | | |
17 | | _ < | __| \ / | | | | | __ | \_ _/ | | | | | | | |
18 | | |_) | | |____ \ /\ / | | | | | | | | | | | `--' | | `--' |
19 | |______/ |_______| \__/ \__/ |__| |__| |__| |__| |__| \______/ \______/
20 |
21 | """)
22 |
23 |
24 | topic = "Star Wars"
25 | index_name = "book_wookieepedia_mpnet"
26 |
27 | # Huggingface embedding setup
28 | hf = lib_embeddings.setup_embeddings()
29 |
30 | ## Elasticsearch as a vector db
31 | db, url = lib_vectordb.setup_vectordb(hf,index_name)
32 |
33 | ## set up the conversational LLM
34 | llm_chain_informed= lib_llm.make_the_llm()
35 |
36 |
37 | ## how to ask a question
38 | def ask_a_question(question):
39 | # print("The Question at hand: "+question)
40 |
41 | ## 3. get the relevant chunk from Elasticsearch for a question
42 | # print(">> 3. get the relevant chunk from Elasticsearch for a question")
43 | similar_docs = db.similarity_search(question)
44 | print(f'The most relevant passage: \n\t{similar_docs[0].page_content}')
45 |
46 | ## 4. Ask Local LLM context informed prompt
47 | # print(">> 4. Asking The Book ... and its response is: ")
48 |
49 | informed_context= similar_docs[0].page_content
50 | informed_response = llm_chain_informed.run(context=informed_context,question=question)
51 |
52 | return informed_response
53 |
54 |
55 | # The conversational loop
56 |
57 | print(f'I am a trivia chat bot, ask me any question about {topic}')
58 |
59 | while True:
60 | command = input("User Question >> ")
61 | response= ask_a_question(command)
62 | print(f"\tAnswer : {response}")
63 |
64 |
--------------------------------------------------------------------------------
/terminal.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/elastic/blog-langchain-elasticsearch/e6f0ade92a33096ca3e2b6f386d851071def4e40/terminal.jpg
--------------------------------------------------------------------------------