import streamlit as st
from streamlit_chat import message
import langchain_helper as lch
from langchain.schema import (SystemMessage, HumanMessage, AIMessage, messages)


def main():
    st.set_page_config(
        page_title="Iliad technical assessment",
        page_icon="🤖",
    )
    st.header("ChatBot Free Assistance")
    st.write("by [Julien GODFROY](https://github.com/jugodfroy)", )

    if "messages" not in st.session_state:
        st.session_state.messages = [
            # SystemMessage(content="En tant que ChatBot du service client de FREE, ton objectif est de fournir des réponses structurée, factuelles, utiles et concises aux questions des clients. Tu dois répondre en Markdown, uniquement en Français. Utilise les informations extraites des documents du service client pour répondre. Si la réponse à la question n'est pas disponible dans ta base de données, indique clairement que tu ne sais pas, sans inventer de réponse. Après avoir répondu, recommande une ou plusieurs URL pertinentes parmi celles fournies."),
        ]

    ##########################################
    #                SIDEBAR                 #
    ##########################################

    with st.sidebar:
        img = st.image("img/Logo_iliad.png", width=50)
        title = st.title("Iliad technical assessment")
        mistral = st.selectbox(
            "Utiliser l'API Mistral (online) ? :", ['No, run locally', 'Yes (key needed)'])
        with st.form("my_form"):
            if mistral == 'No, run locally':
                llm = st.selectbox("Choisissez un LLM offline :", [
                    "vigostral", "mistral-openorca:7b-q5_K_S", "mistral-openorca:7b-q5_K_M", "gemma", "mistral:instruct", "mistral:7b-instruct-q5_K_M", "mixtral"])
                st.write(
                    "Make sur the selected model is installed : ollama pull <modelname>")
                gpu = st.checkbox("Utiliser le GPU (CUDA) (pas testé)", False)
            else:
                llm = st.selectbox("Choisissez un LLM online:", [
                    "open-mistral-7b", "open-mixtral-8x7b"])  # add mistral-small-latest, mistral-medium-latest, mistral-large-latest to unlock the non-open source mistral LLM
                API_KEY = st.text_input(
                    "Entrez votre clé API Mistral :", type="password")
            user_input = st.text_area(
                "Posez votre question ici :",
                max_chars=150,
                help="Keep your question clear and concise for the best results.",
                placeholder="Comment obtenir le code RIO de ma ligne mobile ?"
            )
            submit_btn = st.form_submit_button("Envoyer")

        reset_btn = st.button("Reset press 2 times")

    ##########################################
    #                MAIN CORE               #
    ##########################################
    if 'previous_doc' not in st.session_state:
        st.session_state['previous_doc'] = ""
    message("Bonjour, je suis l'agent conversationnel de Free. Comment puis-je vous aider ?", is_user=False)

    # If the user has submitted a question
    if submit_btn and user_input != "":
        with st.spinner("Je réflechis..."):
            if mistral == 'No, run locally':    # run with local LLM
                response, doc = lch.main(
                    user_input, st.session_state.messages, st.session_state['previous_doc'], llm, gpu)
            else:
                response, doc = lch.main(       # run with Mistral API
                    user_input, st.session_state.messages, previous_doc=st.session_state['previous_doc'], llm=llm, API_KEY=API_KEY)
            st.session_state.messages.append(HumanMessage(content=user_input))

            # to deal with different response types depending on the type of LLM (local, or api)
            if mistral == 'No, run locally':
                st.session_state.messages.append(
                    AIMessage(content=response))
            else:
                st.session_state.messages.append(
                    AIMessage(content=response.content))
        # keep track of the previous doc for the next query
        st.session_state['previous_doc'] = str(doc)

    # Refresh the chat area
    messages = st.session_state.get('messages', [])
    for i, msg in enumerate(messages):
        if i % 2 == 0:  # user msg
            message(msg.content, is_user=True, key="user_"+str(i))
        else:        # bot msg
            message(msg.content, is_user=False, key="bot_"+str(i))

    if reset_btn:
        st.session_state.messages.clear()
        previous_doc = ""
        user_input = ""


if __name__ == "__main__":
    main()

