├── .env.sample ├── .gitattributes ├── .gitignore ├── LICENSE ├── README.md ├── chat.py ├── main.py ├── requirements.txt └── src └── scraper.py /.env.sample: -------------------------------------------------------------------------------- 1 | # Scraper config 2 | FILES_TO_IGNORE='"package-lock.json", "LICENSE", ".gitattributes", ".gitignore", "yarn.lock"' 3 | SAVE_PATH="./repos_content" # Save the scraped data in a directory called repos-content in the root 4 | MAX_ATTEMPTS=3 5 | 6 | # Repository to scrape 7 | REPO_URL="https://github.com/soos3d/chatgpt-plugin-development-quickstart-express" 8 | 9 | # OpenAI 10 | OPENAI_API_KEY="YOUR_KEY" 11 | EMBEDDINGS_MODEL="text-embedding-ada-002" 12 | LANGUAGE_MODEL="gpt-3.5-turbo" # gpt-4 13 | 14 | # Deeplake vector DB 15 | ACTIVELOOP_TOKEN="YOUR_KEY" 16 | DATASET_PATH="./local_vector_db" # "hub://USER_ID/custom_dataset" # Edit with your user id if you want to use the cloud db. -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Local vector db 2 | local_vector_db/ 3 | chat-repo/ 4 | 5 | # Byte-compiled / optimized / DLL files 6 | __pycache__/ 7 | *.py[cod] 8 | *$py.class 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Distribution / packaging 14 | .Python 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | share/python-wheels/ 28 | *.egg-info/ 29 | .installed.cfg 30 | *.egg 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .nox/ 47 | .coverage 48 | .coverage.* 49 | .cache 50 | nosetests.xml 51 | coverage.xml 52 | *.cover 53 | *.py,cover 54 | .hypothesis/ 55 | .pytest_cache/ 56 | cover/ 57 | 58 | # Translations 59 | *.mo 60 | *.pot 61 | 62 | # Django stuff: 63 | *.log 64 | local_settings.py 65 | db.sqlite3 66 | db.sqlite3-journal 67 | 68 | # Flask stuff: 69 | instance/ 70 | .webassets-cache 71 | 72 | # Scrapy stuff: 73 | .scrapy 74 | 75 | # Sphinx documentation 76 | docs/_build/ 77 | 78 | # PyBuilder 79 | .pybuilder/ 80 | target/ 81 | 82 | # Jupyter Notebook 83 | .ipynb_checkpoints 84 | 85 | # IPython 86 | profile_default/ 87 | ipython_config.py 88 | 89 | # pyenv 90 | # For a library or package, you might want to ignore these files since the code is 91 | # intended to run in multiple environments; otherwise, check them in: 92 | # .python-version 93 | 94 | # pipenv 95 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 96 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 97 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 98 | # install all needed dependencies. 99 | #Pipfile.lock 100 | 101 | # poetry 102 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 103 | # This is especially recommended for binary packages to ensure reproducibility, and is more 104 | # commonly ignored for libraries. 105 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 106 | #poetry.lock 107 | 108 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 109 | __pypackages__/ 110 | 111 | # Celery stuff 112 | celerybeat-schedule 113 | celerybeat.pid 114 | 115 | # SageMath parsed files 116 | *.sage.py 117 | 118 | # Environments 119 | .env 120 | .venv 121 | env/ 122 | venv/ 123 | ENV/ 124 | env.bak/ 125 | venv.bak/ 126 | 127 | # Spyder project settings 128 | .spyderproject 129 | .spyproject 130 | 131 | # Rope project settings 132 | .ropeproject 133 | 134 | # mkdocs documentation 135 | /site 136 | 137 | # mypy 138 | .mypy_cache/ 139 | .dmypy.json 140 | dmypy.json 141 | 142 | # Pyre type checker 143 | .pyre/ 144 | 145 | # pytype static type analyzer 146 | .pytype/ 147 | 148 | # Cython debug symbols 149 | cython_debug/ 150 | 151 | # PyCharm 152 | # JetBrains specific template is maintainted in a separate JetBrains.gitignore that can 153 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 154 | # and can be added to the global gitignore or merged into this file. For a more nuclear 155 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 156 | #.idea/ 157 | -------------------------------------------------------------------------------- /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 | # Scrape and chat with repositories 2 | 3 | This project is designed to allow you to plug in a GitHub repository URL (like `https://github.com/soos3d/chatgpt-plugin-development-quickstart-express`) and then engage with OpenAI's Chat GPT models to gain a better understanding of the repository's codebase. 4 | 5 | To handle the 'AI' part, the program utilizes the [Langchain](https://python.langchain.com/en/latest/index.html) framework and [Deep Lake](https://docs.activeloop.ai/) following this logic: 6 | 7 | 1. The repository is scraped, and each file's content is saved in a `txt` format. 8 | 2. Langchain is used to load this data, break it down into chunks, and create embedding vectors using the OpenAI embedding model. 9 | 3. Langchain then helps to build a vector database using Deep Lake. 10 | 4. Lastly, Langchain spins up a chat bot with the help of a Chat GPT model. 11 | 12 | With this setup, you can interact with 'chat' with any repository. 13 | 14 | ## Table of contents 15 | 16 | - [Project structure](#project-structure) 17 | - [Requirements](#requirements) 18 | - [Getting Started](#getting-started) 19 | - [Use a cloud vector database](#use-a-cloud-vector-database) 20 | - [Configuration](#configuration) 21 | 22 | ## Project structure 23 | 24 | This project only has three files! Langchain really allows to simply the logic. 25 | 26 | ```sh 27 | chat-with-repo-langchain 28 | │ 29 | ├── main.py 30 | ├── chat.py 31 | ├── src 32 | │ └── scraper.py 33 | └── .env 34 | ``` 35 | 36 | - `main.py`: This is the entry point and the part responsible for ingesting a repository URL, generating embedding vectors, and indexing it in a vector database. 37 | - `chat.py`: This module starts the chat functionality, accepts user queries, and gets the context from the Vectore database; it also stores the chat history for the time it's running. 38 | - `src/scraper.py`: This file holds the scraping logic, and this module is called during the execution of `main.py`. 39 | - `.env`: This is where environment variables are stored; it also holds the configuration of the vector database. 40 | 41 | 42 | ## Requirements 43 | 44 | Before getting started, ensure you have the following: 45 | 46 | * [Python](https://www.python.org/downloads/) - Version 3.7 or newer is required. 47 | * An active account on OpenAI, along with an [OpenAI API key](https://platform.openai.com/account/api-keys). 48 | * A Deep Lake account, complete with a [Deep Lake API key](https://app.activeloop.ai/?utm_source=referral&utm_medium=platform&utm_campaign=signup_promo_settings&utm_id=plg). 49 | 50 | ## Getting Started 51 | 52 | > ℹ️ It's strongly advised to create a new Python virtual environment to run this program. It helps maintain a tidy workspace by keeping dependencies in one place. 53 | 54 | * Create a Python virtual environment with: 55 | 56 | ```sh 57 | python3 -m venv repo-ai 58 | ``` 59 | 60 | Then activate it with: 61 | 62 | ```sh 63 | source repo-ai/bin/activate 64 | ``` 65 | 66 | * Clone the repository: 67 | 68 | ```sh 69 | git clone https://github.com/soos3d/chat-with-repo-langchain-openai.git 70 | ``` 71 | Then: 72 | 73 | ```sh 74 | cd chat-with-repo-langchain-openai 75 | ``` 76 | 77 | * Install the Python dependencies: 78 | 79 | ```sh 80 | pip install -r requirements.txt 81 | ``` 82 | 83 | This will install all of the required Langchain, OpenAI, and Deep Lake dependencies. 84 | 85 | * Edit the `.env.sample` file with your information, specifically the API keys: 86 | 87 | ```env 88 | # Scraper config 89 | FILES_TO_IGNORE='"package-lock.json", "LICENSE", ".gitattributes", ".gitignore", "yarn.lock"' 90 | SAVE_PATH="./repos_content" # Save the scraped data in a directory called repos-content in the root 91 | MAX_ATTEMPTS=3 92 | 93 | # Repository to scrape if the hardcoded section is active. 94 | REPO_URL="https://github.com/soos3d/chatgpt-plugin-development-quickstart-express" 95 | 96 | # OpenAI 97 | OPENAI_API_KEY="YOUR_KEY" 98 | EMBEDDINGS_MODEL="text-embedding-ada-002" 99 | LANGUAGE_MODEL="gpt-3.5-turbo" # gpt-4 100 | 101 | # Deeplake vector DB 102 | ACTIVELOOP_TOKEN="YOUR_KEY" 103 | DATASET_PATH="./local_vector_db" # "hub://USER_ID/custom_dataset" # Edit with your user id if you want to use the cloud db. 104 | ``` 105 | 106 | Here is where you select which Chat GPT model to use; `gpt-3.5-turbo` it the default model, and the path to the cloud vector dataset if you don't want to store it locally; it is set up locally by default. 107 | 108 | * Run the `main.py` file: 109 | 110 | ```sh 111 | python3 main.py 112 | ``` 113 | 114 | * Input a repository URL 115 | 116 | ```sh 117 | Input the repository you want to index: https://github.com/soos3d/chatgpt-plugin-development-quickstart-express 118 | ``` 119 | 120 | This will scrape the repository, load the files, split it in chunks, generate embedding vectors, create a local vector database and store the embeddings. 121 | 122 | You will see the following response: 123 | 124 | ```sh 125 | Scraping the repository... 126 | 127 | ==================================================================================================== 128 | Repository contents written to ./repos_content/soos3d_chatgpt-plugin-development-quickstart-express. 129 | ==================================================================================================== 130 | List of file paths written to ./repos_content/soos3d_chatgpt-plugin-development-quickstart-express/soos3d_chatgpt-plugin-development-quickstart-express_file_paths.txt. 131 | 132 | Time needed to pull the data: 10.23s. 133 | ==================================================================================================== 134 | Loading docs... 135 | 88%|███████████████████████████████████████████████████████████████████████████████████████████▉ | 7/8 [00:01<00:00, 5.79it/s] 136 | Loaded 7 documents. 137 | ==================================================================================================== 138 | Splitting documents... 139 | Generated 25 chunks. 140 | ==================================================================================================== 141 | Creating vector DB... 142 | ./local_vector_db loaded successfully. 143 | Evaluating ingest: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:05<00:00 144 | Dataset(path='./local_vector_db', tensors=['embedding', 'ids', 'metadata', 'text']) 145 | 146 | tensor htype shape dtype compression 147 | ------- ------- ------- ------- ------- 148 | embedding generic (25, 1536) float32 None 149 | ids text (25, 1) str None 150 | metadata json (25, 1) str None 151 | text text (25, 1) str None 152 | Vector database updated. 153 | ``` 154 | 155 | * Chat with the repository: 156 | 157 | ```sh 158 | python3 chat.py 159 | ``` 160 | 161 | This will start the chat model and you can leverage it's full power, I recomend to use the GPT 4 model if possible. The followinf is an example response based on my [ChatGPT plugins boilerplate repository]() using the `gpt4` model: 162 | 163 | ```sh 164 | ./local_vector_db loaded successfully. 165 | 166 | Deep Lake Dataset in ./local_vector_db already exists, loading from the storage 167 | Dataset(path='./local_vector_db', read_only=True, tensors=['embedding', 'ids', 'metadata', 'text']) 168 | 169 | tensor htype shape dtype compression 170 | ------- ------- ------- ------- ------- 171 | embedding generic (25, 1536) float32 None 172 | ids text (25, 1) str None 173 | metadata json (25, 1) str None 174 | text text (25, 1) str None 175 | 176 | Please enter your question (or 'quit' to stop): Can you explain how the index.js file in the ChatpGTP plugin quickstart repo works? 177 | 178 | Question: Can you explain how the index.js file in the ChatpGTP plugin quickstart repo works? 179 | Answer: Certainly! The `index.js` file in the ChatGPT plugin quickstart repository serves as the entry point for the Express.js server application. Here's a breakdown of its functionality: 180 | 181 | 1. Import required modules: The necessary modules are imported, including `express`, `path`, `cors`, `fs`, and `body-parser`. Additionally, the custom module `getAirportData` is imported from `./src/app`. 182 | 183 | ```javascript 184 | const express = require('express'); 185 | const path = require('path'); 186 | const cors = require('cors'); 187 | const fs = require('fs'); 188 | const bodyParser = require('body-parser'); 189 | require('dotenv').config(); 190 | 191 | const { getAirportData } = require('./src/app'); 192 | ``` 193 | ``` 194 | 195 | 2. Initialize Express application: The Express application is initialized and stored in the `app` variable. 196 | 197 | ```javascript 198 | const app = express(); 199 | ``` 200 | 201 | 3. Set the port number: The port number is set based on the environment variable `PORT` or defaults to 3000 if `PORT` is not set. 202 | 203 | ```javascript 204 | const PORT = process.env.PORT || 3000; 205 | ``` 206 | 207 | 4. Configure Express to parse JSON: The application is configured to parse JSON in the body of incoming requests using `bodyParser.json()`. 208 | 209 | ```javascript 210 | app.use(bodyParser.json()); 211 | ``` 212 | 213 | 5. Configure CORS options: CORS (Cross-Origin Resource Sharing) is configured to allow requests from `https://chat.openai.com` and to send a 200 status code for successful preflight requests for compatibility with some older browsers. 214 | 215 | ```javascript 216 | const corsOptions = { 217 | origin: 'https://chat.openai.com', 218 | optionsSuccessStatus: 200 219 | }; 220 | 221 | app.use(cors(corsOptions)); 222 | ``` 223 | 224 | The rest of the `index.js` file sets up the server to listen on the specified port and handles the routes for the plugin. The server starts listening for incoming requests on the specified port, and the plugin is ready to be used with ChatGPT. 225 | 226 | Tokens Used: 2214 227 | Prompt Tokens: 1817 228 | Completion Tokens: 397 229 | Successful Requests: 1 230 | Total Cost (USD): $0.07833 231 | 232 | ``` 233 | > ℹ️ Note that it also prints how many tokens were used and an estimate cost for the OpenAI API. 234 | 235 | ## Use a cloud vector database 236 | 237 | By default this project creates a local vector database using [Deep Lake](https://app.activeloop.ai/?utm_source=referral&utm_medium=platform&utm_campaign=signup_promo_settings&utm_id=plg), but you can also use a cloud based DB. 238 | 239 | > Note that e local database will be faster. 240 | 241 | In `main.py` uncomment the following section: 242 | 243 | ```py 244 | # Enable the following to create a cloud vector DB using Deep Lake 245 | """ 246 | deeplake_path = os.getenv('DATASET_PATH') 247 | ds = deeplake.empty(deeplake_path) 248 | db = DeepLake(dataset_path=deeplake_path, embedding_function=embeddings, overwrite=True, public=True) 249 | """ 250 | ``` 251 | 252 | Remember to edit the environment variable for the dataset path and add the `USER_ID` you have in your [Deep Lake](https://app.activeloop.ai/?utm_source=referral&utm_medium=platform&utm_campaign=signup_promo_settings&utm_id=plg) account, and to remove or comment the code to create the local DB. 253 | 254 | ```env 255 | DATASET_PATH="hub://USER_ID/custom_dataset" # Edit with your user id if you want to use the cloud db. 256 | ``` 257 | 258 | ```py 259 | # Set the deeplake_path to the repository name 260 | deeplake_path = os.getenv('DATASET_PATH') 261 | db = DeepLake(dataset_path=deeplake_path, embedding_function=embeddings, overwrite=True) 262 | ``` 263 | 264 | ## Configuration 265 | 266 | The entire app is configured from the `.env` file so you don't have to actually change the code if you don't want to. 267 | 268 | * FILES_TO_IGNORE is a list of files that will not be scraped. This is to reduce clutter and save some resources. 269 | 270 | ```env 271 | # Scraper config 272 | FILES_TO_IGNORE='"package-lock.json", "LICENSE", ".gitattributes", ".gitignore", "yarn.lock"' 273 | SAVE_PATH="./repos_content" # Save the scraped data in a directory called repos-content in the root 274 | MAX_ATTEMPTS=3 275 | 276 | # Repository to scrape if the hardcoded section is active. 277 | REPO_URL="https://github.com/soos3d/chatgpt-plugin-development-quickstart-express" 278 | 279 | # OpenAI 280 | OPENAI_API_KEY="YOUR_KEY" 281 | EMBEDDINGS_MODEL="text-embedding-ada-002" 282 | LANGUAGE_MODEL="gpt-3.5-turbo" # gpt-4 283 | 284 | # Deeplake vector DB 285 | ACTIVELOOP_TOKEN="YOUR_KEY" 286 | DATASET_PATH="./local_vector_db" # "hub://USER_ID/custom_dataset" # Edit with your user id if you want to use the cloud db. 287 | ``` -------------------------------------------------------------------------------- /chat.py: -------------------------------------------------------------------------------- 1 | import os 2 | from dotenv import load_dotenv 3 | from langchain.vectorstores import DeepLake 4 | from langchain.chat_models import ChatOpenAI 5 | from langchain.chains import ConversationalRetrievalChain 6 | from langchain.embeddings import OpenAIEmbeddings 7 | from langchain.callbacks import get_openai_callback 8 | 9 | # Load environment variables from .env file 10 | load_dotenv() 11 | 12 | # Set environment variables 13 | os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY') 14 | os.environ['ACTIVELOOP_TOKEN'] = os.getenv('ACTIVELOOP_TOKEN') 15 | language_model = os.getenv('LANGUAGE_MODEL') 16 | 17 | # Set DeepLake dataset path 18 | DEEPLAKE_PATH = os.getenv('DATASET_PATH') 19 | 20 | # Initialize OpenAI embeddings and disallow special tokens 21 | EMBEDDINGS = OpenAIEmbeddings(disallowed_special=()) 22 | 23 | # Initialize DeepLake vector store with OpenAI embeddings 24 | deep_lake = DeepLake( 25 | dataset_path=DEEPLAKE_PATH, 26 | read_only=True, 27 | embedding_function=EMBEDDINGS, 28 | ) 29 | 30 | # Initialize retriever and set search parameters 31 | retriever = deep_lake.as_retriever() 32 | retriever.search_kwargs.update({ 33 | 'distance_metric': 'cos', 34 | 'fetch_k': 100, 35 | 'maximal_marginal_relevance': True, 36 | 'k': 10, 37 | }) 38 | 39 | # Initialize ChatOpenAI model 40 | model = ChatOpenAI(model_name=language_model, temperature=0.2) # gpt-3.5-turbo by default. Use gpt-4 for better and more accurate responses 41 | 42 | # Initialize ConversationalRetrievalChain 43 | qa = ConversationalRetrievalChain.from_llm(model, retriever=retriever) 44 | 45 | # Initialize chat history 46 | chat_history = [] 47 | 48 | def get_user_input(): 49 | """Get user input and handle 'quit' command.""" 50 | question = input("\nPlease enter your question (or 'quit' to stop): ") 51 | if question.lower() == 'quit': 52 | return None 53 | return question 54 | 55 | def print_answer(question, answer): 56 | """Format and print question and answer.""" 57 | print(f"\nQuestion: {question}\nAnswer: {answer}\n") 58 | 59 | def main(): 60 | """Main program loop.""" 61 | while True: 62 | question = get_user_input() 63 | if question is None: # User has quit 64 | break 65 | 66 | # Display token usage and approximate costs 67 | with get_openai_callback() as tokens_usage: 68 | result = qa({"question": question, "chat_history": chat_history}) 69 | chat_history.append((question, result['answer'])) 70 | print_answer(question, result['answer']) 71 | print(tokens_usage) 72 | 73 | if __name__ == "__main__": 74 | main() 75 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.path.insert(0, './src') 3 | import os 4 | import time 5 | 6 | from dotenv import load_dotenv 7 | from scraper import main as github_scraper_main 8 | from langchain.embeddings import OpenAIEmbeddings 9 | from langchain.document_loaders import DirectoryLoader 10 | from langchain.text_splitter import RecursiveCharacterTextSplitter 11 | from langchain.vectorstores import DeepLake 12 | from langchain.chat_models import ChatOpenAI 13 | from langchain.chains import ConversationalRetrievalChain 14 | import deeplake 15 | 16 | def main(): 17 | """ 18 | Main function that handles the scraping, loading, splitting, vector generation, 19 | Optional querying and question-answering process. 20 | """ 21 | 22 | # Load environment variables from .env file 23 | load_dotenv() 24 | os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY') 25 | os.environ['ACTIVELOOP_TOKEN'] = os.getenv('ACTIVELOOP_TOKEN') 26 | 27 | #repo_url = os.getenv('REPO_URL') # Enable this if you want to input the URL from env variables. 28 | repo_url = input('Input the repository you want to index: ') 29 | max_attempts = int(os.getenv('MAX_ATTEMPTS', 5)) # Set a default value for max_attempts 30 | 31 | # Config embeddings model 32 | 33 | embeddings = OpenAIEmbeddings(disallowed_special=()) 34 | 35 | # Scrape the repo; will create a txt file with the organized data 36 | for attempt in range(1, max_attempts+1): 37 | try: 38 | print('Scraping the repository...\n') 39 | start_time = time.time() 40 | github_scraper_main(repo_url) 41 | elapsed_time = time.time() - start_time 42 | print(f"Time needed to pull the data: {elapsed_time:.2f}s.") 43 | break 44 | except Exception as e: 45 | print(f"Attempt {attempt} failed with error: {e}") 46 | if attempt == max_attempts: 47 | print("Max attempts reached. Exiting...") 48 | return 49 | else: 50 | print("Retrying...") 51 | 52 | # Load the document 53 | loader = DirectoryLoader('./repos_content/', glob="**/*.txt", show_progress=True, use_multithreading=True) 54 | print("=" * 100) 55 | print('Loading docs...') 56 | docs = loader.load() 57 | print(f"Loaded {len(docs)} documents.") 58 | 59 | # Split the docs 60 | text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=10, length_function=len) 61 | print("=" * 100) 62 | print('Splitting documents...') 63 | text = text_splitter.split_documents(docs) 64 | print(f'Generated {len(text)} chunks.') 65 | 66 | # Generate vectors and update the vector db. 67 | print("=" * 100) 68 | print('Creating vector DB...') 69 | 70 | # Set the deeplake_path to the repository name 71 | deeplake_path = os.getenv('DATASET_PATH') 72 | db = DeepLake(dataset_path=deeplake_path, embedding_function=embeddings, overwrite=True) 73 | 74 | 75 | # Enable the following to create a cloud vector DB using Deep Lake 76 | """ 77 | deeplake_path = os.getenv('DATASET_PATH') 78 | ds = deeplake.empty(deeplake_path) 79 | db = DeepLake(dataset_path=deeplake_path, embedding_function=embeddings, overwrite=True, public=True) 80 | """ 81 | 82 | db.add_documents(text) 83 | print('Vector database updated.') 84 | 85 | # Enable the following section and edit the questions to test while indexing a new repository. 86 | """ 87 | # Initialize DeepLake vector store with OpenAI embeddings 88 | deep_lake = DeepLake( 89 | dataset_path=deeplake_path, 90 | read_only=True, 91 | embedding_function=embeddings, 92 | ) 93 | # Initialize retriever and set search parameters 94 | retriever = deep_lake.as_retriever() 95 | retriever.search_kwargs.update({ 96 | 'distance_metric': 'cos', 97 | 'fetch_k': 100, 98 | 'maximal_marginal_relevance': True, 99 | 'k': 10, 100 | }) 101 | 102 | # List questions to answer in a row. 103 | # Initialize GPT model 104 | language_model= os.getenv('LANGUAGE_MODEL') 105 | model = ChatOpenAI(model_name=language_model, temperature=0.2) # gpt-3.5-turbo by default, edit in .env 106 | qa = ConversationalRetrievalChain.from_llm(model, retriever=retriever) 107 | 108 | questions = [ 109 | "What files are present in the chatgpt plugin quickstart repository?", 110 | "Can you summarize the chatgpt plugin quickstart repository readme file?", 111 | "Can you show me the ai-plugin.json?", 112 | "What dependencies are required from package.json?" 113 | ] 114 | chat_history = [] 115 | 116 | for question in questions: 117 | result = qa({"question": question, "chat_history": chat_history}) 118 | chat_history.append((question, result['answer'])) 119 | print(f"-> **Question**: {question}\n") 120 | print(f"**Answer**: {result['answer']}\n") 121 | """ 122 | 123 | if __name__ == "__main__": 124 | main() 125 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aioboto3==11.2.0 2 | aiobotocore==2.5.0 3 | aiohttp==3.8.4 4 | aioitertools==0.11.0 5 | aiosignal==1.3.1 6 | antlr4-python3-runtime==4.9.3 7 | anyio==3.7.0 8 | argilla==1.8.0 9 | async-timeout==4.0.2 10 | attrs==23.1.0 11 | backoff==2.2.1 12 | beautifulsoup4==4.12.2 13 | boto3==1.26.76 14 | botocore==1.29.76 15 | certifi==2023.5.7 16 | cffi==1.15.1 17 | chardet==5.1.0 18 | charset-normalizer==3.1.0 19 | click==8.1.3 20 | coloredlogs==15.0.1 21 | commonmark==0.9.1 22 | contourpy==1.0.7 23 | cryptography==41.0.1 24 | cycler==0.11.0 25 | dataclasses-json==0.5.7 26 | deeplake==3.5.4 27 | Deprecated==1.2.14 28 | dill==0.3.6 29 | dnspython==2.3.0 30 | effdet==0.4.1 31 | entrypoints==0.4 32 | et-xmlfile==1.1.0 33 | exceptiongroup==1.1.1 34 | filelock==3.12.0 35 | flatbuffers==23.5.26 36 | fonttools==4.39.4 37 | frozenlist==1.3.3 38 | fsspec==2023.5.0 39 | h11==0.14.0 40 | httpcore==0.16.3 41 | httpx==0.23.3 42 | huggingface-hub==0.15.1 43 | humanfriendly==10.0 44 | humbug==0.3.1 45 | idna==3.4 46 | iopath==0.1.10 47 | Jinja2==3.1.2 48 | jmespath==1.0.1 49 | joblib==1.2.0 50 | kiwisolver==1.4.4 51 | langchain==0.0.188 52 | layoutparser==0.3.4 53 | loguru==0.7.0 54 | lxml==4.9.2 55 | Markdown==3.4.3 56 | MarkupSafe==2.1.2 57 | marshmallow==3.19.0 58 | marshmallow-enum==1.5.1 59 | matplotlib==3.7.1 60 | monotonic==1.6 61 | mpmath==1.3.0 62 | msg-parser==1.2.0 63 | multidict==6.0.4 64 | multiprocess==0.70.14 65 | mypy-extensions==1.0.0 66 | nest-asyncio==1.5.6 67 | networkx==3.1 68 | nltk==3.8.1 69 | numcodecs==0.11.0 70 | numexpr==2.8.4 71 | numpy==1.23.5 72 | olefile==0.46 73 | omegaconf==2.3.0 74 | onnxruntime==1.15.0 75 | openai==0.27.7 76 | openapi-schema-pydantic==1.2.4 77 | opencv-python==4.7.0.72 78 | openpyxl==3.1.2 79 | packaging==23.1 80 | pandas==1.5.3 81 | pathos==0.3.0 82 | pdf2image==1.16.3 83 | pdfminer.six==20221105 84 | pdfplumber==0.9.0 85 | Pillow==9.5.0 86 | pinecone-client==2.2.1 87 | portalocker==2.7.0 88 | pox==0.3.2 89 | ppft==1.7.6.6 90 | protobuf==4.23.2 91 | pycocotools==2.0.6 92 | pycparser==2.21 93 | pydantic==1.10.8 94 | Pygments==2.15.1 95 | PyJWT==2.7.0 96 | pypandoc==1.11 97 | pyparsing==3.0.9 98 | pytesseract==0.3.10 99 | python-dateutil==2.8.2 100 | python-docx==0.8.11 101 | python-dotenv==1.0.0 102 | python-magic==0.4.27 103 | python-multipart==0.0.6 104 | python-pptx==0.6.21 105 | pytz==2023.3 106 | PyYAML==6.0 107 | regex==2023.5.5 108 | requests==2.31.0 109 | rfc3986==1.5.0 110 | rich==13.0.1 111 | s3transfer==0.6.1 112 | safetensors==0.3.1 113 | scipy==1.10.1 114 | six==1.16.0 115 | sniffio==1.3.0 116 | soupsieve==2.4.1 117 | SQLAlchemy==2.0.15 118 | sympy==1.12 119 | tabulate==0.9.0 120 | tenacity==8.2.2 121 | tiktoken==0.4.0 122 | timm==0.9.2 123 | tokenizers==0.13.3 124 | torch==2.0.1 125 | torchvision==0.15.2 126 | tqdm==4.65.0 127 | transformers==4.29.2 128 | typer==0.9.0 129 | typing-inspect==0.9.0 130 | typing_extensions==4.6.3 131 | unstructured==0.7.1 132 | unstructured-inference==0.5.1 133 | urllib3==1.26.16 134 | Wand==0.6.11 135 | wrapt==1.14.1 136 | xlrd==2.0.1 137 | XlsxWriter==3.1.2 138 | yarl==1.9.2 139 | -------------------------------------------------------------------------------- /src/scraper.py: -------------------------------------------------------------------------------- 1 | import os 2 | import ast 3 | import requests 4 | import csv 5 | from bs4 import BeautifulSoup 6 | import urllib.parse 7 | from dotenv import load_dotenv 8 | 9 | load_dotenv() # take environment variables from .env. 10 | 11 | def get_soup(url): 12 | response = requests.get(url) 13 | return BeautifulSoup(response.content, 'html.parser') 14 | 15 | def get_items_in_directory(url): 16 | soup = get_soup(url) 17 | items = [] 18 | 19 | for item in soup.find_all('a', class_='js-navigation-open Link--primary'): 20 | items.append('https://github.com' + item.get('href')) 21 | 22 | return items 23 | 24 | def get_file_content(file_url): 25 | soup = get_soup(file_url) 26 | file_name = soup.find('strong', class_='final-path').text 27 | 28 | # A set of file extensions to ignore 29 | ignored_extensions = {'.png', '.jpg', '.jpeg', '.gif'} 30 | 31 | # Check the file extension 32 | _, extension = os.path.splitext(file_name) 33 | if extension in ignored_extensions: 34 | return None, None 35 | 36 | files_to_ignore = set(ast.literal_eval(os.getenv('FILES_TO_IGNORE'))) 37 | 38 | if file_name in files_to_ignore: 39 | return None, None 40 | 41 | raw_btn = soup.find('a', attrs={'id': 'raw-url'}) 42 | 43 | if raw_btn: 44 | raw_url = 'https://github.com' + raw_btn['href'] 45 | response = requests.get(raw_url) 46 | file_content = response.text 47 | else: 48 | print(f"Could not find raw content for {file_name}.") 49 | return None, None 50 | 51 | return file_name, file_content 52 | 53 | 54 | def process_repository(url, output_dir_path, current_dir="", file_paths=[]): 55 | items = get_items_in_directory(url) 56 | 57 | # Parse the URL to extract the user and repo names 58 | parsed_url = urllib.parse.urlparse(url) 59 | user_name, repo_name = parsed_url.path.strip("/").split("/")[:2] 60 | 61 | for item_url in items: 62 | if "/tree/" in item_url: 63 | item_name = item_url.split('/')[-1] 64 | new_current_dir = os.path.join(current_dir, item_name) 65 | process_repository(item_url, output_dir_path, new_current_dir, file_paths) 66 | elif "/blob/" in item_url: 67 | file_name, file_content = get_file_content(item_url) 68 | if file_name is not None: 69 | file_path = os.path.join(current_dir, file_name) 70 | file_paths.append(file_path) 71 | safe_file_path = file_path.replace("/", "_") # Replace / with _ in file path 72 | output_file_path = os.path.join(output_dir_path, f"{file_name}.txt") 73 | 74 | # Create the directory if it doesn't exist 75 | os.makedirs(os.path.dirname(output_file_path), exist_ok=True) 76 | 77 | with open(output_file_path, 'w') as output_file: 78 | output_file.write(f"The following is the content of a file named {file_name} from a GitHub repository named {repo_name} by {user_name}. The content starts after ------ and ends before --END--.\n") # Custom sentence 79 | output_file.write("------\n") 80 | output_file.write(f"{file_path}\n") 81 | output_file.write(f"{file_content}\n") 82 | output_file.write("--END--\n") 83 | return file_paths 84 | 85 | def main(repo_url): 86 | # Parse the repository URL to extract the user and repo names 87 | parsed_url = urllib.parse.urlparse(repo_url) 88 | user_name, repo_name = parsed_url.path.strip("/").split("/") 89 | 90 | # Form the output directory path 91 | output_dir_path = os.path.join(os.getenv('SAVE_PATH'), f"{user_name}_{repo_name}") 92 | 93 | # Create the output directory if it doesn't exist 94 | os.makedirs(output_dir_path, exist_ok=True) 95 | 96 | # Form the output filenames 97 | txt_filename = f"{user_name}_{repo_name}_file_paths.txt" 98 | 99 | # Form the full paths for the output files 100 | txt_file_path = os.path.join(output_dir_path, txt_filename) 101 | 102 | file_paths = process_repository(repo_url, output_dir_path) 103 | print("=" * 100) 104 | print(f"Repository contents written to {output_dir_path}.") 105 | 106 | # Write the list of file paths to a TXT file 107 | with open(txt_file_path, 'w') as txtfile: 108 | txtfile.write(f"This is a list of file paths from the GitHub repository named {repo_name} by {user_name}:\n") 109 | for file_path in file_paths: 110 | txtfile.write(file_path + "\n") 111 | print("=" * 100) 112 | print(f"List of file paths written to {txt_file_path}.\n") 113 | 114 | 115 | 116 | # This asks for URL input if the file is randirectly for testing purposes. 117 | if __name__ == "__main__": 118 | repo_url = input("Enter the GitHub repository URL: ") 119 | main(repo_url) --------------------------------------------------------------------------------