Spaces:
Build error
Build error
Merge remote-tracking branch 'upstream/main' into feat/refactor-csv
Browse files- .gitignore +0 -9
- .streamlit/config.toml +3 -5
- Procfile +1 -0
- README.md +13 -23
- requirements.txt +0 -0
- setup.sh +18 -0
- src/chatbot_csv.py +221 -0
- src/tuto_chatbot_csv.py +73 -0
.gitignore
CHANGED
|
@@ -153,13 +153,4 @@ cython_debug/
|
|
| 153 |
|
| 154 |
#venv
|
| 155 |
|
| 156 |
-
poto-associations-sample.csv.pkl
|
| 157 |
-
.chroma/index/uuid_to_id_f2b3bfe1-6ee9-4665-bbd5-20dcc1db40c7.pkl
|
| 158 |
-
.chroma/index/uuid_to_id_c44e4b69-0e90-41b5-8f83-9c1fd114daab.pkl
|
| 159 |
-
.chroma/index/index_metadata_f2b3bfe1-6ee9-4665-bbd5-20dcc1db40c7.pkl
|
| 160 |
-
.chroma/index/index_metadata_c44e4b69-0e90-41b5-8f83-9c1fd114daab.pkl
|
| 161 |
-
.chroma/index/index_f2b3bfe1-6ee9-4665-bbd5-20dcc1db40c7.bin
|
| 162 |
-
.chroma/index/index_c44e4b69-0e90-41b5-8f83-9c1fd114daab.bin
|
| 163 |
-
.chroma/index/id_to_uuid_f2b3bfe1-6ee9-4665-bbd5-20dcc1db40c7.pkl
|
| 164 |
-
.chroma/index/id_to_uuid_c44e4b69-0e90-41b5-8f83-9c1fd114daab.pkl
|
| 165 |
*.pkl
|
|
|
|
| 153 |
|
| 154 |
#venv
|
| 155 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
*.pkl
|
.streamlit/config.toml
CHANGED
|
@@ -1,6 +1,4 @@
|
|
| 1 |
[theme]
|
| 2 |
-
base="light"
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
[browser]
|
| 6 |
-
gatherUsageStats = false
|
|
|
|
| 1 |
[theme]
|
| 2 |
+
base = "light"
|
| 3 |
+
backgroundColor = "#FFF1F9"
|
| 4 |
+
secondaryBackgroundColor = "#FFDCF1"
|
|
|
|
|
|
Procfile
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
web: sh setup.sh && streamlit run src/chatbot_csv.py
|
README.md
CHANGED
|
@@ -1,13 +1,14 @@
|
|
| 1 |
-
# ChatBot-
|
| 2 |
|
| 3 |
-
### An AI chatbot featuring conversational memory, designed to enable users to discuss their
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
###
|
| 6 |
-
|
| 7 |
-
#### This is a fork of [ChatBot-CSV](https://github.com/yvann-hub/ChatBot-CSV) by [yvann-hub](https://github.com/yvann-hub), many thanks to him for his work. π€
|
| 8 |
|
| 9 |
## Running Locally π»
|
| 10 |
-
|
| 11 |
Follow these steps to set up and run the service locally :
|
| 12 |
|
| 13 |
### Prerequisites
|
|
@@ -15,25 +16,17 @@ Follow these steps to set up and run the service locally :
|
|
| 15 |
- Git
|
| 16 |
|
| 17 |
### Installation
|
| 18 |
-
|
| 19 |
Clone the repository :
|
| 20 |
|
| 21 |
-
`git clone https://github.com/
|
| 22 |
|
| 23 |
-
Navigate to the project directory :
|
| 24 |
-
|
| 25 |
-
`cd ChatBot-PDF`
|
| 26 |
|
| 27 |
-
|
| 28 |
|
| 29 |
-
``
|
| 30 |
-
./launch.sh
|
| 31 |
-
```
|
| 32 |
|
| 33 |
-
Or if you are on Windows, or prefer to run the commands manually :
|
| 34 |
|
| 35 |
Create a virtual environment :
|
| 36 |
-
|
| 37 |
```bash
|
| 38 |
python -m venv .venv
|
| 39 |
.\.venv\Scripts\activate
|
|
@@ -43,17 +36,14 @@ Install the required dependencies in the virtual environment :
|
|
| 43 |
|
| 44 |
`pip install -r requirements.txt`
|
| 45 |
|
|
|
|
| 46 |
Launch the chat service locally :
|
| 47 |
|
| 48 |
-
`streamlit run
|
| 49 |
|
| 50 |
#### That's it! The service is now up and running locally. π€
|
| 51 |
|
| 52 |
## Contributing
|
|
|
|
| 53 |
|
| 54 |
-
Contributions are always welcome! If you want to contribute to this project, please open an issue or submit a pull request.
|
| 55 |
-
|
| 56 |
-
## License
|
| 57 |
-
|
| 58 |
-
This project is licensed under the MIT License - see the LICENSE file for details.
|
| 59 |
|
|
|
|
| 1 |
+
# ChatBot-CSV π€
|
| 2 |
|
| 3 |
+
### An AI chatbot featuring conversational memory, designed to enable users to discuss their CSV data in a more intuitive manner. π
|
| 4 |
+
#### By integrating the strengths of Langchain and OpenAI, ChatBot-CSV employs large language models to provide users with seamless, context-aware natural language interactions for a better understanding of their CSV data.π§
|
| 5 |
+
#### For better understanding, see my medium article π : [Build a chat-bot over your CSV data](https://medium.com/@yvann-ba/build-a-chatbot-on-your-csv-data-with-langchain-and-openai-ed121f85f0cd)
|
| 6 |
+
## Quick Start π
|
| 7 |
+
To use ChatBot-CSV, simply visit the following link :
|
| 8 |
|
| 9 |
+
### [chatbot-csv.com](https://chatbot-csv.com/)
|
|
|
|
|
|
|
| 10 |
|
| 11 |
## Running Locally π»
|
|
|
|
| 12 |
Follow these steps to set up and run the service locally :
|
| 13 |
|
| 14 |
### Prerequisites
|
|
|
|
| 16 |
- Git
|
| 17 |
|
| 18 |
### Installation
|
|
|
|
| 19 |
Clone the repository :
|
| 20 |
|
| 21 |
+
`git clone https://github.com/yvann-hub/ChatBot-CSV.git`
|
| 22 |
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
Navigate to the project directory :
|
| 25 |
|
| 26 |
+
`cd ChatBot-CSV`
|
|
|
|
|
|
|
| 27 |
|
|
|
|
| 28 |
|
| 29 |
Create a virtual environment :
|
|
|
|
| 30 |
```bash
|
| 31 |
python -m venv .venv
|
| 32 |
.\.venv\Scripts\activate
|
|
|
|
| 36 |
|
| 37 |
`pip install -r requirements.txt`
|
| 38 |
|
| 39 |
+
|
| 40 |
Launch the chat service locally :
|
| 41 |
|
| 42 |
+
`streamlit run src/chatbot_csv.py`
|
| 43 |
|
| 44 |
#### That's it! The service is now up and running locally. π€
|
| 45 |
|
| 46 |
## Contributing
|
| 47 |
+
Contributions are always welcome! If you want to contribute to this project, please open an issue or submit a pull request (:
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
requirements.txt
CHANGED
|
Binary files a/requirements.txt and b/requirements.txt differ
|
|
|
setup.sh
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
mkdir -p ~/.streamlit/
|
| 2 |
+
|
| 3 |
+
echo "\
|
| 4 |
+
[general]\n\
|
| 5 |
+
email = \"yyvannbarbotts@gmail.com\"\n\
|
| 6 |
+
" > ~/.streamlit/credentials.toml
|
| 7 |
+
|
| 8 |
+
echo "\
|
| 9 |
+
[server]\n\
|
| 10 |
+
headless = true\n\
|
| 11 |
+
enableCORS=false\n\
|
| 12 |
+
port = $PORT\n\
|
| 13 |
+
\n\
|
| 14 |
+
[theme]\n\
|
| 15 |
+
base = \"light\"\n\
|
| 16 |
+
backgroundColor = \"#FFF1F9\"\n\
|
| 17 |
+
secondaryBackgroundColor = \"#FFDCF1\"\n\
|
| 18 |
+
" > ~/.streamlit/config.toml
|
src/chatbot_csv.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import pickle
|
| 3 |
+
import streamlit as st
|
| 4 |
+
import tempfile
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import asyncio
|
| 7 |
+
|
| 8 |
+
from streamlit_chat import message
|
| 9 |
+
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 10 |
+
from langchain.chat_models import ChatOpenAI
|
| 11 |
+
from langchain.chains import ConversationalRetrievalChain
|
| 12 |
+
from langchain.document_loaders.csv_loader import CSVLoader
|
| 13 |
+
from langchain.vectorstores import FAISS
|
| 14 |
+
from langchain.prompts.prompt import PromptTemplate
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
st.set_page_config(layout="wide", page_icon="π¬", page_title="ChatBot-CSV")
|
| 18 |
+
|
| 19 |
+
st.markdown(
|
| 20 |
+
"<h1 style='text-align: center;'>ChatBot-CSV, Talk with your csv-data ! π¬</h1>",
|
| 21 |
+
unsafe_allow_html=True)
|
| 22 |
+
|
| 23 |
+
user_api_key = st.sidebar.text_input(
|
| 24 |
+
label="#### Your OpenAI API key π",
|
| 25 |
+
placeholder="Paste your openAI API key, sk-",
|
| 26 |
+
type="password")
|
| 27 |
+
|
| 28 |
+
async def main():
|
| 29 |
+
|
| 30 |
+
if user_api_key == "":
|
| 31 |
+
|
| 32 |
+
st.markdown(
|
| 33 |
+
"<div style='text-align: center;'><h4>Enter your OpenAI API key to start chatting π</h4></div>",
|
| 34 |
+
unsafe_allow_html=True)
|
| 35 |
+
|
| 36 |
+
else:
|
| 37 |
+
os.environ["OPENAI_API_KEY"] = user_api_key
|
| 38 |
+
|
| 39 |
+
uploaded_file = st.sidebar.file_uploader("upload", type="csv", label_visibility="hidden")
|
| 40 |
+
|
| 41 |
+
if uploaded_file is not None:
|
| 42 |
+
def show_user_file(uploaded_file):
|
| 43 |
+
file_container = st.expander("Your CSV file :")
|
| 44 |
+
shows = pd.read_csv(uploaded_file)
|
| 45 |
+
uploaded_file.seek(0)
|
| 46 |
+
file_container.write(shows)
|
| 47 |
+
|
| 48 |
+
show_user_file(uploaded_file)
|
| 49 |
+
|
| 50 |
+
else :
|
| 51 |
+
st.sidebar.info(
|
| 52 |
+
"π Upload your CSV file to get started, "
|
| 53 |
+
"sample for try : [fishfry-locations.csv](https://drive.google.com/file/d/18i7tN2CqrmoouaSqm3hDfAk17hmWx94e/view?usp=sharing)"
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
if uploaded_file :
|
| 57 |
+
try :
|
| 58 |
+
async def storeDocEmbeds(file, filename):
|
| 59 |
+
|
| 60 |
+
# Write the uploaded file to a temporary file
|
| 61 |
+
with tempfile.NamedTemporaryFile(mode="wb", delete=False) as tmp_file:
|
| 62 |
+
tmp_file.write(file)
|
| 63 |
+
tmp_file_path = tmp_file.name
|
| 64 |
+
|
| 65 |
+
# Load the data from the CSV file using Langchain
|
| 66 |
+
loader = CSVLoader(file_path=tmp_file_path, encoding="utf-8")
|
| 67 |
+
data = loader.load()
|
| 68 |
+
|
| 69 |
+
embeddings = OpenAIEmbeddings()
|
| 70 |
+
|
| 71 |
+
vectors = FAISS.from_documents(data, embeddings)
|
| 72 |
+
os.remove(tmp_file_path)
|
| 73 |
+
|
| 74 |
+
with open(filename + ".pkl", "wb") as f:
|
| 75 |
+
pickle.dump(vectors, f)
|
| 76 |
+
|
| 77 |
+
async def getDocEmbeds(file, filename):
|
| 78 |
+
|
| 79 |
+
if not os.path.isfile(filename + ".pkl"):
|
| 80 |
+
# If not, store the vectors using the storeDocEmbeds function
|
| 81 |
+
await storeDocEmbeds(file, filename)
|
| 82 |
+
|
| 83 |
+
with open(filename + ".pkl", "rb") as f:
|
| 84 |
+
#global vectors
|
| 85 |
+
vectors = pickle.load(f)
|
| 86 |
+
|
| 87 |
+
return vectors
|
| 88 |
+
|
| 89 |
+
async def conversational_chat(query):
|
| 90 |
+
|
| 91 |
+
# Use the Langchain ConversationalRetrievalChain to generate a response to the user's query
|
| 92 |
+
result = chain({"question": query, "chat_history": st.session_state['history']})
|
| 93 |
+
|
| 94 |
+
# Add the user's query and the chatbot's response to the chat history
|
| 95 |
+
st.session_state['history'].append((query, result["answer"]))
|
| 96 |
+
|
| 97 |
+
# You can print the chat history for debugging :
|
| 98 |
+
#print("Log: ")
|
| 99 |
+
#print(st.session_state['history'])
|
| 100 |
+
|
| 101 |
+
return result["answer"]
|
| 102 |
+
|
| 103 |
+
# Set up sidebar with various options
|
| 104 |
+
with st.sidebar.expander("π οΈ Settings", expanded=False):
|
| 105 |
+
|
| 106 |
+
# Add a button to reset the chat history
|
| 107 |
+
if st.button("Reset Chat"):
|
| 108 |
+
st.session_state['reset_chat'] = True
|
| 109 |
+
|
| 110 |
+
# Allow the user to select a chatbot model to use
|
| 111 |
+
MODEL = st.selectbox(label='Model', options=['gpt-3.5-turbo','gpt-4'])
|
| 112 |
+
|
| 113 |
+
if 'history' not in st.session_state:
|
| 114 |
+
st.session_state['history'] = []
|
| 115 |
+
|
| 116 |
+
if 'ready' not in st.session_state:
|
| 117 |
+
st.session_state['ready'] = False
|
| 118 |
+
|
| 119 |
+
if 'reset_chat' not in st.session_state:
|
| 120 |
+
st.session_state['reset_chat'] = False
|
| 121 |
+
|
| 122 |
+
if uploaded_file is not None:
|
| 123 |
+
|
| 124 |
+
# Display a spinner while processing the file
|
| 125 |
+
with st.spinner("Processing..."):
|
| 126 |
+
|
| 127 |
+
uploaded_file.seek(0)
|
| 128 |
+
file = uploaded_file.read()
|
| 129 |
+
|
| 130 |
+
# Generate embeddings vectors for the file
|
| 131 |
+
vectors = await getDocEmbeds(file, uploaded_file.name)
|
| 132 |
+
|
| 133 |
+
_template = """Given the following conversation and a follow-up question, rephrase the follow-up question to be a stand-alone question.
|
| 134 |
+
You can assume that the question is about the information in a CSV file.
|
| 135 |
+
Chat History:
|
| 136 |
+
{chat_history}
|
| 137 |
+
Follow-up entry: {question}
|
| 138 |
+
Standalone question:"""
|
| 139 |
+
CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(_template)
|
| 140 |
+
|
| 141 |
+
qa_template = """"You are an AI conversational assistant to answer questions based on information from a csv file.
|
| 142 |
+
You are given data from a csv file and a question, you must help the user find the information they need.
|
| 143 |
+
Only give responses for information you know about. Don't try to make up an answer.
|
| 144 |
+
Your answers should be short,friendly, in the same language.
|
| 145 |
+
question: {question}
|
| 146 |
+
=========
|
| 147 |
+
{context}
|
| 148 |
+
=======
|
| 149 |
+
"""
|
| 150 |
+
QA_PROMPT = PromptTemplate(template=qa_template, input_variables=["question", "context"])
|
| 151 |
+
|
| 152 |
+
chain = ConversationalRetrievalChain.from_llm(llm = ChatOpenAI(temperature=0.0,model_name=MODEL),
|
| 153 |
+
condense_question_prompt=CONDENSE_QUESTION_PROMPT,qa_prompt=QA_PROMPT,retriever=vectors.as_retriever())
|
| 154 |
+
|
| 155 |
+
# Set the "ready" flag to True now that the chatbot is ready to chat
|
| 156 |
+
st.session_state['ready'] = True
|
| 157 |
+
|
| 158 |
+
if st.session_state['ready']:
|
| 159 |
+
|
| 160 |
+
# If the chat history has not yet been initialized, initialize it now
|
| 161 |
+
if 'generated' not in st.session_state:
|
| 162 |
+
st.session_state['generated'] = ["Hello ! Ask me anything about " + uploaded_file.name + " π€"]
|
| 163 |
+
|
| 164 |
+
if 'past' not in st.session_state:
|
| 165 |
+
st.session_state['past'] = ["Hey ! π"]
|
| 166 |
+
|
| 167 |
+
#container for displaying the chat history
|
| 168 |
+
response_container = st.container()
|
| 169 |
+
|
| 170 |
+
#container for the user's text input
|
| 171 |
+
container = st.container()
|
| 172 |
+
|
| 173 |
+
with container:
|
| 174 |
+
|
| 175 |
+
# Create a form for the user to enter their query
|
| 176 |
+
with st.form(key='my_form', clear_on_submit=True):
|
| 177 |
+
|
| 178 |
+
user_input = st.text_input("Query:", placeholder="Talk about your csv data here (:", key='input')
|
| 179 |
+
submit_button = st.form_submit_button(label='Send')
|
| 180 |
+
|
| 181 |
+
# If the "reset_chat" flag has been set, reset the chat history and generated messages
|
| 182 |
+
if st.session_state['reset_chat']:
|
| 183 |
+
|
| 184 |
+
st.session_state['history'] = []
|
| 185 |
+
st.session_state['past'] = ["Hey ! π"]
|
| 186 |
+
st.session_state['generated'] = ["Hello ! Ask me anything about " + uploaded_file.name + " π€"]
|
| 187 |
+
response_container.empty()
|
| 188 |
+
st.session_state['reset_chat'] = False
|
| 189 |
+
|
| 190 |
+
if submit_button and user_input:
|
| 191 |
+
|
| 192 |
+
# Generate a response using the Langchain ConversationalRetrievalChain
|
| 193 |
+
output = await conversational_chat(user_input)
|
| 194 |
+
|
| 195 |
+
# Add the user's input and the chatbot's output to the chat history
|
| 196 |
+
st.session_state['past'].append(user_input)
|
| 197 |
+
st.session_state['generated'].append(output)
|
| 198 |
+
|
| 199 |
+
if st.session_state['generated']:
|
| 200 |
+
|
| 201 |
+
# Display the chat history
|
| 202 |
+
with response_container:
|
| 203 |
+
|
| 204 |
+
for i in range(len(st.session_state['generated'])):
|
| 205 |
+
message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="big-smile")
|
| 206 |
+
message(st.session_state["generated"][i], key=str(i), avatar_style="thumbs")
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
except Exception as e:
|
| 210 |
+
st.error(f"Error: {str(e)}")
|
| 211 |
+
|
| 212 |
+
about = st.sidebar.expander("About π€")
|
| 213 |
+
about.write("#### ChatBot-CSV is an AI chatbot featuring conversational memory, designed to enable users to discuss their CSV data in a more intuitive manner. π")
|
| 214 |
+
about.write("#### He employs large language models to provide users with seamless, context-aware natural language interactions for a better understanding of their CSV data. π")
|
| 215 |
+
about.write("#### Powered by [Langchain](https://github.com/hwchase17/langchain), [OpenAI](https://platform.openai.com/docs/models/gpt-3-5) and [Streamlit](https://github.com/streamlit/streamlit) β‘")
|
| 216 |
+
about.write("#### Source code : [yvann-hub/ChatBot-CSV](https://github.com/yvann-hub/ChatBot-CSV)")
|
| 217 |
+
|
| 218 |
+
#Run the main function using asyncio
|
| 219 |
+
if __name__ == "__main__":
|
| 220 |
+
asyncio.run(main())
|
| 221 |
+
|
src/tuto_chatbot_csv.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#pip install streamlit langchain openai fais-cpu tiktoken
|
| 2 |
+
|
| 3 |
+
import streamlit as st
|
| 4 |
+
from streamlit_chat import message
|
| 5 |
+
from langchain.embeddings.openai import OpenAIEmbeddings
|
| 6 |
+
from langchain.chat_models import ChatOpenAI
|
| 7 |
+
from langchain.chains import ConversationalRetrievalChain
|
| 8 |
+
from langchain.document_loaders.csv_loader import CSVLoader
|
| 9 |
+
from langchain.vectorstores import FAISS
|
| 10 |
+
import tempfile
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
user_api_key = st.sidebar.text_input(
|
| 14 |
+
label="#### Your OpenAI API key π",
|
| 15 |
+
placeholder="Paste your openAI API key, sk-",
|
| 16 |
+
type="password")
|
| 17 |
+
|
| 18 |
+
uploaded_file = st.sidebar.file_uploader("upload", type="csv")
|
| 19 |
+
|
| 20 |
+
if uploaded_file :
|
| 21 |
+
with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
|
| 22 |
+
tmp_file.write(uploaded_file.getvalue())
|
| 23 |
+
tmp_file_path = tmp_file.name
|
| 24 |
+
|
| 25 |
+
loader = CSVLoader(file_path=tmp_file_path, encoding="utf-8")
|
| 26 |
+
data = loader.load()
|
| 27 |
+
|
| 28 |
+
embeddings = OpenAIEmbeddings()
|
| 29 |
+
vectors = FAISS.from_documents(data, embeddings)
|
| 30 |
+
|
| 31 |
+
chain = ConversationalRetrievalChain.from_llm(llm = ChatOpenAI(temperature=0.0,model_name='gpt-3.5-turbo', openai_api_key=user_api_key),
|
| 32 |
+
retriever=vectors.as_retriever())
|
| 33 |
+
|
| 34 |
+
def conversational_chat(query):
|
| 35 |
+
|
| 36 |
+
result = chain({"question": query, "chat_history": st.session_state['history']})
|
| 37 |
+
st.session_state['history'].append((query, result["answer"]))
|
| 38 |
+
|
| 39 |
+
return result["answer"]
|
| 40 |
+
|
| 41 |
+
if 'history' not in st.session_state:
|
| 42 |
+
st.session_state['history'] = []
|
| 43 |
+
|
| 44 |
+
if 'generated' not in st.session_state:
|
| 45 |
+
st.session_state['generated'] = ["Hello ! Ask me anything about " + uploaded_file.name + " π€"]
|
| 46 |
+
|
| 47 |
+
if 'past' not in st.session_state:
|
| 48 |
+
st.session_state['past'] = ["Hey ! π"]
|
| 49 |
+
|
| 50 |
+
#container for the chat history
|
| 51 |
+
response_container = st.container()
|
| 52 |
+
#container for the user's text input
|
| 53 |
+
container = st.container()
|
| 54 |
+
|
| 55 |
+
with container:
|
| 56 |
+
with st.form(key='my_form', clear_on_submit=True):
|
| 57 |
+
|
| 58 |
+
user_input = st.text_input("Query:", placeholder="Talk about your csv data here (:", key='input')
|
| 59 |
+
submit_button = st.form_submit_button(label='Send')
|
| 60 |
+
|
| 61 |
+
if submit_button and user_input:
|
| 62 |
+
output = conversational_chat(user_input)
|
| 63 |
+
|
| 64 |
+
st.session_state['past'].append(user_input)
|
| 65 |
+
st.session_state['generated'].append(output)
|
| 66 |
+
|
| 67 |
+
if st.session_state['generated']:
|
| 68 |
+
with response_container:
|
| 69 |
+
for i in range(len(st.session_state['generated'])):
|
| 70 |
+
message(st.session_state["past"][i], is_user=True, key=str(i) + '_user', avatar_style="big-smile")
|
| 71 |
+
message(st.session_state["generated"][i], key=str(i), avatar_style="thumbs")
|
| 72 |
+
|
| 73 |
+
#streamlit run tuto_chatbot_csv.py
|