langchain.schema.AIMessage langchain_helper.main langchain.schema.HumanMessage
[((187, 261), 'streamlit.set_page_config', 'st.set_page_config', ([], {'page_title': '"""Iliad technical assessment"""', 'page_icon': '"""🤖"""'}), "(page_title='Iliad technical assessment', page_icon='🤖')\n", (205, 261), True, 'import streamlit as st\n'), ((289, 325), 'streamlit.header', 'st.header', (['"""ChatBot Free Assistance"""'], {}), "('ChatBot Free Assistance')\n", (298, 325), True, 'import streamlit as st\n'), ((330, 391), 'streamlit.write', 'st.write', (['"""by [Julien GODFROY](https://github.com/jugodfroy)"""'], {}), "('by [Julien GODFROY](https://github.com/jugodfroy)')\n", (338, 391), True, 'import streamlit as st\n'), ((2965, 3079), 'streamlit_chat.message', 'message', (['"""Bonjour, je suis l\'agent conversationnel de Free. Comment puis-je vous aider ?"""'], {'is_user': '(False)'}), '(\n    "Bonjour, je suis l\'agent conversationnel de Free. Comment puis-je vous aider ?"\n    , is_user=False)\n', (2972, 3079), False, 'from streamlit_chat import message\n'), ((4235, 4271), 'streamlit.session_state.get', 'st.session_state.get', (['"""messages"""', '[]'], {}), "('messages', [])\n", (4255, 4271), True, 'import streamlit as st\n'), ((1225, 1265), 'streamlit.image', 'st.image', (['"""img/Logo_iliad.png"""'], {'width': '(50)'}), "('img/Logo_iliad.png', width=50)\n", (1233, 1265), True, 'import streamlit as st\n'), ((1282, 1320), 'streamlit.title', 'st.title', (['"""Iliad technical assessment"""'], {}), "('Iliad technical assessment')\n", (1290, 1320), True, 'import streamlit as st\n'), ((1339, 1435), 'streamlit.selectbox', 'st.selectbox', (['"""Utiliser l\'API Mistral (online) ? :"""', "['No, run locally', 'Yes (key needed)']"], {}), '("Utiliser l\'API Mistral (online) ? :", [\'No, run locally\',\n    \'Yes (key needed)\'])\n', (1351, 1435), True, 'import streamlit as st\n'), ((2693, 2725), 'streamlit.button', 'st.button', (['"""Reset press 2 times"""'], {}), "('Reset press 2 times')\n", (2702, 2725), True, 'import streamlit as st\n'), ((4538, 4571), 'streamlit.session_state.messages.clear', 'st.session_state.messages.clear', ([], {}), '()\n', (4569, 4571), True, 'import streamlit as st\n'), ((1458, 1476), 'streamlit.form', 'st.form', (['"""my_form"""'], {}), "('my_form')\n", (1465, 1476), True, 'import streamlit as st\n'), ((2347, 2544), 'streamlit.text_area', 'st.text_area', (['"""Posez votre question ici :"""'], {'max_chars': '(150)', 'help': '"""Keep your question clear and concise for the best results."""', 'placeholder': '"""Comment obtenir le code RIO de ma ligne mobile ?"""'}), "('Posez votre question ici :', max_chars=150, help=\n    'Keep your question clear and concise for the best results.',\n    placeholder='Comment obtenir le code RIO de ma ligne mobile ?')\n", (2359, 2544), True, 'import streamlit as st\n'), ((2639, 2671), 'streamlit.form_submit_button', 'st.form_submit_button', (['"""Envoyer"""'], {}), "('Envoyer')\n", (2660, 2671), True, 'import streamlit as st\n'), ((3167, 3196), 'streamlit.spinner', 'st.spinner', (['"""Je réflechis..."""'], {}), "('Je réflechis...')\n", (3177, 3196), True, 'import streamlit as st\n'), ((1545, 1741), 'streamlit.selectbox', 'st.selectbox', (['"""Choisissez un LLM offline :"""', "['vigostral', 'mistral-openorca:7b-q5_K_S', 'mistral-openorca:7b-q5_K_M',\n    'gemma', 'mistral:instruct', 'mistral:7b-instruct-q5_K_M', 'mixtral']"], {}), "('Choisissez un LLM offline :', ['vigostral',\n    'mistral-openorca:7b-q5_K_S', 'mistral-openorca:7b-q5_K_M', 'gemma',\n    'mistral:instruct', 'mistral:7b-instruct-q5_K_M', 'mixtral'])\n", (1557, 1741), True, 'import streamlit as st\n'), ((1771, 1849), 'streamlit.write', 'st.write', (['"""Make sur the selected model is installed : ollama pull <modelname>"""'], {}), "('Make sur the selected model is installed : ollama pull <modelname>')\n", (1779, 1849), True, 'import streamlit as st\n'), ((1893, 1949), 'streamlit.checkbox', 'st.checkbox', (['"""Utiliser le GPU (CUDA) (pas testé)"""', '(False)'], {}), "('Utiliser le GPU (CUDA) (pas testé)', False)\n", (1904, 1949), True, 'import streamlit as st\n'), ((1990, 2077), 'streamlit.selectbox', 'st.selectbox', (['"""Choisissez un LLM online:"""', "['open-mistral-7b', 'open-mixtral-8x7b']"], {}), "('Choisissez un LLM online:', ['open-mistral-7b',\n    'open-mixtral-8x7b'])\n", (2002, 2077), True, 'import streamlit as st\n'), ((2236, 2300), 'streamlit.text_input', 'st.text_input', (['"""Entrez votre clé API Mistral :"""'], {'type': '"""password"""'}), "('Entrez votre clé API Mistral :', type='password')\n", (2249, 2300), True, 'import streamlit as st\n'), ((3299, 3395), 'langchain_helper.main', 'lch.main', (['user_input', 'st.session_state.messages', "st.session_state['previous_doc']", 'llm', 'gpu'], {}), "(user_input, st.session_state.messages, st.session_state[\n    'previous_doc'], llm, gpu)\n", (3307, 3395), True, 'import langchain_helper as lch\n'), ((3462, 3587), 'langchain_helper.main', 'lch.main', (['user_input', 'st.session_state.messages'], {'previous_doc': "st.session_state['previous_doc']", 'llm': 'llm', 'API_KEY': 'API_KEY'}), "(user_input, st.session_state.messages, previous_doc=st.\n    session_state['previous_doc'], llm=llm, API_KEY=API_KEY)\n", (3470, 3587), True, 'import langchain_helper as lch\n'), ((3678, 3710), 'langchain.schema.HumanMessage', 'HumanMessage', ([], {'content': 'user_input'}), '(content=user_input)\n', (3690, 3710), False, 'from langchain.schema import SystemMessage, HumanMessage, AIMessage, messages\n'), ((3925, 3952), 'langchain.schema.AIMessage', 'AIMessage', ([], {'content': 'response'}), '(content=response)\n', (3934, 3952), False, 'from langchain.schema import SystemMessage, HumanMessage, AIMessage, messages\n'), ((4042, 4077), 'langchain.schema.AIMessage', 'AIMessage', ([], {'content': 'response.content'}), '(content=response.content)\n', (4051, 4077), False, 'from langchain.schema import SystemMessage, HumanMessage, AIMessage, messages\n')]