Spaces:
Running
Running
Commit
·
35dac1d
0
Parent(s):
First commit
Browse files- .envTemplate +2 -0
- .gitignore +196 -0
- README.md +125 -0
- env.bat +1 -0
- env.sh +1 -0
- streamlit_webchat.py +51 -0
- webchat.py +221 -0
.envTemplate
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
API_KEY=your_api_key
|
2 |
+
PROJECT_ID=your_project_id
|
.gitignore
ADDED
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
.env
|
3 |
+
### Python ###
|
4 |
+
# Byte-compiled / optimized / DLL files
|
5 |
+
__pycache__/
|
6 |
+
*.py[cod]
|
7 |
+
*$py.class
|
8 |
+
|
9 |
+
# C extensions
|
10 |
+
*.so
|
11 |
+
|
12 |
+
# Distribution / packaging
|
13 |
+
.Python
|
14 |
+
build/
|
15 |
+
develop-eggs/
|
16 |
+
dist/
|
17 |
+
downloads/
|
18 |
+
eggs/
|
19 |
+
.eggs/
|
20 |
+
lib/
|
21 |
+
lib64/
|
22 |
+
parts/
|
23 |
+
sdist/
|
24 |
+
var/
|
25 |
+
wheels/
|
26 |
+
share/python-wheels/
|
27 |
+
*.egg-info/
|
28 |
+
.installed.cfg
|
29 |
+
*.egg
|
30 |
+
MANIFEST
|
31 |
+
|
32 |
+
# PyInstaller
|
33 |
+
# Usually these files are written by a python script from a template
|
34 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
35 |
+
*.manifest
|
36 |
+
*.spec
|
37 |
+
|
38 |
+
# Installer logs
|
39 |
+
pip-log.txt
|
40 |
+
pip-delete-this-directory.txt
|
41 |
+
|
42 |
+
# Unit test / coverage reports
|
43 |
+
htmlcov/
|
44 |
+
.tox/
|
45 |
+
.nox/
|
46 |
+
.coverage
|
47 |
+
.coverage.*
|
48 |
+
.cache
|
49 |
+
nosetests.xml
|
50 |
+
coverage.xml
|
51 |
+
*.cover
|
52 |
+
*.py,cover
|
53 |
+
.hypothesis/
|
54 |
+
.pytest_cache/
|
55 |
+
cover/
|
56 |
+
|
57 |
+
# Translations
|
58 |
+
*.mo
|
59 |
+
*.pot
|
60 |
+
|
61 |
+
# Django stuff:
|
62 |
+
*.log
|
63 |
+
local_settings.py
|
64 |
+
db.sqlite3
|
65 |
+
db.sqlite3-journal
|
66 |
+
|
67 |
+
# Flask stuff:
|
68 |
+
instance/
|
69 |
+
.webassets-cache
|
70 |
+
|
71 |
+
# Scrapy stuff:
|
72 |
+
.scrapy
|
73 |
+
|
74 |
+
# Sphinx documentation
|
75 |
+
docs/_build/
|
76 |
+
|
77 |
+
# PyBuilder
|
78 |
+
.pybuilder/
|
79 |
+
target/
|
80 |
+
|
81 |
+
# Jupyter Notebook
|
82 |
+
.ipynb_checkpoints
|
83 |
+
|
84 |
+
# IPython
|
85 |
+
profile_default/
|
86 |
+
ipython_config.py
|
87 |
+
|
88 |
+
.venv/
|
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 |
+
# pdm
|
109 |
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
110 |
+
#pdm.lock
|
111 |
+
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
112 |
+
# in version control.
|
113 |
+
# https://pdm.fming.dev/#use-with-ide
|
114 |
+
.pdm.toml
|
115 |
+
|
116 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
117 |
+
__pypackages__/
|
118 |
+
|
119 |
+
# Celery stuff
|
120 |
+
celerybeat-schedule
|
121 |
+
celerybeat.pid
|
122 |
+
|
123 |
+
# SageMath parsed files
|
124 |
+
*.sage.py
|
125 |
+
|
126 |
+
# Environments
|
127 |
+
.env
|
128 |
+
.venv
|
129 |
+
env/
|
130 |
+
venv/
|
131 |
+
ENV/
|
132 |
+
env.bak/
|
133 |
+
venv.bak/
|
134 |
+
|
135 |
+
# Spyder project settings
|
136 |
+
.spyderproject
|
137 |
+
.spyproject
|
138 |
+
|
139 |
+
# Rope project settings
|
140 |
+
.ropeproject
|
141 |
+
|
142 |
+
# mkdocs documentation
|
143 |
+
/site
|
144 |
+
|
145 |
+
# mypy
|
146 |
+
.mypy_cache/
|
147 |
+
.dmypy.json
|
148 |
+
dmypy.json
|
149 |
+
|
150 |
+
# Pyre type checker
|
151 |
+
.pyre/
|
152 |
+
|
153 |
+
# pytype static type analyzer
|
154 |
+
.pytype/
|
155 |
+
|
156 |
+
# Cython debug symbols
|
157 |
+
cython_debug/
|
158 |
+
|
159 |
+
# PyCharm
|
160 |
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
161 |
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
162 |
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
163 |
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
164 |
+
#.idea/
|
165 |
+
|
166 |
+
### Python Patch ###
|
167 |
+
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
|
168 |
+
poetry.toml
|
169 |
+
|
170 |
+
# ruff
|
171 |
+
.ruff_cache/
|
172 |
+
|
173 |
+
# LSP config files
|
174 |
+
pyrightconfig.json
|
175 |
+
|
176 |
+
### VisualStudioCode ###
|
177 |
+
.vscode/*
|
178 |
+
!.vscode/settings.json
|
179 |
+
!.vscode/tasks.json
|
180 |
+
!.vscode/launch.json
|
181 |
+
!.vscode/extensions.json
|
182 |
+
!.vscode/*.code-snippets
|
183 |
+
|
184 |
+
# Local History for Visual Studio Code
|
185 |
+
.history/
|
186 |
+
|
187 |
+
# Built Visual Studio Code Extensions
|
188 |
+
*.vsix
|
189 |
+
|
190 |
+
### VisualStudioCode Patch ###
|
191 |
+
# Ignore all local history of files
|
192 |
+
.history
|
193 |
+
.ionide
|
194 |
+
|
195 |
+
# End of https://www.toptal.com/developers/gitignore/api/visualstudiocode,python
|
196 |
+
Untitled.java
|
README.md
ADDED
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
51 |
+
```
|
52 |
+
|
53 |
+
IMPORTANT: Be aware of the disk space that will be taken up by documents when they're loaded into
|
54 |
+
chromadb on your laptop. The size in chroma will likely be the same as .txt file size
|
55 |
+
|
56 |
+
|
57 |
+
|
58 |
+
|
59 |
+
## Step 3: Getting API from IBM Cloud
|
60 |
+
|
61 |
+
### Obtaining an API Key
|
62 |
+
|
63 |
+
To obtain an API key from IBM Cloud, follow these steps:
|
64 |
+
|
65 |
+
1. **Sign In**
|
66 |
+
- Go to [IBM Cloud](https://cloud.ibm.com) and sign in to your account.
|
67 |
+
|
68 |
+
2. **Navigate to Account Settings**
|
69 |
+
- Click on your account name in the top right corner of the IBM Cloud dashboard.
|
70 |
+
- From the dropdown menu, select "Manage" to go to the Account settings.
|
71 |
+
|
72 |
+
3. **Access API Keys**
|
73 |
+
- In the left-hand menu, click on “IBM Cloud API keys” under the “Access (IAM)” section.
|
74 |
+
|
75 |
+
4. **Create an API Key**
|
76 |
+
- On the “API keys” page, click on the “Create an IBM Cloud API key” button.
|
77 |
+
- Provide a name and an optional description for your API key.
|
78 |
+
- Select the appropriate access policies if needed.
|
79 |
+
- Click on the “Create” button to generate the API key.
|
80 |
+
|
81 |
+
5. **Save Your API Key**
|
82 |
+
- Once the API key is created, a dialog box displaying the API key value will appear.
|
83 |
+
- Make sure to copy and save this key as it will not be shown again.
|
84 |
+
|
85 |
+
> 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.
|
86 |
+
|
87 |
+
### Retrieving the Project ID for IBM Watsonx
|
88 |
+
|
89 |
+
To obtain the Project ID for IBM Watsonx, you will need access to the IBM Watson Machine Learning (WML) service. Follow these steps:
|
90 |
+
|
91 |
+
1. **Log In**
|
92 |
+
- Log in to the [IBM Cloud Console](https://cloud.ibm.com) using your IBM Cloud credentials.
|
93 |
+
|
94 |
+
2. **Navigate to Watson Machine Learning**
|
95 |
+
- Go to the Watson Machine Learning service.
|
96 |
+
|
97 |
+
3. **Access Service Instance**
|
98 |
+
- Click on the service instance associated with your Watsonx project.
|
99 |
+
|
100 |
+
4. **Find Service Credentials**
|
101 |
+
- In the left-hand menu, click on “Service credentials”.
|
102 |
+
- Under the “Credentials” tab, you will find a list of service credentials associated with your Watsonx project.
|
103 |
+
|
104 |
+
5. **Retrieve Project ID**
|
105 |
+
- Click on the name of the service credential you want to use.
|
106 |
+
- In the JSON object, find the “project_id” field. The value of this field is your Project ID.
|
107 |
+
|
108 |
+
### Adding Credentials to Your Project
|
109 |
+
|
110 |
+
Add the API key and Project ID to the `.env` file in your project directory:
|
111 |
+
|
112 |
+
```plaintext
|
113 |
+
API_KEY=your_api_key
|
114 |
+
PROJECT_ID=your_project_id
|
115 |
+
```
|
116 |
+
|
117 |
+
This will configure your project to connect to Watsonx.ai using the obtained credentials.
|
118 |
+
|
119 |
+
Step 4: Creation of app.py
|
120 |
+
|
121 |
+
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)
|
122 |
+
This example shows a Question and Answer use case for a provided web site
|
123 |
+
|
124 |
+
|
125 |
+
|
env.bat
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
.venv\Scripts\activate.bat
|
env.sh
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
source .venv/Scripts/activate
|
streamlit_webchat.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("🌠Demo of RAG with a Web page")
|
32 |
+
|
33 |
+
user_url = st.text_input('Provide a URL')
|
34 |
+
|
35 |
+
collection_name = st.text_input('Provide a unique name for this website (lower case). Use the same name for the same URL to avoid loading data multiple times.')
|
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 |
+
|
webchat.py
ADDED
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# Important: hardcoding the API key in Python code is not a best practice. We are using
|
20 |
+
# this approach for the ease of demo setup. In a production application these variables
|
21 |
+
# can be stored in an .env or a properties file
|
22 |
+
|
23 |
+
# URL of the hosted LLMs is hardcoded because at this time all LLMs share the same endpoint
|
24 |
+
url = "https://us-south.ml.cloud.ibm.com"
|
25 |
+
|
26 |
+
# These global variables will be updated in get_credentials() function
|
27 |
+
watsonx_project_id = ""
|
28 |
+
# Replace with your IBM Cloud key
|
29 |
+
api_key = ""
|
30 |
+
|
31 |
+
def get_credentials():
|
32 |
+
|
33 |
+
load_dotenv()
|
34 |
+
# Update the global variables that will be used for authentication in another function
|
35 |
+
globals()["api_key"] = os.getenv("api_key", None)
|
36 |
+
globals()["watsonx_project_id"] = os.getenv("project_id", None)
|
37 |
+
|
38 |
+
# The get_model function creates an LLM model object with the specified parameters
|
39 |
+
|
40 |
+
def get_model(model_type, max_tokens, min_tokens, decoding, temperature, top_k, top_p):
|
41 |
+
generate_params = {
|
42 |
+
GenParams.MAX_NEW_TOKENS: max_tokens,
|
43 |
+
GenParams.MIN_NEW_TOKENS: min_tokens,
|
44 |
+
GenParams.DECODING_METHOD: decoding,
|
45 |
+
GenParams.TEMPERATURE: temperature,
|
46 |
+
GenParams.TOP_K: top_k,
|
47 |
+
GenParams.TOP_P: top_p,
|
48 |
+
}
|
49 |
+
|
50 |
+
model = Model(
|
51 |
+
model_id=model_type,
|
52 |
+
params=generate_params,
|
53 |
+
credentials={
|
54 |
+
"apikey": api_key,
|
55 |
+
"url": url
|
56 |
+
},
|
57 |
+
project_id=watsonx_project_id
|
58 |
+
)
|
59 |
+
|
60 |
+
return model
|
61 |
+
|
62 |
+
def get_model_test(model_type, max_tokens, min_tokens, decoding, temperature):
|
63 |
+
generate_params = {
|
64 |
+
GenParams.MAX_NEW_TOKENS: max_tokens,
|
65 |
+
GenParams.MIN_NEW_TOKENS: min_tokens,
|
66 |
+
GenParams.DECODING_METHOD: decoding,
|
67 |
+
GenParams.TEMPERATURE: temperature
|
68 |
+
}
|
69 |
+
|
70 |
+
model = Model(
|
71 |
+
model_id=model_type,
|
72 |
+
params=generate_params,
|
73 |
+
credentials={
|
74 |
+
"apikey": api_key,
|
75 |
+
"url": url
|
76 |
+
},
|
77 |
+
project_id=watsonx_project_id
|
78 |
+
)
|
79 |
+
|
80 |
+
return model
|
81 |
+
|
82 |
+
|
83 |
+
# Embedding function
|
84 |
+
class MiniLML6V2EmbeddingFunction(EmbeddingFunction):
|
85 |
+
MODEL = SentenceTransformer('all-MiniLM-L6-v2')
|
86 |
+
|
87 |
+
def __call__(self, texts):
|
88 |
+
return MiniLML6V2EmbeddingFunction.MODEL.encode(texts).tolist()
|
89 |
+
|
90 |
+
|
91 |
+
def extract_text(url):
|
92 |
+
try:
|
93 |
+
# Send an HTTP GET request to the URL
|
94 |
+
response = requests.get(url)
|
95 |
+
|
96 |
+
# Check if the request was successful
|
97 |
+
if response.status_code == 200:
|
98 |
+
# Parse the HTML content of the page using BeautifulSoup
|
99 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
100 |
+
|
101 |
+
# Extract contents of <p> elements
|
102 |
+
p_contents = [p.get_text() for p in soup.find_all('p')]
|
103 |
+
|
104 |
+
# Print the contents of <p> elements
|
105 |
+
print("\nContents of <p> elements: \n")
|
106 |
+
for content in p_contents:
|
107 |
+
print(content)
|
108 |
+
raw_web_text = " ".join(p_contents)
|
109 |
+
# remove \xa0 which is used in html to avoid words break acorss lines.
|
110 |
+
cleaned_text = raw_web_text.replace("\xa0", " ")
|
111 |
+
return cleaned_text
|
112 |
+
|
113 |
+
else:
|
114 |
+
print(f"Failed to retrieve the page. Status code: {response.status_code}")
|
115 |
+
|
116 |
+
except Exception as e:
|
117 |
+
print(f"An error occurred: {str(e)}")
|
118 |
+
|
119 |
+
|
120 |
+
def split_text_into_sentences(text):
|
121 |
+
nlp = spacy.load("en_core_web_md")
|
122 |
+
doc = nlp(text)
|
123 |
+
sentences = [sent.text for sent in doc.sents]
|
124 |
+
cleaned_sentences = [s.strip() for s in sentences]
|
125 |
+
return cleaned_sentences
|
126 |
+
|
127 |
+
|
128 |
+
def create_embedding(url, collection_name):
|
129 |
+
cleaned_text = extract_text(url)
|
130 |
+
cleaned_sentences = split_text_into_sentences(cleaned_text)
|
131 |
+
|
132 |
+
client = chromadb.Client()
|
133 |
+
|
134 |
+
collection = client.get_or_create_collection(collection_name)
|
135 |
+
|
136 |
+
# Upload text to chroma
|
137 |
+
collection.upsert(
|
138 |
+
documents=cleaned_sentences,
|
139 |
+
metadatas=[{"source": str(i)} for i in range(len(cleaned_sentences))],
|
140 |
+
ids=[str(i) for i in range(len(cleaned_sentences))],
|
141 |
+
)
|
142 |
+
|
143 |
+
return collection
|
144 |
+
|
145 |
+
|
146 |
+
def create_prompt(url, question, collection_name):
|
147 |
+
# Create embeddings for the text file
|
148 |
+
collection = create_embedding(url, collection_name)
|
149 |
+
|
150 |
+
# query relevant information
|
151 |
+
relevant_chunks = collection.query(
|
152 |
+
query_texts=[question],
|
153 |
+
n_results=5,
|
154 |
+
)
|
155 |
+
context = "\n\n\n".join(relevant_chunks["documents"][0])
|
156 |
+
# Please note that this is a generic format. You can change this format to be specific to llama
|
157 |
+
prompt = (f"{context}\n\nPlease answer the following question in one sentence using this "
|
158 |
+
+ f"text. "
|
159 |
+
+ f"If the question is unanswerable, say \"unanswerable\". Do not include information that's not relevant to the question."
|
160 |
+
+ f"Question: {question}")
|
161 |
+
|
162 |
+
return prompt
|
163 |
+
|
164 |
+
|
165 |
+
def main():
|
166 |
+
|
167 |
+
# Get the API key and project id and update global variables
|
168 |
+
get_credentials()
|
169 |
+
|
170 |
+
# Try diffrent URLs and questions
|
171 |
+
url = "https://www.usbank.com/financialiq/manage-your-household/buy-a-car/own-electric-vehicles-learned-buying-driving-EVs.html"
|
172 |
+
|
173 |
+
question = "What are the incentives for purchasing EVs?"
|
174 |
+
# question = "What is the percentage of driving powered by hybrid cars?"
|
175 |
+
# question = "Can an EV be plugged in to a household outlet?"
|
176 |
+
collection_name = "test_web_RAG"
|
177 |
+
|
178 |
+
answer_questions_from_web(api_key, watsonx_project_id, url, question, collection_name)
|
179 |
+
|
180 |
+
|
181 |
+
def answer_questions_from_web(request_api_key, request_project_id, url, question, collection_name):
|
182 |
+
# Update the global variable
|
183 |
+
globals()["api_key"] = request_api_key
|
184 |
+
globals()["watsonx_project_id"] = request_project_id
|
185 |
+
|
186 |
+
# Specify model parameters
|
187 |
+
model_type = "meta-llama/llama-2-70b-chat"
|
188 |
+
max_tokens = 100
|
189 |
+
min_tokens = 50
|
190 |
+
top_k = 50
|
191 |
+
top_p = 1
|
192 |
+
decoding = DecodingMethods.GREEDY
|
193 |
+
temperature = 0.7
|
194 |
+
|
195 |
+
# Get the watsonx model = try both options
|
196 |
+
model = get_model(model_type, max_tokens, min_tokens, decoding, temperature, top_k, top_p)
|
197 |
+
|
198 |
+
# Get the prompt
|
199 |
+
complete_prompt = create_prompt(url, question, collection_name)
|
200 |
+
|
201 |
+
# Let's review the prompt
|
202 |
+
print("----------------------------------------------------------------------------------------------------")
|
203 |
+
print("*** Prompt:" + complete_prompt + "***")
|
204 |
+
print("----------------------------------------------------------------------------------------------------")
|
205 |
+
|
206 |
+
generated_response = model.generate(prompt=complete_prompt)
|
207 |
+
response_text = generated_response['results'][0]['generated_text']
|
208 |
+
|
209 |
+
# Remove trailing white spaces
|
210 |
+
response_text = response_text.strip()
|
211 |
+
|
212 |
+
# print model response
|
213 |
+
print("--------------------------------- Generated response -----------------------------------")
|
214 |
+
print(response_text)
|
215 |
+
print("*********************************************************************************************")
|
216 |
+
|
217 |
+
return response_text
|
218 |
+
|
219 |
+
# Invoke the main function
|
220 |
+
if __name__ == "__main__":
|
221 |
+
main()
|