# SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# This is a simple standalone implementation showing rag pipeline using Nvidia AI Foundational models.
# It uses a simple Streamlit UI and one file implementation of a minimalistic RAG pipeline.

############################################
# Component #1 - Document Loader
############################################

import streamlit as st
import os

st.set_page_config(layout = "wide")

with st.sidebar:
    DOCS_DIR = os.path.abspath("./uploaded_docs")
    if not os.path.exists(DOCS_DIR):
        os.makedirs(DOCS_DIR)
    st.subheader("Add to the Knowledge Base")
    with st.form("my-form", clear_on_submit=True):
        uploaded_files = st.file_uploader("Upload a file to the Knowledge Base:", accept_multiple_files = True)
        submitted = st.form_submit_button("Upload!")

    if uploaded_files and submitted:
        for uploaded_file in uploaded_files:
            st.success(f"File {uploaded_file.name} uploaded successfully!")
            with open(os.path.join(DOCS_DIR, uploaded_file.name),"wb") as f:
                f.write(uploaded_file.read())

############################################
# Component #2 - Embedding Model and LLM
############################################

from langchain_nvidia_ai_endpoints import ChatNVIDIA, NVIDIAEmbeddings

# make sure to export your NVIDIA AI Playground key as NVIDIA_API_KEY!
llm = ChatNVIDIA(model="mixtral_8x7b")
document_embedder = NVIDIAEmbeddings(model="nvolveqa_40k", model_type="passage")
query_embedder = NVIDIAEmbeddings(model="nvolveqa_40k", model_type="query")

############################################
# Component #3 - Vector Database Store
############################################

from langchain.text_splitter import CharacterTextSplitter
from langchain.document_loaders import DirectoryLoader
from langchain.vectorstores import FAISS
import pickle

with st.sidebar:
    # Option for using an existing vector store
    use_existing_vector_store = st.radio("Use existing vector store if available", ["Yes", "No"], horizontal=True)

# Path to the vector store file
vector_store_path = "vectorstore.pkl"

# Load raw documents from the directory
raw_documents = DirectoryLoader(DOCS_DIR).load()


# Check for existing vector store file
vector_store_exists = os.path.exists(vector_store_path)
vectorstore = None
if use_existing_vector_store == "Yes" and vector_store_exists:
    with open(vector_store_path, "rb") as f:
        vectorstore = pickle.load(f)
    with st.sidebar:
        st.success("Existing vector store loaded successfully.")
else:
    with st.sidebar:
        if raw_documents:
            with st.spinner("Splitting documents into chunks..."):
                text_splitter = CharacterTextSplitter(chunk_size=2000, chunk_overlap=200)
                documents = text_splitter.split_documents(raw_documents)

            with st.spinner("Adding document chunks to vector database..."):
                vectorstore = FAISS.from_documents(documents, document_embedder)

            with st.spinner("Saving vector store"):
                with open(vector_store_path, "wb") as f:
                    pickle.dump(vectorstore, f)
            st.success("Vector store created and saved.")
        else:
            st.warning("No documents available to process!", icon="⚠️")

############################################
# Component #4 - LLM Response Generation and Chat
############################################

st.subheader("Chat with your AI Assistant, Envie!")

if "messages" not in st.session_state:
    st.session_state.messages = []

for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.markdown(message["content"])

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

prompt_template = ChatPromptTemplate.from_messages(
    [("system", "You are a helpful AI assistant named Envie. You will reply to questions only based on the context that you are provided. If something is out of context, you will refrain from replying and politely decline to respond to the user."), ("user", "{input}")]
)
user_input = st.chat_input("Can you tell me what NVIDIA is known for?")
llm = ChatNVIDIA(model="mixtral_8x7b")

chain = prompt_template | llm | StrOutputParser()

if user_input and vectorstore!=None:
    st.session_state.messages.append({"role": "user", "content": user_input})
    retriever = vectorstore.as_retriever()
    docs = retriever.get_relevant_documents(user_input)
    with st.chat_message("user"):
        st.markdown(user_input)

    context = ""
    for doc in docs:
        context += doc.page_content + "\n\n"

    augmented_user_input = "Context: " + context + "\n\nQuestion: " + user_input + "\n"

    with st.chat_message("assistant"):
        message_placeholder = st.empty()
        full_response = ""

        for response in chain.stream({"input": augmented_user_input}):
            full_response += response
            message_placeholder.markdown(full_response + "▌")
        message_placeholder.markdown(full_response)
    st.session_state.messages.append({"role": "assistant", "content": full_response})

