RAHMAN00700 commited on
Commit
dee16ac
·
0 Parent(s):

first commit

Browse files
.envTemplate ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ API_KEY=your_api_key
2
+ PROJECT_ID=your_project_id
.github/workflows/main.yml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync to Hugging Face hub
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ # to run this workflow manually from the Actions tab
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ sync-to-hub:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v3
13
+ with:
14
+ fetch-depth: 0
15
+ lfs: true
16
+ - name: Push to hub
17
+ env:
18
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
19
+ run: git push --force https://RAHMAN00700:$HF_TOKEN@huggingface.co/spaces/RAHMAN00700/Chat_with_URL1 main
.streamlit/config.toml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [theme]
2
+ base="light"
3
+ primaryColor="#0D62FE"
4
+ backgroundColor="#ffffff"
5
+ secondaryBackgroundColor="#f0f2f6"
6
+ textColor="#000000"
7
+ font="sans serif"
8
+
9
+ [server]
10
+ headless = true
11
+ port = 8501
12
+ enableCORS = false
13
+ enableXsrfProtection = false
README.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: WatsonX WebChat
3
+ emoji: 🚀
4
+ colorFrom: pink
5
+ colorTo: gray
6
+ sdk: docker
7
+ app_port: 8501
8
+ pinned: false
9
+ ---
10
+ # WatsonX-WebChat
11
+
12
+ WatsonX-WebChat is a user-friendly web app that lets you chat with a web page! Just provide a URL, and it uses IBM Watson's language models to answer your questions based on the page's content. It combines smart retrieval techniques with AI for accurate and relevant answers.
13
+ ![](assets/2024-05-29-12-05-51.png)
14
+ ## Features
15
+
16
+ - Extracts and processes text from a given URL.
17
+ - Embeds the text and stores it in a database.
18
+ - Answers user questions based on the embedded content using IBM Watson's language models.
19
+ - Interactive web interface built with Streamlit.
20
+
21
+ ## Setup and Deployment
22
+
23
+ ### Prerequisites
24
+
25
+ - WatsonX IBM
26
+ - Docker (optional)
27
+ ### Installation
28
+
29
+ 1. **Clone the repository:**
30
+
31
+ ```sh
32
+ git clone https://github.com/Abd-al-RahmanH/Chat-with-URL.git
33
+ cd Chat-with-URL
34
+ ```
35
+
36
+ 2. **Create a `.env` file with your IBM Cloud credentials:**
37
+
38
+ ```plaintext
39
+ API_KEY=your_ibm_cloud_api_key
40
+ PROJECT_ID=your_ibm_cloud_project_id
41
+ ```
42
+
43
+ ## To Run
44
+
45
+ ```sh
46
+ pip install -r requirments.txt
47
+ ```
48
+
49
+ ```sh
50
+ streamlit run app.py
51
+ ```
52
+
53
+
54
+ ### Usage
55
+
56
+ 1. **Access the application:**
57
+
58
+ Open your browser and go to the URL provided by Hugging Face after deploying the application.
59
+
60
+ 2. **Enter the required information:**
61
+
62
+ - **API Key**: Your IBM Cloud API key.
63
+ - **Project ID**: Your IBM Cloud project ID.
64
+ - **URL**: The URL of the webpage you want to extract content
65
+ - **Question**: The question you want to ask based on the webpage content.
66
+
67
+ 3. **Get the response:**
68
+
69
+ Click the "Answer the question" button to get a response from the application.
70
+
71
+ ## Contributing
72
+
73
+ Feel free to open issues or submit pull requests if you find any bugs or have suggestions for new features.
74
+
75
+ ## License
76
+
77
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
app.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ import streamlit as st
4
+ import webchat
5
+ import utils
6
+
7
+ # URL of the hosted LLMs is hardcoded because at this time all LLMs share the same endpoint
8
+ url = "https://us-south.ml.cloud.ibm.com"
9
+
10
+ def main():
11
+ # Load environment variables from .env file
12
+ load_dotenv()
13
+ api_key = os.getenv("api_key")
14
+ project_id = os.getenv("project_id")
15
+
16
+ if not api_key or not project_id:
17
+ st.error("Missing API Key or Project ID in the .env file.")
18
+ return
19
+
20
+ st.set_page_config(layout="wide", page_title="RAG Web Demo", page_icon="")
21
+ utils.load_css("styles.css")
22
+
23
+ # Streamlit app title with style
24
+ st.markdown("""
25
+ <div class="menu-bar">
26
+ <h1>IBM watsonx.ai - webchat</h1>
27
+ </div>
28
+ <div style="margin-top: 20px;"><p>Insert the website you want to chat with and ask your question.</p></div>
29
+ """, unsafe_allow_html=True)
30
+
31
+ # Sidebar for information
32
+ st.sidebar.header("Information")
33
+ st.sidebar.markdown("Credentials are securely loaded from your `.env` file. Ensure the file is properly configured.", unsafe_allow_html=True)
34
+ st.sidebar.markdown("<hr>", unsafe_allow_html=True)
35
+
36
+ # Main input area
37
+ user_url = st.text_input('Provide a URL')
38
+ # UI component to enter the question
39
+ question = st.text_area('Question', height=100)
40
+ button_clicked = st.button("Answer the question")
41
+ st.markdown("<hr>", unsafe_allow_html=True)
42
+ st.subheader("Response")
43
+
44
+ collection_name = "base"
45
+ client = utils.chromadb_client()
46
+
47
+ if button_clicked and user_url:
48
+ # Invoke the LLM when the button is clicked
49
+ response = webchat.answer_questions_from_web(api_key, project_id, user_url, question, collection_name, client)
50
+ st.write(response)
51
+ else:
52
+ if not user_url and button_clicked:
53
+ st.warning("Please provide a URL to proceed.")
54
+
55
+ # Cleaning Vector Database
56
+ st.sidebar.markdown("<hr>", unsafe_allow_html=True)
57
+ st.sidebar.header("Memory")
58
+ clean_button_clicked = st.sidebar.button("Clean Memory")
59
+ if clean_button_clicked:
60
+ if collection_name:
61
+ utils.clear_collection(collection_name, client)
62
+ st.sidebar.success("Memory cleared successfully!")
63
+ print("Memory cleared successfully!")
64
+ else:
65
+ st.sidebar.error("Collection name is not defined or empty.")
66
+
67
+ if __name__ == "__main__":
68
+ main()
assets/2024-05-29-12-05-51.png ADDED
docs/README.md ADDED
@@ -0,0 +1,534 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## How to Chat with a Website Using WatsonX
2
+
3
+ Hello everyone! Today, we're going to create an exciting web app that allows us to chat with any website using Watsonx.ai.
4
+
5
+ Watsonx.ai is a powerful SaaS service that leverages the full capabilities of IBM's cloud infrastructure. This tool provides a robust platform for integrating advanced AI functionalities into your applications, making it easier than ever to enhance user interactions with intelligent, context-aware responses.
6
+
7
+
8
+ ## Step 1: Environment Creation
9
+
10
+ There are several ways to create an environment in Python. Follow these steps to set up your environment locally:
11
+
12
+ 1. **Install Python 3.10**
13
+ - Download and install Python 3.10 from [here](https://www.python.org/downloads/windows/).
14
+
15
+ 2. **Create a Virtual Environment**
16
+ - Open your terminal or command prompt and navigate to your project directory.
17
+ - Run the following command to create a virtual environment:
18
+ ```bash
19
+ python -m venv .venv
20
+ ```
21
+ - This command creates a new directory named `.venv` in your current working directory.
22
+
23
+ 3. **Activate the Virtual Environment**
24
+ - **Windows:**
25
+ ```bash
26
+ .venv\Scripts\activate.bat
27
+ ```
28
+ - **Linux:**
29
+ ```bash
30
+ source .venv/bin/activate
31
+ ```
32
+
33
+ 4. **Upgrade pip**
34
+ - Run the following command to upgrade pip:
35
+ ```bash
36
+ python -m pip install --upgrade pip
37
+ ```
38
+
39
+ 5. **Optional: Install JupyterLab for Development and Testing**
40
+ - If you want to use JupyterLab, install it by running:
41
+ ```bash
42
+ pip install ipykernel jupyterlab
43
+ ```
44
+
45
+ ## Step 2: Setup Libraries
46
+
47
+ Once you have your environment set up and activated, you need to install the necessary libraries. Run the following command to install the required packages:
48
+
49
+ ```bash
50
+ pip install streamlit python-dotenv ibm_watson_machine_learning requests chromadb sentence_transformers spacy
51
+ ```
52
+
53
+ ```bash
54
+ python -m spacy download en_core_web_md
55
+ ```
56
+
57
+ IMPORTANT: Be aware of the disk space that will be taken up by documents when they're loaded into
58
+ chromadb on your laptop. The size in chroma will likely be the same as .txt file size.
59
+
60
+ ## Step 3: Getting API from IBM Cloud
61
+
62
+ ### Obtaining an API Key
63
+
64
+ To obtain an API key from IBM Cloud, follow these steps:
65
+
66
+ 1. **Sign In**
67
+ - Go to [IBM Cloud](https://cloud.ibm.com) and sign in to your account.
68
+
69
+ 2. **Navigate to Account Settings**
70
+ - Click on your account name in the top right corner of the IBM Cloud dashboard.
71
+ - From the dropdown menu, select "Manage" to go to the Account settings.
72
+
73
+ 3. **Access API Keys**
74
+ - In the left-hand menu, click on “IBM Cloud API keys” under the “Access (IAM)” section.
75
+
76
+ 4. **Create an API Key**
77
+ - On the “API keys” page, click on the “Create an IBM Cloud API key” button.
78
+ - Provide a name and an optional description for your API key.
79
+ - Select the appropriate access policies if needed.
80
+ - Click on the “Create” button to generate the API key.
81
+
82
+ 5. **Save Your API Key**
83
+ - Once the API key is created, a dialog box displaying the API key value will appear.
84
+ - Make sure to copy and save this key as it will not be shown again.
85
+
86
+ > Note: The steps above are based on the current IBM Cloud interface. They may vary slightly depending on any updates or changes. If you encounter any difficulties or if the steps do not match your IBM Cloud interface, refer to the IBM Cloud documentation or contact IBM support for assistance.
87
+
88
+ ### Retrieving the Project ID for IBM Watsonx
89
+
90
+ To obtain the Project ID for IBM Watsonx, you will need access to the IBM Watson Machine Learning (WML) service. Follow these steps:
91
+
92
+ 1. **Log In**
93
+ - Log in to the [IBM Cloud Console](https://cloud.ibm.com) using your IBM Cloud credentials.
94
+
95
+ 2. **Navigate to Watson Machine Learning**
96
+ - Go to the Watson Machine Learning service.
97
+
98
+ 3. **Access Service Instance**
99
+ - Click on the service instance associated with your Watsonx project.
100
+
101
+ 4. **Find Service Credentials**
102
+ - In the left-hand menu, click on “Service credentials”.
103
+ - Under the “Credentials” tab, you will find a list of service credentials associated with your Watsonx project.
104
+
105
+ 5. **Retrieve Project ID**
106
+ - Click on the name of the service credential you want to use.
107
+ - In the JSON object, find the “project_id” field. The value of this field is your Project ID.
108
+
109
+ ### Adding Credentials to Your Project
110
+
111
+ Add the API key and Project ID to the `.env` file in your project directory:
112
+
113
+ ```plaintext
114
+ API_KEY=your_api_key
115
+ PROJECT_ID=your_project_id
116
+ ```
117
+
118
+ This will configure your project to connect to Watsonx.ai using the obtained credentials.
119
+
120
+ ## Step 4: Creation of app.py
121
+
122
+ In the followig section we are going to invoke Large Language Models (LLMs) deployed in watsonx.ai. Documentation: [here](https://ibm.github.io/watson-machine-learning-sdk/foundation_models.html)
123
+ This example shows a Question and Answer use case for a provided web site
124
+
125
+
126
+
127
+ ### Section 1: Importing Necessary Libraries
128
+
129
+ ```python
130
+ # For reading credentials from the .env file
131
+ import os
132
+ from dotenv import load_dotenv
133
+
134
+ from sentence_transformers import SentenceTransformer
135
+ from chromadb.api.types import EmbeddingFunction
136
+
137
+ # WML python SDK
138
+ from ibm_watson_machine_learning.foundation_models import Model
139
+ from ibm_watson_machine_learning.metanames import GenTextParamsMetaNames as GenParams
140
+ from ibm_watson_machine_learning.foundation_models.utils.enums import ModelTypes, DecodingMethods
141
+
142
+ import requests
143
+ from bs4 import BeautifulSoup
144
+ import spacy
145
+ import chromadb
146
+ import en_core_web_md
147
+ ```
148
+
149
+ **Explanation:**
150
+ - `os` and `dotenv` libraries are used for handling environment variables securely.
151
+ - `sentence_transformers` and `chromadb.api.types` are used for text embedding and database operations.
152
+ - `ibm_watson_machine_learning` SDK helps interact with IBM Watson models.
153
+ - `requests` and `BeautifulSoup` are used for web scraping.
154
+ - `spacy` is used for natural language processing tasks.
155
+
156
+ ### Section 2: Setting Up Environment Variables
157
+
158
+ ```python
159
+ # Important: hardcoding the API key in Python code is not a best practice. We are using
160
+ # this approach for the ease of demo setup. In a production application these variables
161
+ # can be stored in an .env or a properties file
162
+
163
+ # URL of the hosted LLMs is hardcoded because at this time all LLMs share the same endpoint
164
+ url = "https://us-south.ml.cloud.ibm.com"
165
+
166
+ # These global variables will be updated in get_credentials() function
167
+ watsonx_project_id = ""
168
+ # Replace with your IBM Cloud key
169
+ api_key = ""
170
+ ```
171
+
172
+ **Explanation:**
173
+ - Hardcoding credentials is not recommended for production; use environment variables instead.
174
+ - `url` is the endpoint for IBM Watson models.
175
+ - `watsonx_project_id` and `api_key` will be populated from environment variables.
176
+
177
+ ### Section 3: Loading Credentials
178
+
179
+ ```python
180
+ def get_credentials():
181
+ load_dotenv()
182
+ # Update the global variables that will be used for authentication in another function
183
+ globals()["api_key"] = os.getenv("api_key", None)
184
+ globals()["watsonx_project_id"] = os.getenv("project_id", None)
185
+ ```
186
+
187
+ **Explanation:**
188
+ - `get_credentials` function loads the `.env` file and updates global variables for `api_key` and `watsonx_project_id`.
189
+
190
+ ### Section 4: Creating the Model
191
+
192
+ ```python
193
+ def get_model(model_type, max_tokens, min_tokens, decoding, temperature, top_k, top_p):
194
+ generate_params = {
195
+ GenParams.MAX_NEW_TOKENS: max_tokens,
196
+ GenParams.MIN_NEW_TOKENS: min_tokens,
197
+ GenParams.DECODING_METHOD: decoding,
198
+ GenParams.TEMPERATURE: temperature,
199
+ GenParams.TOP_K: top_k,
200
+ GenParams.TOP_P: top_p,
201
+ }
202
+
203
+ model = Model(
204
+ model_id=model_type,
205
+ params=generate_params,
206
+ credentials={
207
+ "apikey": api_key,
208
+ "url": url
209
+ },
210
+ project_id=watsonx_project_id
211
+ )
212
+
213
+ return model
214
+ ```
215
+
216
+ **Explanation:**
217
+ - `get_model` function initializes a Watson model with specified parameters like `max_tokens`, `decoding` method, `temperature`, etc.
218
+ - Credentials and project ID are passed to authenticate the model.
219
+
220
+ ### Section 5: Embedding Function
221
+
222
+ ```python
223
+ class MiniLML6V2EmbeddingFunction(EmbeddingFunction):
224
+ MODEL = SentenceTransformer('all-MiniLM-L6-v2')
225
+
226
+ def __call__(self, texts):
227
+ return MiniLML6V2EmbeddingFunction.MODEL.encode(texts).tolist()
228
+ ```
229
+
230
+ **Explanation:**
231
+ - `MiniLML6V2EmbeddingFunction` class uses `SentenceTransformer` to convert text into embeddings, which are numeric representations of the text.
232
+
233
+ ### Section 6: Extracting Text from a Webpage
234
+
235
+ ```python
236
+ def extract_text(url):
237
+ try:
238
+ # Send an HTTP GET request to the URL
239
+ response = requests.get(url)
240
+
241
+ # Check if the request was successful
242
+ if response.status_code == 200:
243
+ # Parse the HTML content of the page using BeautifulSoup
244
+ soup = BeautifulSoup(response.text, 'html.parser')
245
+
246
+ # Extract contents of <p> elements
247
+ p_contents = [p.get_text() for p in soup.find_all('p')]
248
+
249
+ # Print the contents of <p> elements
250
+ print("\nContents of <p> elements: \n")
251
+ for content in p_contents:
252
+ print(content)
253
+ raw_web_text = " ".join(p_contents)
254
+ # remove \xa0 which is used in html to avoid words break acorss lines.
255
+ cleaned_text = raw_web_text.replace("\xa0", " ")
256
+ return cleaned_text
257
+
258
+ else:
259
+ print(f"Failed to retrieve the page. Status code: {response.status_code}")
260
+
261
+ except Exception as e:
262
+ print(f"An error occurred: {str(e)}")
263
+ ```
264
+
265
+ **Explanation:**
266
+ - `extract_text` function scrapes text content from `<p>` tags of a given webpage URL using `requests` and `BeautifulSoup`.
267
+
268
+ ### Section 7: Splitting Text into Sentences
269
+
270
+ ```python
271
+ def split_text_into_sentences(text):
272
+ nlp = spacy.load("en_core_web_md")
273
+ doc = nlp(text)
274
+ sentences = [sent.text for sent in doc.sents]
275
+ cleaned_sentences = [s.strip() for s in sentences]
276
+ return cleaned_sentences
277
+ ```
278
+
279
+ **Explanation:**
280
+ - `split_text_into_sentences` function uses `spaCy` to split the extracted text into sentences and clean them.
281
+
282
+ ### Section 8: Creating Embeddings
283
+
284
+ ```python
285
+ def create_embedding(url, collection_name, client):
286
+ cleaned_text = extract_text(url)
287
+ cleaned_sentences = split_text_into_sentences(cleaned_text)
288
+ collection = client.get_or_create_collection(collection_name)
289
+
290
+ # Upload text to chroma
291
+ collection.upsert(
292
+ documents=cleaned_sentences,
293
+ metadatas=[{"source": str(i)} for i in range(len(cleaned_sentences))],
294
+ ids=[str(i) for i in range(len(cleaned_sentences))],
295
+ )
296
+
297
+ return collection
298
+ ```
299
+
300
+ **Explanation:**
301
+ - `create_embedding` function extracts, cleans, and splits text, then uploads it to a Chroma database collection.
302
+
303
+ ### Section 9: Creating a Prompt for the Model
304
+
305
+ ```python
306
+ def create_prompt(url, question, collection_name,client):
307
+
308
+ # Create embeddings for the text file
309
+ collection = create_embedding(url, collection_name,client)
310
+
311
+ # query relevant information
312
+ relevant_chunks = collection.query(
313
+ query_texts=[question],
314
+ n_results=5,
315
+ )
316
+ context = "\n\n\n".join(relevant_chunks["documents"][0])
317
+ # Please note that this is a generic format. You can change this format to be specific to llama
318
+ prompt = (f"{context}\n\nPlease answer the following question in one sentence using this "
319
+ + f"text. "
320
+ + f"If the question is unanswerable, say \"unanswerable\". Do not include information that's not relevant to the question."
321
+ + f"Question: {question}")
322
+
323
+ return prompt
324
+ ```
325
+
326
+ **Explanation:**
327
+ - `create_prompt` function generates a prompt by querying the Chroma database for relevant text chunks based on a question and constructs a formatted prompt.
328
+
329
+ ### Section 10: Main Function
330
+
331
+ ```python
332
+ def main():
333
+
334
+ # Get the API key and project id and update global variables
335
+ get_credentials()
336
+
337
+ # Try diffrent URLs and questions
338
+ url = "https://huggingface.co/learn/nlp-course/chapter1/2?fw=pt"
339
+
340
+ question = "What is NLP?"
341
+
342
+ collection_name = "test_web_RAG"
343
+
344
+ answer_questions_from_web(api_key, watsonx_project_id, url, question, collection_name)
345
+ ```
346
+
347
+ **Explanation:**
348
+ - `main` function initializes credentials and runs the process to answer a question based on the content from a given URL.
349
+
350
+ ### Section 11: Answering Questions from the Web
351
+
352
+ ```python
353
+ def answer_questions_from_web(request_api_key, request_project_id, url, question, collection_name):
354
+ # Update the global variable
355
+ globals()["api_key"] = request_api_key
356
+ globals()["watsonx_project_id"] = request_project_id
357
+
358
+ # Specify model parameters
359
+ model_type = "meta-llama/llama-2-70b-chat"
360
+ max_tokens = 100
361
+ min_tokens = 50
362
+ top_k = 50
363
+ top_p = 1
364
+ decoding = DecodingMethods.GREEDY
365
+ temperature = 0.7
366
+
367
+ # Get the watsonx model = try both options
368
+ model = get_model(model_type, max_tokens, min_tokens, decoding, temperature, top_k, top_p)
369
+ # Get client Chromadb
370
+ client = chromadb.Client()
371
+ # Get the prompt
372
+ complete_prompt = create_prompt(url, question, collection_name,client)
373
+
374
+ # Let's review the prompt
375
+ print("----------------------------------------------------------------------------------------------------")
376
+ print("*** Prompt:" + complete_prompt + "***")
377
+ print("----------------------------------------------------------------------------------------------------")
378
+
379
+ generated_response = model.generate(prompt=complete_prompt)
380
+ response_text = generated_response['results'][0]['generated_text']
381
+
382
+ # Remove trailing white spaces
383
+ response_text = response
384
+
385
+ _text.strip()
386
+
387
+ # print model response
388
+ print("--------------------------------- Generated response -----------------------------------")
389
+ print(response_text)
390
+ print("*********************************************************************************************")
391
+
392
+ return response_text
393
+ ```
394
+
395
+ **Explanation:**
396
+ - `answer_questions_from_web` function updates the global variables, initializes the model, creates a prompt, generates a response, and prints the answer.
397
+
398
+ ### Section 12: Running the Script
399
+
400
+ ```python
401
+ # Invoke the main function
402
+ if __name__ == "__main__":
403
+ main()
404
+ ```
405
+
406
+ **Explanation:**
407
+ - This code block ensures that the `main` function is called when the script is run directly.
408
+
409
+ By breaking down the code into these sections, readers can understand the role of each part and how they work together to create a web chat application using Watsonx.ai.
410
+
411
+
412
+ ### Explanation of `run.py` Code
413
+
414
+ Let's break down and explain the `run.py` code step-by-step:
415
+
416
+ #### Section 1: Importing Necessary Libraries
417
+
418
+ ```python
419
+ # For reading credentials from the .env file
420
+ import os
421
+ from dotenv import load_dotenv
422
+ import streamlit as st
423
+ import webchat
424
+ ```
425
+
426
+ **Explanation:**
427
+ - `os` and `dotenv` are used to load environment variables.
428
+ - `streamlit` is a library for creating interactive web applications.
429
+ - `webchat` is a module that contains functions for interacting with IBM Watson models.
430
+
431
+ #### Section 2: Setting Up Environment Variables
432
+
433
+ ```python
434
+ # URL of the hosted LLMs is hardcoded because at this time all LLMs share the same endpoint
435
+ url = "https://us-south.ml.cloud.ibm.com"
436
+
437
+ # These global variables will be updated in get_credentials() function
438
+ watsonx_project_id = ""
439
+ api_key = ""
440
+ ```
441
+
442
+ **Explanation:**
443
+ - `url` is the endpoint for IBM Watson models.
444
+ - `watsonx_project_id` and `api_key` are initialized and will be populated with actual values from environment variables.
445
+
446
+ #### Section 3: Loading Credentials
447
+
448
+ ```python
449
+ def get_credentials():
450
+ load_dotenv()
451
+ # Update the global variables that will be used for authentication in another function
452
+ globals()["api_key"] = os.getenv("API_KEY", "")
453
+ globals()["watsonx_project_id"] = os.getenv("PROJECT_ID", "")
454
+ ```
455
+
456
+ **Explanation:**
457
+ - `get_credentials` function loads the environment variables from a `.env` file and updates the global `api_key` and `watsonx_project_id`.
458
+
459
+ #### Section 4: Streamlit Application Setup
460
+
461
+ ```python
462
+ def main():
463
+ # Get the API key and project id and update global variables
464
+ get_credentials()
465
+
466
+ # Use the full page instead of a narrow central column
467
+ st.set_page_config(layout="wide")
468
+
469
+ # Streamlit app title
470
+ st.title("IBM watsonx - Chat with a Web Page")
471
+
472
+ # Sidebar for settings
473
+ st.sidebar.header("Settings")
474
+ api_key_input = st.sidebar.text_input("API Key", api_key)
475
+ project_id_input = st.sidebar.text_input("Project ID", watsonx_project_id)
476
+
477
+ # Update credentials if provided by the user
478
+ if api_key_input:
479
+ globals()["api_key"] = api_key_input
480
+ if project_id_input:
481
+ globals()["watsonx_project_id"] = project_id_input
482
+
483
+ user_url = st.text_input('Provide a URL')
484
+ collection_name = st.text_input('Collection Name: Choose a unique name (lowercase letters, numbers, and underscores allowed) to identify this data set within ChromaDB. This name helps you organize and access your data efficiently')
485
+
486
+ # UI component to enter the question
487
+ question = st.text_area('Question', height=100)
488
+ button_clicked = st.button("Answer the question")
489
+
490
+ st.subheader("Response")
491
+
492
+ # Invoke the LLM when the button is clicked
493
+ if button_clicked:
494
+ response = webchat.answer_questions_from_web(api_key, watsonx_project_id, user_url, question, collection_name)
495
+ st.write(response)
496
+ ```
497
+
498
+ **Explanation:**
499
+ - `main` function sets up the Streamlit application.
500
+ - `get_credentials` is called to load API credentials.
501
+ - `st.set_page_config` configures the page layout.
502
+ - Streamlit UI components are defined:
503
+ - Title and sidebar settings for API key and project ID.
504
+ - Text input fields for URL and collection name.
505
+ - Text area for the question.
506
+ - Button to trigger the question answering process.
507
+ - When the button is clicked, `webchat.answer_questions_from_web` function is called to get the response, which is then displayed on the page.
508
+
509
+ #### Section 5: Running the Application
510
+
511
+ ```python
512
+ if __name__ == "__main__":
513
+ main()
514
+ ```
515
+
516
+
517
+ ```
518
+ streamlit run run.py
519
+ ```
520
+
521
+ ![](assets/2024-05-29-10-05-58.png)
522
+
523
+
524
+
525
+ **Explanation:**
526
+ - Ensures that the `main` function is executed when the script is run directly.
527
+
528
+ ### Summary of the Program
529
+
530
+ The provided code sets up an interactive web application using Streamlit to demonstrate a Retrieval-Augmented Generation (RAG) system. The system allows users to input a URL, which is then scraped for content. This content is embedded and stored in a database. Users can ask questions related to the content, and the system uses IBM Watson's language model to generate relevant answers. The application handles authentication via environment variables and allows users to update credentials through the UI.
531
+
532
+ ### Conclusion
533
+
534
+ In this blog post, we've explored a Python-based web chat application using Watsonx.ai and IBM Watson's powerful language models. The application demonstrates how to build a Retrieval-Augmented Generation (RAG) system that scrapes web content, embeds it, and leverages machine learning to answer user questions. By breaking down the code into manageable sections, we've provided a comprehensive guide to understanding and implementing such a system. This application showcases the potential of combining web scraping, natural language processing, and interactive web frameworks to create sophisticated AI-driven solutions.
docs/assets/2024-05-29-10-05-58.png ADDED
docs/run.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # For reading credentials from the .env file
2
+ import os
3
+ from dotenv import load_dotenv
4
+ import streamlit as st
5
+ import webchat
6
+ # URL of the hosted LLMs is hardcoded because at this time all LLMs share the same endpoint
7
+ url = "https://us-south.ml.cloud.ibm.com"
8
+
9
+ # These global variables will be updated in get_credentials() function
10
+ watsonx_project_id = ""
11
+ # Replace with your IBM Cloud key
12
+ api_key = ""
13
+
14
+ def get_credentials():
15
+
16
+ load_dotenv()
17
+ # Update the global variables that will be used for authentication in another function
18
+ globals()["api_key"] = os.getenv("api_key", None)
19
+ globals()["watsonx_project_id"] = os.getenv("project_id", None)
20
+
21
+
22
+ def main():
23
+
24
+ # Get the API key and project id and update global variables
25
+ get_credentials()
26
+
27
+ # Use the full page instead of a narrow central column
28
+ st.set_page_config(layout="wide")
29
+
30
+ # Streamlit app title
31
+ st.title("IBM watsonx - Chat with a Web Page")
32
+
33
+ user_url = st.text_input('Provide a URL')
34
+
35
+ collection_name = st.text_input('Collection Name: Choose a unique name (lowercase letters, numbers, and underscores allowed) to identify this data set within ChromaDB. This name helps you organize and access your data efficiently')
36
+
37
+ # UI component to enter the question
38
+ question = st.text_area('Question',height=100)
39
+ button_clicked = st.button("Answer the question")
40
+
41
+ st.subheader("Response")
42
+
43
+ # Invoke the LLM when the button is clicked
44
+ if button_clicked:
45
+ response = webchat.answer_questions_from_web(api_key,watsonx_project_id,user_url,question,collection_name)
46
+ st.write(response)
47
+
48
+ if __name__ == "__main__":
49
+ main()
50
+
51
+
docs/utils/notes.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Deploy on Hugging Face
2
+
3
+ 3. **Log in to Hugging Face CLI:**
4
+
5
+ ```sh
6
+ huggingface-cli login
7
+ ```
8
+
9
+ 2. **Create a new repository on Hugging Face.**
10
+
11
+ 3. **Push the Docker image to Hugging Face:**
12
+
13
+ ```sh
14
+ docker tag watsonx-webchat huggingface.co/ruslanmv/watsonx-webchat
15
+
16
+ ```
17
+
18
+
19
+
20
+ ```sh
21
+ docker push huggingface.co/ruslanmv/watsonx-webchat
22
+ ```
23
+
24
+ 4. **Configure the Hugging Face repository to use the Docker image:**
25
+
26
+ - Go to your Hugging Face repository page.
27
+ - Click on "Settings".
28
+ - Under "Custom Docker Image", set the image to `huggingface.co/ruslanmv/watsonx-webchat`.
docs/webchat.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # For reading credentials from the .env file
2
+ import os
3
+ from dotenv import load_dotenv
4
+
5
+ from sentence_transformers import SentenceTransformer
6
+ from chromadb.api.types import EmbeddingFunction
7
+
8
+ # WML python SDK
9
+ from ibm_watson_machine_learning.foundation_models import Model
10
+ from ibm_watson_machine_learning.metanames import GenTextParamsMetaNames as GenParams
11
+ from ibm_watson_machine_learning.foundation_models.utils.enums import ModelTypes, DecodingMethods
12
+
13
+ import requests
14
+ from bs4 import BeautifulSoup
15
+ import spacy
16
+ import chromadb
17
+ import en_core_web_md
18
+
19
+
20
+ # Important: hardcoding the API key in Python code is not a best practice. We are using
21
+ # this approach for the ease of demo setup. In a production application these variables
22
+ # can be stored in an .env or a properties file
23
+
24
+ # URL of the hosted LLMs is hardcoded because at this time all LLMs share the same endpoint
25
+ url = "https://us-south.ml.cloud.ibm.com"
26
+
27
+ # These global variables will be updated in get_credentials() function
28
+ watsonx_project_id = ""
29
+ # Replace with your IBM Cloud key
30
+ api_key = ""
31
+
32
+ def get_credentials():
33
+
34
+ load_dotenv()
35
+ # Update the global variables that will be used for authentication in another function
36
+ globals()["api_key"] = os.getenv("api_key", None)
37
+ globals()["watsonx_project_id"] = os.getenv("project_id", None)
38
+
39
+ # The get_model function creates an LLM model object with the specified parameters
40
+
41
+ def get_model(model_type, max_tokens, min_tokens, decoding, temperature, top_k, top_p):
42
+ generate_params = {
43
+ GenParams.MAX_NEW_TOKENS: max_tokens,
44
+ GenParams.MIN_NEW_TOKENS: min_tokens,
45
+ GenParams.DECODING_METHOD: decoding,
46
+ GenParams.TEMPERATURE: temperature,
47
+ GenParams.TOP_K: top_k,
48
+ GenParams.TOP_P: top_p,
49
+ }
50
+
51
+ model = Model(
52
+ model_id=model_type,
53
+ params=generate_params,
54
+ credentials={
55
+ "apikey": api_key,
56
+ "url": url
57
+ },
58
+ project_id=watsonx_project_id
59
+ )
60
+
61
+ return model
62
+
63
+ def get_model_test(model_type, max_tokens, min_tokens, decoding, temperature):
64
+ generate_params = {
65
+ GenParams.MAX_NEW_TOKENS: max_tokens,
66
+ GenParams.MIN_NEW_TOKENS: min_tokens,
67
+ GenParams.DECODING_METHOD: decoding,
68
+ GenParams.TEMPERATURE: temperature
69
+ }
70
+
71
+ model = Model(
72
+ model_id=model_type,
73
+ params=generate_params,
74
+ credentials={
75
+ "apikey": api_key,
76
+ "url": url
77
+ },
78
+ project_id=watsonx_project_id
79
+ )
80
+
81
+ return model
82
+
83
+ # Set up cache directory (consider user-defined location)
84
+ current_dir = os.getcwd()
85
+ cache_dir = os.path.join(current_dir, ".cache")
86
+ # Create cache directory if necessary
87
+ if not os.path.exists(cache_dir):
88
+ os.makedirs(cache_dir)
89
+ # Set the Hugging Face cache directory
90
+ os.environ["HF_HOME"] = cache_dir
91
+ # Download the model (specify the correct model identifier)
92
+ model_name = 'sentence-transformers/all-MiniLM-L6-v2'
93
+ #model_name = "all-MiniLM-L6-v2"
94
+ model = SentenceTransformer(model_name, cache_folder=cache_dir)
95
+ # Print confirmation message
96
+ print(f"Model '{model_name}' downloaded and loaded from cache directory: {cache_dir}")
97
+
98
+ # Embedding function
99
+ class MiniLML6V2EmbeddingFunction(EmbeddingFunction):
100
+ MODEL = model
101
+ def __call__(self, texts):
102
+ return MiniLML6V2EmbeddingFunction.MODEL.encode(texts).tolist()
103
+
104
+ def extract_text(url):
105
+ try:
106
+ # Send an HTTP GET request to the URL
107
+ response = requests.get(url)
108
+
109
+ # Check if the request was successful
110
+ if response.status_code == 200:
111
+ # Parse the HTML content of the page using BeautifulSoup
112
+ soup = BeautifulSoup(response.text, 'html.parser')
113
+
114
+ # Extract contents of <p> elements
115
+ p_contents = [p.get_text() for p in soup.find_all('p')]
116
+
117
+ # Print the contents of <p> elements
118
+ print("\nContents of <p> elements: \n")
119
+ for content in p_contents:
120
+ print(content)
121
+ raw_web_text = " ".join(p_contents)
122
+ # remove \xa0 which is used in html to avoid words break acorss lines.
123
+ cleaned_text = raw_web_text.replace("\xa0", " ")
124
+ return cleaned_text
125
+ else:
126
+ print(f"Failed to retrieve the page. Status code: {response.status_code}")
127
+
128
+ except Exception as e:
129
+ print(f"An error occurred: {str(e)}")
130
+
131
+
132
+ def split_text_into_sentences(text):
133
+ nlp = spacy.load("en_core_web_md")
134
+ doc = nlp(text)
135
+ sentences = [sent.text for sent in doc.sents]
136
+ cleaned_sentences = [s.strip() for s in sentences]
137
+ return cleaned_sentences
138
+
139
+ def create_embedding(url, collection_name,client):
140
+ cleaned_text = extract_text(url)
141
+ cleaned_sentences = split_text_into_sentences(cleaned_text)
142
+ collection = client.get_or_create_collection(collection_name)
143
+ # Upload text to chroma
144
+ collection.upsert(
145
+ documents=cleaned_sentences,
146
+ metadatas=[{"source": str(i)} for i in range(len(cleaned_sentences))],
147
+ ids=[str(i) for i in range(len(cleaned_sentences))],
148
+ )
149
+
150
+ return collection
151
+
152
+
153
+ def create_prompt_old(url, question, collection_name, client):
154
+ # Create embeddings for the text file
155
+ collection = create_embedding(url, collection_name, client)
156
+
157
+ # query relevant information
158
+ relevant_chunks = collection.query(
159
+ query_texts=[question],
160
+ n_results=5,
161
+ )
162
+ context = "\n\n\n".join(relevant_chunks["documents"][0])
163
+ # Please note that this is a generic format. You can change this format to be specific to llama
164
+ prompt = (f"{context}\n\nPlease answer the following question in one sentence using this "
165
+ + f"text. "
166
+ + f"If the question is unanswerable, say \"unanswerable\". Do not include information that's not relevant to the question."
167
+ + f"Question: {question}")
168
+
169
+ return prompt
170
+
171
+ def create_prompt(url, question, collection_name,client):
172
+ try:
173
+ # Create embeddings for the text file
174
+ collection = create_embedding(url, collection_name,client)
175
+ except Exception as e:
176
+ return f"Error creating embeddings: {e}"
177
+
178
+ try:
179
+ # Query relevant information
180
+ relevant_chunks = collection.query(
181
+ query_texts=[question],
182
+ n_results=5,
183
+ )
184
+ context = "\n\n\n".join(relevant_chunks["documents"][0])
185
+ except Exception as e:
186
+ return f"Error querying the collection: {e}"
187
+
188
+ # Create the prompt
189
+ prompt = (
190
+ "<|begin_of_text|>\n"
191
+ "<|start_header_id|>system<|end_header_id|>\n"
192
+ "You are a helpful AI assistant.\n"
193
+ "<|eot_id|>\n"
194
+ "<|start_header_id|>user<|end_header_id|>\n"
195
+ f"### Context:\n{context}\n\n"
196
+ f"### Instruction:\n"
197
+ f"Please answer the following question based on the above context. Your answer should be concise and directly address the question. "
198
+ f"If the question is unanswerable based on the given context, respond with 'unanswerable'.\n\n"
199
+ f"### Question:\n{question}\n"
200
+ "<|eot_id|>\n"
201
+ "<|start_header_id|>assistant<|end_header_id|>\n"
202
+ )
203
+
204
+ return prompt
205
+
206
+
207
+
208
+ def main():
209
+
210
+ # Get the API key and project id and update global variables
211
+ get_credentials()
212
+
213
+ # Try diffrent URLs and questions
214
+ url = "https://huggingface.co/learn/nlp-course/chapter1/2?fw=pt"
215
+
216
+ question = "What is NLP?"
217
+ collection_name = "test_web_RAG"
218
+
219
+ answer_questions_from_web(api_key, watsonx_project_id, url, question, collection_name)
220
+
221
+
222
+ def answer_questions_from_web(request_api_key, request_project_id, url, question, collection_name,client):
223
+ # Update the global variable
224
+ globals()["api_key"] = request_api_key
225
+ globals()["watsonx_project_id"] = request_project_id
226
+
227
+ # Specify model parameters
228
+ model_type = "meta-llama/llama-2-70b-chat"
229
+ #model_type = "meta-llama/llama-3-70b-instruct"
230
+ max_tokens = 100
231
+ min_tokens = 50
232
+ top_k = 50
233
+ top_p = 1
234
+ decoding = DecodingMethods.GREEDY
235
+ temperature = 0.7
236
+
237
+ # Get the watsonx model = try both options
238
+ model = get_model(model_type, max_tokens, min_tokens, decoding, temperature, top_k, top_p)
239
+ # Get client Chromadb
240
+ client = chromadb.Client()
241
+
242
+ # Get the prompt
243
+ complete_prompt = create_prompt(url, question, collection_name,client)
244
+
245
+ # Let's review the prompt
246
+ print("----------------------------------------------------------------------------------------------------")
247
+ print("*** Prompt:" + complete_prompt + "***")
248
+ print("----------------------------------------------------------------------------------------------------")
249
+
250
+ generated_response = model.generate(prompt=complete_prompt)
251
+ response_text = generated_response['results'][0]['generated_text']
252
+
253
+ # Remove trailing white spaces
254
+ response_text = response_text.strip()
255
+
256
+ # print model response
257
+ print("--------------------------------- Generated response -----------------------------------")
258
+ print(response_text)
259
+ print("*********************************************************************************************")
260
+
261
+ return response_text
262
+
263
+ # Invoke the main function
264
+ if __name__ == "__main__":
265
+ main()
requirements.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit==1.35.0
2
+ requests==2.32.2
3
+ beautifulsoup4==4.12.3
4
+ en-core-web-md @ https://github.com/explosion/spacy-models/releases/download/en_core_web_md-3.7.1/en_core_web_md-3.7.1-py3-none-any.whl#sha256=6a0f857a2b4d219c6fa17d455f82430b365bf53171a2d919b9376e5dc9be032e
5
+ spacy
6
+ sentence-transformers==2.7.0
7
+ chromadb
8
+ ibm-watson-machine-learning
9
+ python-dotenv==1.0.1
10
+ transformers==4.41.1
11
+
12
+ tokenizers==0.19.1
13
+ toml==0.10.2
14
+ tomli==2.0.1
15
+ toolz==0.12.1
16
+ torch==2.3.0
17
+ opentelemetry-api==1.24.0
18
+ opentelemetry-exporter-otlp-proto-common==1.24.0
19
+ opentelemetry-exporter-otlp-proto-grpc==1.24.0
20
+ opentelemetry-instrumentation==0.45b0
21
+ opentelemetry-instrumentation-asgi==0.45b0
22
+ opentelemetry-instrumentation-fastapi==0.45b0
23
+ opentelemetry-proto==1.24.0
24
+ opentelemetry-sdk==1.24.0
25
+ tqdm==4.66.4
styles.css ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .reportview-container, .main {
2
+ background: #ffadad;
3
+ color: #000000;
4
+ }
5
+ .sidebar .sidebar-content {
6
+ background: #f0f2f6;
7
+ color: #000000;
8
+ }
9
+ .stButton>button {
10
+ background-color: #0D62FE;
11
+ color: white;
12
+ }
13
+ .stTextInput>div>div>input {
14
+ color: #000000;
15
+ background-color: #ffffff;
16
+ }
17
+ .tTextArea>div>textarea {
18
+ color: #000000;
19
+ background-color: #ffffff;
20
+ }
21
+ label, .stTextInput>label, .stTextArea>label {
22
+ color: #000000;
23
+ }
24
+ h1, h2, h3, h4, h5, h6 {
25
+ color: #000000;
26
+ }
27
+ .sidebar .sidebar-content h2, .sidebar .sidebar-content h3, .sidebar .sidebar-content h4, .sidebar .sidebar-content h5, .sidebar .sidebar-content h6,
28
+ .sidebar .sidebar-content label, .sidebar .sidebar-content .stTextInput>label, .sidebar .sidebar-content .stTextArea>label {
29
+ color: #000000;
30
+ }
31
+ .navbar {
32
+ overflow: hidden;
33
+ background-color: #000000;
34
+ position: fixed;
35
+ top: 0;
36
+ width: 100%;
37
+ z-index: 1000;
38
+ }
39
+ .navbar h1 {
40
+ float: left;
41
+ display: block;
42
+ color: #ffffff;
43
+ text-align: center;
44
+ padding: 14px 1x;
45
+ text-decoration: none;
46
+ font-size: 17px;
47
+ margin: 0;
48
+ }
49
+ .menu-bar {
50
+ background-color: #000000;
51
+ padding: 10px;
52
+ display: flex;
53
+ justify-content: space-between;
54
+ align-items: center;
55
+ }
56
+ .menu-bar h1 {
57
+ color: #ffffff;
58
+ margin: 0;
59
+ font-size: 18px;
60
+ font-family: 'IBM Plex Sans', sans-serif;
61
+ }
utils.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from urllib.parse import urlparse
2
+ from dotenv import load_dotenv
3
+ import os
4
+ import chromadb
5
+ import streamlit as st
6
+ import logging
7
+
8
+ # Set up logging
9
+ logging.basicConfig(level=logging.INFO)
10
+ logger = logging.getLogger(__name__)
11
+
12
+ def get_credentials():
13
+ load_dotenv()
14
+ api_key = os.getenv("api_key", None)
15
+ watsonx_project_id = os.getenv("project_id", None)
16
+
17
+ if not api_key or not watsonx_project_id:
18
+ raise EnvironmentError("Missing `api_key` or `project_id` in the .env file.")
19
+
20
+ return api_key, watsonx_project_id
21
+
22
+ def load_css(file_name):
23
+ try:
24
+ with open(file_name) as file:
25
+ st.markdown(f'<style>{file.read()}</style>', unsafe_allow_html=True)
26
+ except FileNotFoundError:
27
+ st.error(f"CSS file '{file_name}' not found.")
28
+ except Exception as e:
29
+ st.error(f"Failed to load CSS file: {e}")
30
+
31
+ def create_collection_name(url):
32
+ try:
33
+ parsed_url = urlparse(url)
34
+ domain_parts = parsed_url.netloc.split('.')
35
+ if len(domain_parts) >= 2:
36
+ return domain_parts[-2]
37
+ else:
38
+ return "default_collection"
39
+ except Exception as e:
40
+ logger.warning(f"Invalid URL '{url}': {e}")
41
+ return "invalid_url"
42
+
43
+ def chromadb_client():
44
+ from chromadb.config import Settings
45
+
46
+ current_dir = os.getcwd()
47
+ custom_cache_path = os.path.join(current_dir, ".cache")
48
+
49
+ try:
50
+ settings = Settings(persist_directory=custom_cache_path)
51
+ client = chromadb.Client(settings)
52
+ return client
53
+ except Exception as e:
54
+ raise RuntimeError(f"Failed to initialize ChromaDB client: {e}")
55
+
56
+ def clear_collection(collection_name, client):
57
+ try:
58
+ collection = client.get_collection(collection_name)
59
+ if collection:
60
+ collection.delete()
61
+ logger.info(f"Collection '{collection_name}' cleared successfully!")
62
+ except ValueError:
63
+ logger.warning(f"Collection '{collection_name}' does not exist, skipping.")
64
+ except Exception as e:
65
+ logger.error(f"Failed to clear collection '{collection_name}': {e}")
webchat.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from sentence_transformers import SentenceTransformer
4
+ from chromadb.api.types import EmbeddingFunction
5
+ from ibm_watson_machine_learning.foundation_models import Model
6
+ from ibm_watson_machine_learning.metanames import GenTextParamsMetaNames as GenParams
7
+ from ibm_watson_machine_learning.foundation_models.utils.enums import DecodingMethods
8
+ import requests
9
+ from bs4 import BeautifulSoup
10
+ import spacy
11
+ import chromadb
12
+ from utils import chromadb_client
13
+
14
+ # Load environment variables from the .env file
15
+ load_dotenv()
16
+
17
+ # Global constants
18
+ WATSONX_URL = "https://us-south.ml.cloud.ibm.com"
19
+ API_KEY = os.getenv("api_key")
20
+ PROJECT_ID = os.getenv("project_id")
21
+
22
+ # Validate environment variables
23
+ if not API_KEY or not PROJECT_ID:
24
+ raise ValueError("API Key or Project ID is missing from the .env file.")
25
+
26
+ # Model and decoding parameters
27
+ MODEL_PARAMS = {
28
+ "model_type": "meta-llama/llama-3-70b-instruct",
29
+ "max_tokens": 100,
30
+ "min_tokens": 50,
31
+ "decoding": DecodingMethods.GREEDY,
32
+ "temperature": 0.7,
33
+ "top_k": 50,
34
+ "top_p": 1,
35
+ }
36
+
37
+ # Set up cache directory
38
+ CACHE_DIR = os.path.join(os.getcwd(), ".cache")
39
+ os.makedirs(CACHE_DIR, exist_ok=True)
40
+ os.environ["HF_HOME"] = CACHE_DIR
41
+
42
+ # Load sentence-transformers model
43
+ MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"
44
+ embedding_model = SentenceTransformer(MODEL_NAME, cache_folder=CACHE_DIR)
45
+
46
+ # Embedding function
47
+ class MiniLML6V2EmbeddingFunction(EmbeddingFunction):
48
+ MODEL = embedding_model
49
+
50
+ def __call__(self, texts):
51
+ return MiniLML6V2EmbeddingFunction.MODEL.encode(texts).tolist()
52
+
53
+
54
+ def get_model(params):
55
+ """Retrieve the IBM WatsonX LLM model with specified parameters."""
56
+ generate_params = {
57
+ GenParams.MAX_NEW_TOKENS: params["max_tokens"],
58
+ GenParams.MIN_NEW_TOKENS: params["min_tokens"],
59
+ GenParams.DECODING_METHOD: params["decoding"],
60
+ GenParams.TEMPERATURE: params["temperature"],
61
+ GenParams.TOP_K: params["top_k"],
62
+ GenParams.TOP_P: params["top_p"],
63
+ }
64
+
65
+ return Model(
66
+ model_id=params["model_type"],
67
+ params=generate_params,
68
+ credentials={"apikey": API_KEY, "url": WATSONX_URL},
69
+ project_id=PROJECT_ID,
70
+ )
71
+
72
+
73
+ def extract_text(url):
74
+ """Scrape text from a given URL."""
75
+ try:
76
+ response = requests.get(url)
77
+ response.raise_for_status()
78
+ soup = BeautifulSoup(response.text, "html.parser")
79
+ paragraphs = [p.get_text() for p in soup.find_all("p")]
80
+ cleaned_text = " ".join(paragraphs).replace("\xa0", " ")
81
+ return cleaned_text
82
+ except Exception as e:
83
+ raise RuntimeError(f"Failed to extract text from {url}: {e}")
84
+
85
+
86
+ def split_text_into_sentences(text):
87
+ """Split text into sentences using SpaCy."""
88
+ nlp = spacy.load("en_core_web_md")
89
+ doc = nlp(text)
90
+ return [sent.text.strip() for sent in doc.sents]
91
+
92
+
93
+ def create_embedding(url, collection_name, client):
94
+ """Create embeddings for the text scraped from a URL."""
95
+ text = extract_text(url)
96
+ sentences = split_text_into_sentences(text)
97
+ collection = client.get_or_create_collection(collection_name)
98
+ collection.upsert(
99
+ documents=sentences,
100
+ metadatas=[{"source": str(i)} for i in range(len(sentences))],
101
+ ids=[str(i) for i in range(len(sentences))],
102
+ )
103
+ return collection
104
+
105
+
106
+ def create_prompt(url, question, collection_name, client):
107
+ """Generate a prompt using the embedded collection."""
108
+ try:
109
+ collection = create_embedding(url, collection_name, client)
110
+ relevant_chunks = collection.query(query_texts=[question], n_results=5)
111
+ context = "\n\n\n".join(relevant_chunks["documents"][0])
112
+ prompt = (
113
+ "<|begin_of_text|>\n"
114
+ "<|start_header_id|>system<|end_header_id|>\n"
115
+ "You are a helpful AI assistant.\n"
116
+ "<|eot_id|>\n"
117
+ "<|start_header_id|>user<|end_header_id|>\n"
118
+ f"### Context:\n{context}\n\n"
119
+ f"### Instruction:\n"
120
+ f"Please answer the following question based on the above context. Your answer should be concise and directly address the question. "
121
+ f"If the question is unanswerable based on the given context, respond with 'unanswerable'.\n\n"
122
+ f"### Question:\n{question}\n"
123
+ "<|eot_id|>\n"
124
+ "<|start_header_id|>assistant<|end_header_id|>\n"
125
+ )
126
+ return prompt
127
+ except Exception as e:
128
+ raise RuntimeError(f"Error creating prompt: {e}")
129
+
130
+
131
+ def answer_questions_from_web(url, question, collection_name, client):
132
+ """Answer questions by querying WatsonX with relevant context."""
133
+ model = get_model(MODEL_PARAMS)
134
+ prompt = create_prompt(url, question, collection_name, client)
135
+ generated_response = model.generate(prompt=prompt)
136
+ return generated_response["results"][0]["generated_text"].strip()
137
+
138
+
139
+ def main():
140
+ """Main function to run the RAG process."""
141
+ client = chromadb_client()
142
+ url = "https://huggingface.co/learn/nlp-course/chapter1/2?fw=pt"
143
+ question = "What is NLP?"
144
+ collection_name = "test_web_RAG"
145
+ response = answer_questions_from_web(url, question, collection_name, client)
146
+ print("Generated Response:")
147
+ print(response)
148
+
149
+
150
+ if __name__ == "__main__":
151
+ main()