├── README.md ├── vector_encoder_parent.py ├── openai_vector_encoder.py ├── openai_qa_chatbot.py ├── requirements.txt ├── .gitignore ├── vector_indexer.py ├── wiki_datasource.py ├── qa_chatbot.py ├── kohonen_som.py ├── som_based_rag.py ├── LICENSE └── OpenAI_Based_SOM_GPT2_Bot.ipynb /README.md: -------------------------------------------------------------------------------- 1 | # som-driven-qa-rag 2 | Self Organizing Maps (SOM) ML model can be used to conduct semantic search to populate context required for Retrieval Augmented Generation (RAG) LLM models. This repo contains an example to demonstrate the SOM capability. 3 | -------------------------------------------------------------------------------- /vector_encoder_parent.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | ''' 3 | ------------------------------------------------------------------------------ 4 | Copyright 2024 Murali Kashaboina 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | ------------------------------------------------------------------------------ 18 | ''' 19 | 20 | from abc import ABC, abstractmethod 21 | 22 | import torch 23 | 24 | from typing import List 25 | 26 | class VectorEncoder( ABC ): 27 | def __init__( self, encoded_vector_dimensions : int ): 28 | self.encoded_vector_dimensions = int( encoded_vector_dimensions ) 29 | 30 | def get_encoded_vector_dimensions( self ) -> int : 31 | return self.encoded_vector_dimensions 32 | 33 | @abstractmethod 34 | def encode( self, text : str ) -> torch.Tensor : 35 | pass 36 | 37 | @abstractmethod 38 | def encode_batch( self, list_of_text : List[ str ] ) -> torch.Tensor : 39 | pass -------------------------------------------------------------------------------- /openai_vector_encoder.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | ''' 3 | ------------------------------------------------------------------------------ 4 | Copyright 2024 Murali Kashaboina 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | ------------------------------------------------------------------------------ 18 | ''' 19 | 20 | import openai 21 | 22 | from openai.embeddings_utils import get_embedding 23 | 24 | import torch 25 | 26 | from vector_encoder_parent import VectorEncoder 27 | 28 | from typing import List 29 | 30 | 31 | class OpenAIEmbeddingsVectorEncoder( VectorEncoder ): 32 | def __init__( 33 | self, 34 | encoded_vector_dimensions : int, 35 | vector_encoder_id : str, 36 | openai_key : str 37 | ): 38 | super().__init__( encoded_vector_dimensions ) 39 | 40 | if vector_encoder_id == None or len( vector_encoder_id.strip() ) == 0: 41 | raise ValueError( "ERROR: vector_encoder_id must be specified" ) 42 | 43 | if openai_key == None or len( openai_key.strip() ) == 0: 44 | raise ValueError( "ERROR: openai_key must be specified" ) 45 | 46 | self.vector_encoder_id = vector_encoder_id.strip() 47 | 48 | self.openai_key = openai_key.strip() 49 | 50 | def encode( self, text : str ) -> torch.Tensor: 51 | if text == None or len( text.strip() ) == 0: 52 | raise ValueError( "ERROR: Required text is not specified" ) 53 | 54 | openai.api_key = self.openai_key 55 | 56 | embeddings = get_embedding( text, engine = self.vector_encoder_id ) 57 | 58 | vector = torch.tensor( embeddings, dtype=torch.float ) 59 | 60 | return vector 61 | 62 | def encode_batch( self, list_of_text : List[ str ] ) -> torch.Tensor : 63 | if list_of_text == None or len( list_of_text ) == 0: 64 | raise ValueError( "ERROR: Required list_of_text is None or empty" ) 65 | 66 | list_of_text = [ str( text ) for text in list_of_text ] 67 | 68 | openai.api_key = self.openai_key 69 | 70 | response = openai.Embedding.create( 71 | input = list_of_text, 72 | engine = self.vector_encoder_id 73 | ) 74 | 75 | embeddings = [ data["embedding"] for data in response["data"] ] 76 | 77 | vectors = torch.tensor( embeddings, dtype=torch.float ) 78 | 79 | return vectors 80 | -------------------------------------------------------------------------------- /openai_qa_chatbot.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | ''' 3 | ------------------------------------------------------------------------------ 4 | Copyright 2024 Murali Kashaboina 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | ------------------------------------------------------------------------------ 18 | ''' 19 | 20 | import openai 21 | 22 | import tiktoken 23 | 24 | from qa_chatbot import QuestionAnswerChatBot 25 | 26 | class OpenAIQuestionAnswerChatBot( QuestionAnswerChatBot ): 27 | def __init__( 28 | self, 29 | vector_db_util = None, 30 | openai_tokenizer_name : str = None, 31 | openai_model_name : str = None, 32 | openai_key : str = None, 33 | question_input_max_token_count : int = 768, 34 | context_trim_percent :float = 0.05, 35 | device : str = None 36 | ): 37 | super().__init__( 38 | vector_db_util, 39 | question_input_max_token_count = question_input_max_token_count, 40 | context_trim_percent = context_trim_percent, 41 | device = device 42 | ) 43 | if openai_tokenizer_name == None or len( openai_tokenizer_name.strip() ) == 0: 44 | raise ValueError( "ERROR: openai_tokenizer_name must be specified" ) 45 | 46 | if openai_model_name == None or len( openai_model_name.strip() ) == 0: 47 | raise ValueError( "ERROR: openai_model_name must be specified" ) 48 | 49 | if openai_key == None or len( openai_key.strip() ) == 0: 50 | raise ValueError( "ERROR: openai_key must be specified" ) 51 | 52 | self.openai_tokenizer_name = openai_tokenizer_name.strip() 53 | 54 | self.tokenizer = tiktoken.get_encoding( self.openai_tokenizer_name ) 55 | 56 | self.openai_model_name = openai_model_name.strip() 57 | 58 | self.openai_key = openai_key.strip() 59 | 60 | def __get_answer_text__( self, qa_instruction : str, max_new_tokens : int = 5 ) -> str : 61 | openai.api_key = self.openai_key 62 | 63 | basic_answer = openai.Completion.create( 64 | model = self.openai_model_name, 65 | prompt = qa_instruction, 66 | 67 | ) 68 | 69 | answer_text = basic_answer[ "choices" ][0][ "text" ] 70 | 71 | return answer_text 72 | 73 | def __token_count__( self, text : str ): 74 | return len( self.tokenizer.encode( text ) ) 75 | 76 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | accelerate==0.26.1 2 | aiohttp==3.8.4 3 | aiosignal==1.3.1 4 | annotated-types==0.6.0 5 | anyio==3.6.2 6 | argon2-cffi==21.3.0 7 | argon2-cffi-bindings==21.2.0 8 | arrow==1.2.3 9 | asttokens==2.2.1 10 | async-lru==2.0.2 11 | async-timeout==4.0.2 12 | attrs==23.1.0 13 | Babel==2.12.1 14 | backcall==0.2.0 15 | beautifulsoup4==4.12.2 16 | bleach==6.0.0 17 | certifi==2023.5.7 18 | cffi==1.15.1 19 | charset-normalizer==3.1.0 20 | click==8.1.7 21 | comm==0.1.3 22 | contourpy==1.0.7 23 | cycler==0.11.0 24 | datasets==2.16.1 25 | debugpy==1.6.7 26 | decorator==5.1.1 27 | defusedxml==0.7.1 28 | dill==0.3.7 29 | distro==1.9.0 30 | einops==0.7.0 31 | executing==1.2.0 32 | fastjsonschema==2.16.3 33 | filelock==3.12.0 34 | fonttools==4.39.4 35 | fqdn==1.5.1 36 | frozenlist==1.3.3 37 | fsspec==2023.10.0 38 | h11==0.14.0 39 | httpcore==1.0.4 40 | httpx==0.27.0 41 | huggingface-hub==0.20.3 42 | idna==3.4 43 | imageio==2.29.0 44 | importlib-metadata==6.6.0 45 | importlib-resources==5.12.0 46 | IProgress==0.4 47 | ipykernel==6.23.1 48 | ipython==8.12.2 49 | ipywidgets==8.1.1 50 | isoduration==20.11.0 51 | jedi==0.18.2 52 | Jinja2==3.1.2 53 | joblib==1.3.2 54 | json5==0.9.14 55 | jsonpointer==2.3 56 | jsonschema==4.17.3 57 | jupyter-events==0.6.3 58 | jupyter-lsp==2.1.0 59 | jupyter_client==8.2.0 60 | jupyter_core==5.3.0 61 | jupyter_server==2.5.0 62 | jupyter_server_terminals==0.4.4 63 | jupyterlab==4.0.0 64 | jupyterlab-pygments==0.2.2 65 | jupyterlab-widgets==3.0.9 66 | jupyterlab_server==2.22.1 67 | kiwisolver==1.4.4 68 | MarkupSafe==2.1.2 69 | matplotlib==3.6.0 70 | matplotlib-inline==0.1.6 71 | mistune==2.0.5 72 | mpmath==1.3.0 73 | multidict==6.0.4 74 | multiprocess==0.70.15 75 | nbclient==0.7.4 76 | nbconvert==7.4.0 77 | nbformat==5.8.0 78 | nest-asyncio==1.5.6 79 | networkx==3.1 80 | nltk==3.8.1 81 | notebook_shim==0.2.3 82 | numpy==1.24.3 83 | openai==0.28.0 84 | packaging==23.1 85 | pandas==2.0.3 86 | pandocfilters==1.5.0 87 | parso==0.8.3 88 | peft==0.8.2 89 | pexpect==4.8.0 90 | pickleshare==0.7.5 91 | Pillow==9.5.0 92 | pkgutil_resolve_name==1.3.10 93 | platformdirs==3.5.1 94 | plotly==5.19.0 95 | prometheus-client==0.16.0 96 | prompt-toolkit==3.0.38 97 | protobuf==4.23.1 98 | psutil==5.9.5 99 | ptyprocess==0.7.0 100 | pure-eval==0.2.2 101 | pyarrow==15.0.0 102 | pyarrow-hotfix==0.6 103 | pycparser==2.21 104 | pydantic==2.6.2 105 | pydantic_core==2.16.3 106 | Pygments==2.15.1 107 | pyparsing==3.0.9 108 | pyrsistent==0.19.3 109 | python-dateutil==2.8.2 110 | python-json-logger==2.0.7 111 | pytz==2023.3 112 | PyYAML==6.0 113 | pyzmq==25.0.2 114 | regex==2023.12.25 115 | requests==2.30.0 116 | rfc3339-validator==0.1.4 117 | rfc3986-validator==0.1.1 118 | safetensors==0.4.2 119 | scikit-learn==1.3.2 120 | scipy==1.5.3 121 | seaborn==0.13.0 122 | Send2Trash==1.8.2 123 | sentence-transformers==2.5.1 124 | SimpleITK==2.2.1 125 | six==1.16.0 126 | sniffio==1.3.0 127 | soupsieve==2.4.1 128 | stack-data==0.6.2 129 | sympy==1.12 130 | tenacity==8.2.3 131 | terminado==0.17.1 132 | threadpoolctl==3.2.0 133 | tiktoken==0.5.2 134 | tinycss2==1.2.1 135 | tokenizers==0.15.1 136 | tomli==2.0.1 137 | torch @ https://developer.download.nvidia.com/compute/redist/jp/v51/pytorch/torch-2.0.0a0+8aa34602.nv23.03-cp38-cp38-linux_aarch64.whl#sha256=d7e5f1b23d443ce3ee306d2eedc8bb5773cca64f762925d098c1cbceca699643 138 | torchsummary==1.5.1 139 | torchvision==0.15.1a0+42759b1 140 | tornado==6.3.2 141 | tqdm==4.66.1 142 | traitlets==5.9.0 143 | transformers==4.37.2 144 | typing_extensions==4.9.0 145 | tzdata==2023.3 146 | uri-template==1.2.0 147 | urllib3==2.0.2 148 | wcwidth==0.2.6 149 | webcolors==1.13 150 | webencodings==0.5.1 151 | websocket-client==1.5.1 152 | widgetsnbextension==4.0.9 153 | xxhash==3.4.1 154 | yarl==1.9.2 155 | zipp==3.15.0 156 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /vector_indexer.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | ''' 3 | ------------------------------------------------------------------------------ 4 | Copyright 2024 Murali Kashaboina 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | ------------------------------------------------------------------------------ 18 | ''' 19 | 20 | 21 | import warnings 22 | 23 | warnings.simplefilter("ignore") 24 | 25 | from tqdm.autonotebook import tqdm 26 | 27 | import torch 28 | 29 | from kohonen_som import KohonenSOM 30 | 31 | from typing import List 32 | 33 | 34 | class SOMBasedVectorIndexer(): 35 | def __init__( 36 | self, 37 | vector_dimensions : int, 38 | som_lattice_height : int = 20, 39 | som_lattice_width : int = 30, 40 | learning_rate : float = 0.3, 41 | neighborhood_radius : float = None, 42 | topk_bmu_for_indexing : int = 1, 43 | device : str = None 44 | ): 45 | self.topk_bmu_for_indexing = int( topk_bmu_for_indexing ) 46 | 47 | self.som = KohonenSOM( 48 | vector_dimensions, 49 | som_lattice_height = som_lattice_height, 50 | som_lattice_width = som_lattice_width, 51 | learning_rate = learning_rate, 52 | neighborhood_radius = neighborhood_radius, 53 | device = device 54 | ) 55 | 56 | self.generated_indexes = False 57 | 58 | self.som_node_idx_map = {} 59 | 60 | def train_n_gen_indexes( 61 | self, input_vectors : torch.Tensor, 62 | train_epochs : int = 100 63 | ): 64 | if self.generated_indexes: 65 | print( "WARNING: Indexes were already generated. Ignoring the request..." ) 66 | return 67 | 68 | 69 | self.som.train( input_vectors, train_epochs ) 70 | 71 | topk_bmu_indexes = self.som.find_topk_best_matching_units( input_vectors, topk = self.topk_bmu_for_indexing ) 72 | 73 | for idx in tqdm( range( len( topk_bmu_indexes ) ), desc="SOM-Based Indexed Vectors" ): 74 | bmu_indexes = topk_bmu_indexes[ idx ] 75 | 76 | for bmu_index in bmu_indexes: 77 | bmu_index_key = tuple( bmu_index ) 78 | 79 | idx_set = self.som_node_idx_map.get( bmu_index_key, set() ) 80 | 81 | idx_set.add( idx ) 82 | 83 | self.som_node_idx_map[ bmu_index_key ] = idx_set 84 | 85 | self.generated_indexes = True 86 | 87 | def find_nearest_indexes( self, input_vectors : torch.Tensor ) -> List[ List[ int ] ]: 88 | topk_bmu_indexes = self.som.find_topk_best_matching_units( input_vectors, topk = self.topk_bmu_for_indexing ) 89 | 90 | nearest_indexes = [] 91 | 92 | for idx in range( len( topk_bmu_indexes ) ): 93 | nearest_idx = set() 94 | 95 | bmu_indexes = topk_bmu_indexes[ idx ] 96 | 97 | for bmu_index in bmu_indexes: 98 | bmu_index_key = tuple( bmu_index ) 99 | 100 | neighbor_idx_set = self.som_node_idx_map.get( bmu_index_key, set() ) 101 | 102 | nearest_idx = nearest_idx.union( neighbor_idx_set ) 103 | 104 | nearest_idx = list( nearest_idx ) 105 | 106 | nearest_idx.sort() 107 | 108 | nearest_indexes.append( nearest_idx ) 109 | 110 | return nearest_indexes -------------------------------------------------------------------------------- /wiki_datasource.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | ''' 3 | ------------------------------------------------------------------------------ 4 | Copyright 2024 Murali Kashaboina 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | ------------------------------------------------------------------------------ 18 | ''' 19 | 20 | import requests 21 | import pandas as pd 22 | from dateutil.parser import parse 23 | from typing import List 24 | 25 | 26 | class WikiEventsDataSource(): 27 | def __init__( 28 | self, 29 | event_years_to_fetch : List[int] 30 | ): 31 | if event_years_to_fetch == None or len( event_years_to_fetch ) == 0: 32 | raise ValueError( "Argumemt event_years_to_fetch is required. Specified value is None or empty." ) 33 | 34 | self.event_years_to_fetch = [ int(year) for year in event_years_to_fetch ] 35 | 36 | self.event_years_to_fetch = [ str(year) for year in self.event_years_to_fetch ] 37 | 38 | self.fetched = False 39 | 40 | self.df = None 41 | 42 | def get_data( self ) -> pd.DataFrame : 43 | return self.df 44 | 45 | def fetch_n_prepare_data( self ): 46 | if self.fetched: 47 | print( "WARNING: Wiki events for the specified years already fetched. Ignoring the request..." ) 48 | return 49 | 50 | main_df = pd.DataFrame() 51 | 52 | for year in self.event_years_to_fetch: 53 | wiki_api_params = { 54 | "action": "query", 55 | "prop": "extracts", 56 | "exlimit": 1, 57 | "titles": year, 58 | "explaintext": 1, 59 | "formatversion": 2, 60 | "format": "json" 61 | } 62 | 63 | response = requests.get( "https://en.wikipedia.org/w/api.php", params=wiki_api_params ) 64 | 65 | response_dict = response.json() 66 | 67 | df = pd.DataFrame() 68 | 69 | df[ "text" ] = response_dict["query"]["pages"][0]["extract"].split("\n") 70 | 71 | df = self.__clean_df__( df, year ) 72 | 73 | main_df = pd.concat( [ main_df, df ] ) 74 | 75 | self.df = main_df.reset_index(drop=True) 76 | 77 | self.fetched = True 78 | 79 | def __clean_df__( self, df : pd.DataFrame, year : str ) -> pd.DataFrame : 80 | #Filter off blank text and other header text 81 | df = df[ (df[ "text" ].str.len() > 0) & (~df[ "text" ].str.startswith( "==" )) ] 82 | 83 | prefix = "" 84 | 85 | #Iterate through rows of the dataframe and format events that are listed under the date of their occurrence. 86 | for (i, row) in df.iterrows(): 87 | #Only check for the events for which the date is not already prefixed, separated by " – " 88 | if " – " not in row["text"]: 89 | try: 90 | # Check if the row text is actually the date (date header row). The parse function call will pass if it is a valid date such as August 29 91 | parse(row["text"]) 92 | 93 | # If the parse function call is successful, then the row text is a date and hence can be used as a prefix for the following rows that are not formatted with an " – " 94 | prefix = row["text"] 95 | except: 96 | # Since the parse function call threw an exception, it means the row text is not a date and must be the event text without a date prefix. Hence, prepend the date prefix captured in the previous loop. 97 | row["text"] = prefix + " – " + row["text"] 98 | 99 | #Local date functions to filter rows using parse date logic 100 | def startswith_date( evt : str, sep='–' ): 101 | dt_str = evt.split( sep )[0] 102 | try: 103 | parse( dt_str ) 104 | return True 105 | except: 106 | return False 107 | 108 | def dateOnlyText( dt_str : str ): 109 | try: 110 | parse( dt_str ) 111 | return True 112 | except: 113 | return False 114 | 115 | #Select only the rows that contain the date-prefixed event texts - essentially remove the rows with pure dates since we do not need them anymore, and reset the index of the dataframe 116 | df = df[ df[ "text" ].apply( lambda evt: not dateOnlyText( evt ) and startswith_date( evt ) ) ].reset_index(drop=True) 117 | 118 | #Iterate through rows of the dataframe and format date to append year. 119 | for (i, row) in df.iterrows(): 120 | evt = row["text"] 121 | 122 | splits = evt.split( '–' ) 123 | 124 | dt_str = splits[0].strip() 125 | 126 | #Example: Need length for something like "January 15 – " 127 | first_toks_len = len( dt_str ) + 3 128 | 129 | remainder_str = evt[first_toks_len:].strip() 130 | 131 | row["text"] = "".join( [ dt_str, ", ", year, " – ", remainder_str ]) 132 | 133 | return df -------------------------------------------------------------------------------- /qa_chatbot.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | ''' 3 | ------------------------------------------------------------------------------ 4 | Copyright 2024 Murali Kashaboina 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | ------------------------------------------------------------------------------ 18 | ''' 19 | 20 | 21 | from abc import ABC, abstractmethod 22 | import torch 23 | import math 24 | 25 | class QuestionAnswerChatBot( ABC ): 26 | def __init__( 27 | self, 28 | vector_db_util = None, 29 | question_input_max_token_count : int = 768, 30 | context_trim_percent :float = 0.05, 31 | device : str = None 32 | ): 33 | if vector_db_util == None: 34 | raise ValueError( "ERROR: Required vector_db_util is not specified" ) 35 | 36 | self.vector_db_util = vector_db_util 37 | 38 | self.question_input_max_token_count = int( question_input_max_token_count ) 39 | 40 | self.context_trim_percent = float( context_trim_percent ) 41 | 42 | if device == None: 43 | self.device = torch.device( 'cuda' if torch.cuda.is_available() else 'cpu' ) 44 | else: 45 | self.device = torch.device( device ) 46 | 47 | def find_answer_to_question( self, question : str, sim_threshold = 0.68, max_new_tokens : int = 5 ): 48 | if question == None or len( question.strip() ) == 0: 49 | raise ValueError( "ERROR: Required question is not specified" ) 50 | 51 | sim_threshold = float( sim_threshold ) 52 | 53 | max_new_tokens = int( max_new_tokens ) 54 | 55 | qa_instruction = self.get_qa_instruction( question, sim_threshold = sim_threshold ) 56 | 57 | answer_text = self.__get_answer_text__( qa_instruction, max_new_tokens = max_new_tokens ) 58 | 59 | answer_text = self.__clean_answer_text__( qa_instruction, answer_text ) 60 | 61 | return answer_text 62 | 63 | def find_answer_to_question_without_context( self, question : str, max_new_tokens : int = 5 ): 64 | if question == None or len( question.strip() ) == 0: 65 | raise ValueError( "ERROR: Required question is not specified" ) 66 | 67 | max_new_tokens = int( max_new_tokens ) 68 | 69 | qa_template = self.__qa_template__() 70 | 71 | qa_instruction = qa_template.format( "", question ) 72 | 73 | answer_text = self.__get_answer_text__( qa_instruction, max_new_tokens = max_new_tokens ) 74 | 75 | answer_text = self.__clean_answer_text__( qa_instruction, answer_text ) 76 | 77 | return answer_text 78 | 79 | 80 | def get_qa_instruction( self, question : str, sim_threshold = 0.68 ) -> str : 81 | if question == None or len( question.strip() ) == 0: 82 | raise ValueError( "ERROR: Required question is not specified" ) 83 | 84 | sim_threshold = float( sim_threshold ) 85 | 86 | question = question.strip() 87 | 88 | qa_template = self.__qa_template__() 89 | 90 | semantic_sim_texts = self.vector_db_util.find_semantically_similar_data( question, sim_threshold = sim_threshold ) 91 | 92 | if len( semantic_sim_texts ) == 0: 93 | no_context = "No context is found" 94 | qa_instruction = qa_template.format( no_context, question ) 95 | return qa_instruction 96 | 97 | context_texts = [] 98 | 99 | for sim_text in semantic_sim_texts: 100 | context = sim_text[ "text" ] 101 | context = context.strip() 102 | context_texts.append( context ) 103 | 104 | context = " ".join( context_texts ) 105 | 106 | qa_instruction = "" 107 | 108 | while True: 109 | qa_instruction = qa_template.format( context, question ) 110 | 111 | tok_count = self.__token_count__( qa_instruction ) 112 | 113 | if tok_count <= self.question_input_max_token_count: 114 | break 115 | else: 116 | if len( context ) == 0: 117 | no_context = "No context is found" 118 | qa_instruction = qa_template.format( no_context, question ) 119 | break 120 | 121 | trim_len = math.floor( len(context) * self.context_trim_percent ) 122 | 123 | trimmed_len = len(context) - trim_len 124 | 125 | if trim_len > 0: 126 | context = context[ :trimmed_len ] 127 | else: 128 | context = "" 129 | 130 | return qa_instruction 131 | 132 | @abstractmethod 133 | def __get_answer_text__( self, qa_instruction : str, max_new_tokens : int = 5 ) -> str : 134 | pass 135 | 136 | @abstractmethod 137 | def __token_count__( self, text : str ): 138 | pass 139 | 140 | def __clean_answer_text__( self, qa_instruction : str, answer_text : str ) -> str : 141 | if qa_instruction in answer_text: 142 | index = answer_text.index( qa_instruction ) 143 | 144 | index = index + len( qa_instruction ) 145 | 146 | answer_text = answer_text[ index+1: ] 147 | 148 | extra_answer_token = "\nAnswer" 149 | 150 | if extra_answer_token in answer_text: 151 | extra_token_len = len( extra_answer_token ) 152 | 153 | index = answer_text.index( extra_answer_token ) 154 | 155 | answer_text = answer_text[ :index ] + answer_text[ index+extra_token_len: ] 156 | 157 | answer_text = answer_text.strip() 158 | 159 | return answer_text 160 | 161 | def __qa_template__( self ): 162 | qa_template = """Context: 163 | 164 | {} 165 | 166 | --- 167 | 168 | Question: {} 169 | Answer:""" 170 | return qa_template -------------------------------------------------------------------------------- /kohonen_som.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | ''' 3 | ------------------------------------------------------------------------------ 4 | Copyright 2024 Murali Kashaboina 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | ------------------------------------------------------------------------------ 18 | ''' 19 | 20 | import warnings 21 | 22 | warnings.simplefilter("ignore") 23 | 24 | import torch 25 | import torch.nn as nn 26 | 27 | from tqdm.autonotebook import tqdm 28 | 29 | from typing import List 30 | 31 | class KohonenSOM(): 32 | """ 33 | The code is developed based on the following article: 34 | http://www.ai-junkie.com/ann/som/som1.html 35 | 36 | The vector and matrix operations are developed using PyTorch Tensors. 37 | """ 38 | def __init__( 39 | self, 40 | input_dimensions : int, 41 | som_lattice_height : int = 20, 42 | som_lattice_width : int = 20, 43 | learning_rate : float = 0.3, 44 | neighborhood_radius : float = None, 45 | device : str = None 46 | ): 47 | 48 | self.input_dimensions = int( input_dimensions ) 49 | 50 | self.som_lattice_height = int( som_lattice_height ) 51 | 52 | self.som_lattice_width = int( som_lattice_width ) 53 | 54 | if learning_rate == None: 55 | self.learning_rate = 0.3 56 | else: 57 | self.learning_rate = float( learning_rate ) 58 | 59 | if neighborhood_radius == None: 60 | self.neighborhood_radius = max( self.som_lattice_height, self.som_lattice_width ) / 2.0 61 | else: 62 | self.neighborhood_radius = float( neighborhood_radius ) 63 | 64 | if device == None: 65 | self.device = torch.device( 'cuda' if torch.cuda.is_available() else 'cpu' ) 66 | else: 67 | self.device = torch.device( device ) 68 | 69 | def dist_eval( data_points, weights ): 70 | distances = torch.cdist( data_points, weights, p=2 ) 71 | return distances 72 | 73 | self.dist_evaluator = dist_eval 74 | 75 | self.total_lattice_nodes = self.som_lattice_height * self.som_lattice_width 76 | 77 | self.lattice_node_weights = torch.randn( self.total_lattice_nodes, self.input_dimensions, device=self.device ) 78 | 79 | lattice_coordinates = torch.tensor( [ [[i,j] for j in range(self.som_lattice_width)] for i in range( self.som_lattice_height ) ], dtype=torch.int ) 80 | 81 | self.lattice_coordinates = lattice_coordinates.view( self.total_lattice_nodes, 2 ) 82 | 83 | self.trained = False 84 | 85 | #self.dist_evaluator = nn.PairwiseDistance(p=2) 86 | 87 | def train( self, data_points : torch.Tensor, train_epochs : int = 100 ): 88 | if self.trained: 89 | print( "WARNING: Model is already trained. Ignoring the request..." ) 90 | return 91 | 92 | train_epochs = int( train_epochs ) 93 | 94 | total_dpoints = data_points.shape[0] 95 | 96 | data_points = data_points.to( self.device ) 97 | 98 | for epoch in tqdm( range( train_epochs ), desc="Kohonen's SOM Train Epochs" ): 99 | decay_factor = 1.0 - (epoch/train_epochs) 100 | 101 | #learning rate is alpha in the paper 102 | adjusted_lr = self.learning_rate * decay_factor 103 | 104 | #sigma in the paper 105 | adjusted_lattice_node_radius = self.neighborhood_radius * decay_factor 106 | 107 | #sigma square in the paper 108 | squared_adjusted_lattice_node_radius = adjusted_lattice_node_radius**2 109 | 110 | distances = self.dist_evaluator( data_points, self.lattice_node_weights ) 111 | 112 | best_matching_units = torch.argmin( distances, dim=1 ) 113 | 114 | for i in range( total_dpoints ): 115 | data_point = data_points[i] 116 | 117 | bmu_index = best_matching_units[i].item() 118 | 119 | bmu_coordinates = self.lattice_coordinates[ bmu_index ] 120 | 121 | #squared distances of the lattice nodes from the bmu :: dist^2 from equation 6 shown in the paper 122 | squared_lattice_node_radii_from_bmu = torch.sum( torch.pow( self.lattice_coordinates.float() - bmu_coordinates.float(), 2), dim=1) 123 | 124 | squared_lattice_node_radii_from_bmu = squared_lattice_node_radii_from_bmu.to( self.device ) 125 | 126 | #adjust function phi in the paper 127 | lattice_node_weight_adj_factors = torch.exp( -0.5 * squared_lattice_node_radii_from_bmu / squared_adjusted_lattice_node_radius ) 128 | 129 | lattice_node_weight_adj_factors = lattice_node_weight_adj_factors.to( self.device ) 130 | 131 | final_lattice_node_weight_adj_factors = adjusted_lr * lattice_node_weight_adj_factors 132 | 133 | final_lattice_node_weight_adj_factors = final_lattice_node_weight_adj_factors.view( self.total_lattice_nodes, 1 ) 134 | 135 | final_lattice_node_weight_adj_factors = final_lattice_node_weight_adj_factors.to( self.device ) 136 | 137 | lattice_node_weight_adjustments = torch.mul( final_lattice_node_weight_adj_factors, (data_point - self.lattice_node_weights) ) 138 | 139 | self.lattice_node_weights = self.lattice_node_weights + lattice_node_weight_adjustments 140 | 141 | self.lattice_node_weights = self.lattice_node_weights.to( self.device ) 142 | 143 | self.trained = True 144 | 145 | def find_best_matching_unit( self, data_points : torch.Tensor ) -> List[ List[ int ] ] : 146 | if len( data_points.size() ) == 1: 147 | #batching 148 | data_points = data_points.view( 1, data_points.shape[0] ) 149 | 150 | distances = self.dist_evaluator( data_points, self.lattice_node_weights ) 151 | 152 | best_matching_unit_indexes = torch.argmin( distances, dim=1 ) 153 | 154 | best_matching_units = [ self.lattice_coordinates[ bmu_index.item() ].tolist() for bmu_index in best_matching_unit_indexes ] 155 | 156 | return best_matching_units 157 | 158 | def find_topk_best_matching_units( self, data_points : torch.Tensor, topk : int = 1 ) -> List[ List[ int ] ] : 159 | if len( data_points.size() ) == 1: 160 | #batching 161 | data_points = data_points.view( 1, data_points.shape[0] ) 162 | 163 | topk = int( topk ) 164 | 165 | distances = self.dist_evaluator( data_points, self.lattice_node_weights ) 166 | 167 | topk_best_matching_unit_indexes = torch.topk( distances, topk, dim=1, largest=False ).indices 168 | 169 | topk_best_matching_units = [] 170 | 171 | for i in range( data_points.shape[0] ): 172 | best_matching_unit_indexes = topk_best_matching_unit_indexes[i] 173 | 174 | best_matching_units = [ self.lattice_coordinates[ bmu_index.item() ].tolist() for bmu_index in best_matching_unit_indexes ] 175 | 176 | topk_best_matching_units.append( best_matching_units ) 177 | 178 | return topk_best_matching_units -------------------------------------------------------------------------------- /som_based_rag.py: -------------------------------------------------------------------------------- 1 | # coding: utf-8 2 | ''' 3 | ------------------------------------------------------------------------------ 4 | Copyright 2024 Murali Kashaboina 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | ------------------------------------------------------------------------------ 18 | ''' 19 | 20 | import warnings 21 | 22 | warnings.simplefilter("ignore") 23 | 24 | from tqdm.autonotebook import tqdm 25 | 26 | import pandas as pd 27 | import torch 28 | import torch.nn as nn 29 | 30 | from vector_encoder_parent import VectorEncoder 31 | 32 | from vector_indexer import SOMBasedVectorIndexer 33 | 34 | 35 | class SOM_Based_RAG_Util(): 36 | def __init__( 37 | self, 38 | vector_encoder : VectorEncoder, 39 | som_lattice_height : int = 20, 40 | som_lattice_width : int = 30, 41 | learning_rate : float = 0.3, 42 | neighborhood_radius : float = None, 43 | topk_bmu_for_indexing : int = 1, 44 | vectorize_batch_size : int = 100, 45 | device : str = None 46 | ): 47 | if vector_encoder == None: 48 | raise ValueError( "ERROR: vector_encoder must be specified" ) 49 | 50 | self.vector_encoder = vector_encoder 51 | 52 | self.vectorize_batch_size = int( vectorize_batch_size ) 53 | 54 | if device == None: 55 | self.device = torch.device( 'cuda' if torch.cuda.is_available() else 'cpu' ) 56 | else: 57 | self.device = torch.device( device ) 58 | 59 | self.vector_indexer = SOMBasedVectorIndexer( 60 | self.vector_encoder.get_encoded_vector_dimensions(), 61 | som_lattice_height = som_lattice_height, 62 | som_lattice_width = som_lattice_width, 63 | learning_rate = learning_rate, 64 | neighborhood_radius = neighborhood_radius, 65 | topk_bmu_for_indexing = topk_bmu_for_indexing, 66 | device = self.device 67 | ) 68 | 69 | self.data_loaded_n_vectorized = False 70 | 71 | self.data_vectors_indexed = False 72 | 73 | self.df = None 74 | 75 | self.vectors = None 76 | 77 | def find_semantically_similar_data( self, query: str, sim_evaluator = None, sim_threshold : float = 0.8 ): 78 | if not self.data_vectors_indexed: 79 | raise ValueError( "ERROR: Data vectors not indexed." ) 80 | 81 | if query == None or len( query.strip() ) == 0: 82 | raise ValueError( "ERROR: Required query text is not specified." ) 83 | 84 | sim_threshold = float( sim_threshold ) 85 | 86 | if sim_evaluator == None: 87 | sim_evaluator = nn.CosineSimilarity(dim=0, eps=1e-6) 88 | 89 | query_vector = self.vector_encoder.encode( query ) 90 | 91 | query_vector = query_vector.view( self.vector_encoder.get_encoded_vector_dimensions() ) 92 | 93 | query_vector = query_vector.to( self.device ) 94 | 95 | nearest_indexes = self.vector_indexer.find_nearest_indexes( query_vector ) 96 | 97 | nearest_indexes = nearest_indexes[0] 98 | 99 | sim_scores = [] 100 | 101 | for idx in nearest_indexes: 102 | data_vector = self.vectors[ idx ] 103 | 104 | data_vector = data_vector.view( self.vector_encoder.get_encoded_vector_dimensions() ) 105 | 106 | sim_score = sim_evaluator( query_vector, data_vector ) 107 | 108 | if sim_score >= sim_threshold: 109 | sim_score_tuple = (idx, sim_score.item() ) 110 | 111 | sim_scores.append( sim_score_tuple ) 112 | 113 | sim_scores.sort( key = lambda x: x[1], reverse=True ) 114 | 115 | semantically_similar_data = [ 116 | { 117 | 'text': self.df[ 'text' ][ idx ], 118 | 'sim_score' : sim_score 119 | } for idx, sim_score in sim_scores 120 | ] 121 | 122 | return semantically_similar_data 123 | 124 | def find_semantically_similar_data_idx( self, query: str, sim_evaluator = None, sim_threshold : float = 0.8 ): 125 | if not self.data_vectors_indexed: 126 | raise ValueError( "ERROR: Data vectors not indexed." ) 127 | 128 | if query == None or len( query.strip() ) == 0: 129 | raise ValueError( "ERROR: Required query text is not specified." ) 130 | 131 | sim_threshold = float( sim_threshold ) 132 | 133 | if sim_evaluator == None: 134 | sim_evaluator = nn.CosineSimilarity(dim=0, eps=1e-6) 135 | 136 | query_vector = self.vector_encoder.encode( query ) 137 | 138 | query_vector = query_vector.view( self.vector_encoder.get_encoded_vector_dimensions() ) 139 | 140 | query_vector = query_vector.to( self.device ) 141 | 142 | nearest_indexes = self.vector_indexer.find_nearest_indexes( query_vector ) 143 | 144 | nearest_indexes = nearest_indexes[0] 145 | 146 | sim_scores = [] 147 | 148 | for idx in nearest_indexes: 149 | data_vector = self.vectors[ idx ] 150 | 151 | data_vector = data_vector.view( self.vector_encoder.get_encoded_vector_dimensions() ) 152 | 153 | sim_score = sim_evaluator( query_vector, data_vector ) 154 | 155 | if sim_score >= sim_threshold: 156 | sim_score_tuple = (idx, sim_score.item() ) 157 | 158 | sim_scores.append( sim_score_tuple ) 159 | 160 | sim_scores.sort( key = lambda x: x[1], reverse=True ) 161 | 162 | return sim_scores 163 | 164 | def load_n_vectorize_data( self, data_source ): 165 | if self.data_loaded_n_vectorized: 166 | print( "WARNING: Data already loaded and vectorized. Ignoring the request..." ) 167 | return 168 | 169 | data_source.fetch_n_prepare_data() 170 | 171 | self.df = data_source.get_data() 172 | 173 | vectors = None 174 | 175 | for i in tqdm( range(0, len(self.df), self.vectorize_batch_size ), desc="Vectorized Data Batch" ): 176 | list_of_text = self.df.iloc[ i:i+self.vectorize_batch_size ]["text"].tolist() 177 | 178 | batch_encoded_vectors = self.vector_encoder.encode_batch( list_of_text ) 179 | 180 | if vectors == None: 181 | vectors = batch_encoded_vectors 182 | else: 183 | vectors = torch.cat( [ vectors, batch_encoded_vectors], dim=0 ) 184 | 185 | self.vectors = vectors.to( self.device ) 186 | 187 | self.data_loaded_n_vectorized = True 188 | 189 | def train_n_index_data_vectors( self, train_epochs : int = 100 ): 190 | if not self.data_loaded_n_vectorized: 191 | raise ValueError( "ERROR: Data not loaded and vectorized." ) 192 | 193 | if self.data_vectors_indexed: 194 | print( "WARNING: Data vectors already indexed. Ignoring the request..." ) 195 | return 196 | 197 | self.vector_indexer.train_n_gen_indexes( self.vectors, train_epochs ) 198 | 199 | self.data_vectors_indexed = True 200 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /OpenAI_Based_SOM_GPT2_Bot.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "raw", 5 | "id": "731e517c-7bc7-4499-9fe8-00f1599f42f0", 6 | "metadata": {}, 7 | "source": [ 8 | "'''\n", 9 | "------------------------------------------------------------------------------\n", 10 | " Copyright 2024 Murali Kashaboina\n", 11 | "\n", 12 | " Licensed under the Apache License, Version 2.0 (the \"License\");\n", 13 | " you may not use this file except in compliance with the License.\n", 14 | " You may obtain a copy of the License at\n", 15 | "\n", 16 | " http://www.apache.org/licenses/LICENSE-2.0\n", 17 | "\n", 18 | " Unless required by applicable law or agreed to in writing, software\n", 19 | " distributed under the License is distributed on an \"AS IS\" BASIS,\n", 20 | " WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n", 21 | " See the License for the specific language governing permissions and\n", 22 | " limitations under the License.\n", 23 | "------------------------------------------------------------------------------\n", 24 | "'''" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": 1, 30 | "id": "db98a99a-85f3-4312-b038-5f64c254101f", 31 | "metadata": {}, 32 | "outputs": [], 33 | "source": [ 34 | "import warnings\n", 35 | "\n", 36 | "warnings.simplefilter(\"ignore\")\n", 37 | "\n", 38 | "import torch\n", 39 | "\n", 40 | "from som_based_rag import SOM_Based_RAG_Util\n", 41 | "\n", 42 | "from wiki_datasource import WikiEventsDataSource\n", 43 | "\n", 44 | "from openai_vector_encoder import OpenAIEmbeddingsVectorEncoder\n", 45 | "\n", 46 | "from openai_qa_chatbot import OpenAIQuestionAnswerChatBot" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 2, 52 | "id": "d655453b-0e4f-4216-8987-7e9f5f72f8b9", 53 | "metadata": {}, 54 | "outputs": [], 55 | "source": [ 56 | "device = 'cuda' if torch.cuda.is_available() else 'cpu'" 57 | ] 58 | }, 59 | { 60 | "cell_type": "code", 61 | "execution_count": 3, 62 | "id": "3bc95728-72f5-4c19-a9e5-091d402ea0c1", 63 | "metadata": {}, 64 | "outputs": [], 65 | "source": [ 66 | "openai_key = \"YOUR KEY GOES HERE\"\n", 67 | "\n", 68 | "openai_vector_encoder_id = \"text-embedding-ada-002\"\n", 69 | "\n", 70 | "openai_encoded_vector_dimensions = 1536\n", 71 | "\n", 72 | "openai_tokenizer_name = \"cl100k_base\" \n", 73 | "\n", 74 | "openai_model_name = \"gpt-3.5-turbo-instruct\"\n", 75 | "\n", 76 | "vector_encoder = OpenAIEmbeddingsVectorEncoder( openai_encoded_vector_dimensions, openai_vector_encoder_id, openai_key )" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": 4, 82 | "id": "df6c5da9-c735-4de4-9dcd-cc5acff04125", 83 | "metadata": {}, 84 | "outputs": [], 85 | "source": [ 86 | "event_years_to_fetch = [ 2022, 2023, 2024 ]\n", 87 | "data_source = WikiEventsDataSource( event_years_to_fetch )" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": 5, 93 | "id": "50a977b7-28d3-4cc0-8461-072aa7e3f123", 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "som_driven_rag_util = SOM_Based_RAG_Util( \n", 98 | " vector_encoder = vector_encoder,\n", 99 | " som_lattice_height = 20,\n", 100 | " som_lattice_width = 30,\n", 101 | " learning_rate = 0.3,\n", 102 | " topk_bmu_for_indexing = 10,\n", 103 | " device = device\n", 104 | " )" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": 6, 110 | "id": "4d466bc1-882b-46b6-9d0f-d5e480344fb9", 111 | "metadata": {}, 112 | "outputs": [ 113 | { 114 | "data": { 115 | "application/vnd.jupyter.widget-view+json": { 116 | "model_id": "abeeae6b33394bf09d91731ac229b9bf", 117 | "version_major": 2, 118 | "version_minor": 0 119 | }, 120 | "text/plain": [ 121 | "Vectorized Data Batch: 0%| | 0/5 [00:00