langchain.text_splitter.CharacterTextSplitter langchain.document_loaders.DirectoryLoader langchain_core.output_parsers.StrOutputParser langchain.vectorstores.FAISS.from_documents langchain_core.prompts.ChatPromptTemplate.from_messages langchain_nvidia_ai_endpoints.NVIDIAEmbeddings langchain_nvidia_ai_endpoints.ChatNVIDIA
[((1034, 1067), 'streamlit.set_page_config', 'st.set_page_config', ([], {'layout': '"""wide"""'}), "(layout='wide')\n", (1052, 1067), True, 'import streamlit as st\n'), ((2031, 2063), 'langchain_nvidia_ai_endpoints.ChatNVIDIA', 'ChatNVIDIA', ([], {'model': '"""mixtral_8x7b"""'}), "(model='mixtral_8x7b')\n", (2041, 2063), False, 'from langchain_nvidia_ai_endpoints import ChatNVIDIA, NVIDIAEmbeddings\n'), ((2084, 2144), 'langchain_nvidia_ai_endpoints.NVIDIAEmbeddings', 'NVIDIAEmbeddings', ([], {'model': '"""nvolveqa_40k"""', 'model_type': '"""passage"""'}), "(model='nvolveqa_40k', model_type='passage')\n", (2100, 2144), False, 'from langchain_nvidia_ai_endpoints import ChatNVIDIA, NVIDIAEmbeddings\n'), ((2162, 2220), 'langchain_nvidia_ai_endpoints.NVIDIAEmbeddings', 'NVIDIAEmbeddings', ([], {'model': '"""nvolveqa_40k"""', 'model_type': '"""query"""'}), "(model='nvolveqa_40k', model_type='query')\n", (2178, 2220), False, 'from langchain_nvidia_ai_endpoints import ChatNVIDIA, NVIDIAEmbeddings\n'), ((2925, 2958), 'os.path.exists', 'os.path.exists', (['vector_store_path'], {}), '(vector_store_path)\n', (2939, 2958), False, 'import os\n'), ((4095, 4146), 'streamlit.subheader', 'st.subheader', (['"""Chat with your AI Assistant, Envie!"""'], {}), "('Chat with your AI Assistant, Envie!')\n", (4107, 4146), True, 'import streamlit as st\n'), ((4480, 4788), 'langchain_core.prompts.ChatPromptTemplate.from_messages', 'ChatPromptTemplate.from_messages', (["[('system',\n    'You are a helpful AI assistant named Envie. You will reply to questions only based on the context that you are provided. If something is out of context, you will refrain from replying and politely decline to respond to the user.'\n    ), ('user', '{input}')]"], {}), "([('system',\n    'You are a helpful AI assistant named Envie. You will reply to questions only based on the context that you are provided. If something is out of context, you will refrain from replying and politely decline to respond to the user.'\n    ), ('user', '{input}')])\n", (4512, 4788), False, 'from langchain_core.prompts import ChatPromptTemplate\n'), ((4799, 4857), 'streamlit.chat_input', 'st.chat_input', (['"""Can you tell me what NVIDIA is known for?"""'], {}), "('Can you tell me what NVIDIA is known for?')\n", (4812, 4857), True, 'import streamlit as st\n'), ((4864, 4896), 'langchain_nvidia_ai_endpoints.ChatNVIDIA', 'ChatNVIDIA', ([], {'model': '"""mixtral_8x7b"""'}), "(model='mixtral_8x7b')\n", (4874, 4896), False, 'from langchain_nvidia_ai_endpoints import ChatNVIDIA, NVIDIAEmbeddings\n'), ((1103, 1137), 'os.path.abspath', 'os.path.abspath', (['"""./uploaded_docs"""'], {}), "('./uploaded_docs')\n", (1118, 1137), False, 'import os\n'), ((1209, 1250), 'streamlit.subheader', 'st.subheader', (['"""Add to the Knowledge Base"""'], {}), "('Add to the Knowledge Base')\n", (1221, 1250), True, 'import streamlit as st\n'), ((2618, 2704), 'streamlit.radio', 'st.radio', (['"""Use existing vector store if available"""', "['Yes', 'No']"], {'horizontal': '(True)'}), "('Use existing vector store if available', ['Yes', 'No'],\n    horizontal=True)\n", (2626, 2704), True, 'import streamlit as st\n'), ((4930, 4947), 'langchain_core.output_parsers.StrOutputParser', 'StrOutputParser', ([], {}), '()\n', (4945, 4947), False, 'from langchain_core.output_parsers import StrOutputParser\n'), ((4990, 5063), 'streamlit.session_state.messages.append', 'st.session_state.messages.append', (["{'role': 'user', 'content': user_input}"], {}), "({'role': 'user', 'content': user_input})\n", (5022, 5063), True, 'import streamlit as st\n'), ((5738, 5823), 'streamlit.session_state.messages.append', 'st.session_state.messages.append', (["{'role': 'assistant', 'content': full_response}"], {}), "({'role': 'assistant', 'content':\n    full_response})\n", (5770, 5823), True, 'import streamlit as st\n'), ((1149, 1173), 'os.path.exists', 'os.path.exists', (['DOCS_DIR'], {}), '(DOCS_DIR)\n', (1163, 1173), False, 'import os\n'), ((1183, 1204), 'os.makedirs', 'os.makedirs', (['DOCS_DIR'], {}), '(DOCS_DIR)\n', (1194, 1204), False, 'import os\n'), ((1260, 1300), 'streamlit.form', 'st.form', (['"""my-form"""'], {'clear_on_submit': '(True)'}), "('my-form', clear_on_submit=True)\n", (1267, 1300), True, 'import streamlit as st\n'), ((1327, 1415), 'streamlit.file_uploader', 'st.file_uploader', (['"""Upload a file to the Knowledge Base:"""'], {'accept_multiple_files': '(True)'}), "('Upload a file to the Knowledge Base:',\n    accept_multiple_files=True)\n", (1343, 1415), True, 'import streamlit as st\n'), ((1434, 1466), 'streamlit.form_submit_button', 'st.form_submit_button', (['"""Upload!"""'], {}), "('Upload!')\n", (1455, 1466), True, 'import streamlit as st\n'), ((2829, 2854), 'langchain.document_loaders.DirectoryLoader', 'DirectoryLoader', (['DOCS_DIR'], {}), '(DOCS_DIR)\n', (2844, 2854), False, 'from langchain.document_loaders import DirectoryLoader\n'), ((3108, 3122), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (3119, 3122), False, 'import pickle\n'), ((3152, 3208), 'streamlit.success', 'st.success', (['"""Existing vector store loaded successfully."""'], {}), "('Existing vector store loaded successfully.')\n", (3162, 3208), True, 'import streamlit as st\n'), ((4274, 4306), 'streamlit.chat_message', 'st.chat_message', (["message['role']"], {}), "(message['role'])\n", (4289, 4306), True, 'import streamlit as st\n'), ((4316, 4347), 'streamlit.markdown', 'st.markdown', (["message['content']"], {}), "(message['content'])\n", (4327, 4347), True, 'import streamlit as st\n'), ((5172, 5195), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (5187, 5195), True, 'import streamlit as st\n'), ((5205, 5228), 'streamlit.markdown', 'st.markdown', (['user_input'], {}), '(user_input)\n', (5216, 5228), True, 'import streamlit as st\n'), ((5412, 5440), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (5427, 5440), True, 'import streamlit as st\n'), ((5472, 5482), 'streamlit.empty', 'st.empty', ([], {}), '()\n', (5480, 5482), True, 'import streamlit as st\n'), ((1562, 1625), 'streamlit.success', 'st.success', (['f"""File {uploaded_file.name} uploaded successfully!"""'], {}), "(f'File {uploaded_file.name} uploaded successfully!')\n", (1572, 1625), True, 'import streamlit as st\n'), ((3821, 3866), 'streamlit.success', 'st.success', (['"""Vector store created and saved."""'], {}), "('Vector store created and saved.')\n", (3831, 3866), True, 'import streamlit as st\n'), ((3893, 3952), 'streamlit.warning', 'st.warning', (['"""No documents available to process!"""'], {'icon': '"""⚠️"""'}), "('No documents available to process!', icon='⚠️')\n", (3903, 3952), True, 'import streamlit as st\n'), ((3279, 3327), 'streamlit.spinner', 'st.spinner', (['"""Splitting documents into chunks..."""'], {}), "('Splitting documents into chunks...')\n", (3289, 3327), True, 'import streamlit as st\n'), ((3361, 3418), 'langchain.text_splitter.CharacterTextSplitter', 'CharacterTextSplitter', ([], {'chunk_size': '(2000)', 'chunk_overlap': '(200)'}), '(chunk_size=2000, chunk_overlap=200)\n', (3382, 3418), False, 'from langchain.text_splitter import CharacterTextSplitter\n'), ((3510, 3568), 'streamlit.spinner', 'st.spinner', (['"""Adding document chunks to vector database..."""'], {}), "('Adding document chunks to vector database...')\n", (3520, 3568), True, 'import streamlit as st\n'), ((3600, 3650), 'langchain.vectorstores.FAISS.from_documents', 'FAISS.from_documents', (['documents', 'document_embedder'], {}), '(documents, document_embedder)\n', (3620, 3650), False, 'from langchain.vectorstores import FAISS\n'), ((3669, 3702), 'streamlit.spinner', 'st.spinner', (['"""Saving vector store"""'], {}), "('Saving vector store')\n", (3679, 3702), True, 'import streamlit as st\n'), ((1648, 1690), 'os.path.join', 'os.path.join', (['DOCS_DIR', 'uploaded_file.name'], {}), '(DOCS_DIR, uploaded_file.name)\n', (1660, 1690), False, 'import os\n'), ((3781, 3808), 'pickle.dump', 'pickle.dump', (['vectorstore', 'f'], {}), '(vectorstore, f)\n', (3792, 3808), False, 'import pickle\n')]