File size: 10,145 Bytes
5018bdb
 
6e6cf97
 
 
5018bdb
 
 
 
c0b7011
5018bdb
 
 
52cdceb
5018bdb
 
 
 
79df212
6e6cf97
e27a465
cea573b
ec75084
5018bdb
57ec3ad
 
 
5018bdb
6e6cf97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5018bdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbc7c52
5018bdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec75084
5018bdb
 
2ec4111
 
5018bdb
 
 
 
 
 
 
f29479d
 
ec75084
 
 
 
 
 
2b0f9c9
1b3714a
5018bdb
 
 
 
 
 
 
 
 
 
f29479d
5018bdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e1e7c7
5018bdb
 
 
ec75084
 
 
 
 
5018bdb
cea573b
ec75084
 
 
 
e757497
5018bdb
 
 
7593922
5018bdb
 
7593922
 
 
 
5018bdb
 
 
 
 
 
 
2a681e8
 
 
5018bdb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e1e7c7
5018bdb
 
5e1e7c7
 
 
 
 
 
 
 
79df212
7593922
 
 
 
 
 
 
 
5018bdb
5e1e7c7
5018bdb
 
 
7593922
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import streamlit as st
import os
import shutil
import schedule
import time
import pickle
from langchain.prompts import ChatPromptTemplate
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.llms import HuggingFacePipeline
from langchain.retrievers import ParentDocumentRetriever
from langchain.storage import InMemoryStore
from langchain_chroma import Chroma
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, FewShotChatMessagePromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableLambda
from datetime import date
import time
import subprocess
import threading
llm_list = ['Mistral-7B-Instruct-v0.2','Mixtral-8x7B-Instruct-v0.1']
blablador_base = "https://helmholtz-blablador.fz-juelich.de:8000/v1"
# Environment variables
os.environ['LANGCHAIN_TRACING_V2'] = 'true'
os.environ['LANGCHAIN_ENDPOINT'] = 'https://api.smith.langchain.com'
os.environ['LANGCHAIN_API_KEY'] = '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'

# Function to update your retriever
# Function to update your retriever
def update_retriever():
    # Define the directory and file paths
    directory_path = "ohw_proj_chorma_db"
    file_path = "ohw_proj_chorma_db.pcl"

    # Remove the directory and its contents if it exists
    if os.path.exists(directory_path):
        shutil.rmtree(directory_path)
        st.write(f"Directory '{directory_path}' and its contents were removed successfully.")

    # Remove the file if it exists
    if os.path.exists(file_path):
        os.remove(file_path)
        st.write(f"File '{file_path}' was removed successfully.")

    # Run the first Python script
    try:
        subprocess.run(["python", "scrape_github.py"], check=True)
        st.write("GitHub repos downloaded")
    except subprocess.CalledProcessError as e:
        st.error(f"Error running scrape_github.py: {e}")

    # Run the second Python script
    try:
        subprocess.run(["python", "create_retriever.py"], check=True)
        st.write("Retriever updated")
    except subprocess.CalledProcessError as e:
        st.error(f"Error running create_retriever.py: {e}")

    # Additional logic to update your retriever after running the scripts
    st.write("Retriever updated!")

# Function to run the scheduler
def run_scheduler():
    while True:
        schedule.run_pending()
        time.sleep(1)  # Check every second

# Schedule the retriever update every 24 hours
schedule.every(24).hours.do(update_retriever)

# Run the scheduler in a separate thread to not block the main thread
scheduler_thread = threading.Thread(target=run_scheduler)
scheduler_thread.start()
if os.path.exists(directory_path):
    st.write('retriever loaded')
else:
    try:
        subprocess.run(["python", "scrape_github.py"], check=True)
        st.write("GitHub repos downloaded")
    except subprocess.CalledProcessError as e:
        st.error(f"Error running scrape_github.py: {e}")

    # Run the second Python script
    try:
        subprocess.run(["python", "create_retriever.py"], check=True)
        st.write("Retriever updated")
    except subprocess.CalledProcessError as e:
        st.error(f"Error running create_retriever.py: {e}")
def load_from_pickle(filename):
    with open(filename, "rb") as file:
        return pickle.load(file)
def load_retriever(docstore_path,chroma_path,embeddings,child_splitter,parent_splitter):
    """Loads the vector store and document store, initializing the retriever."""
    db3 = Chroma(collection_name="full_documents", #collection_name shoud be the same as in the first time
                     embedding_function=embeddings,
                     persist_directory=chroma_path
    )
    store_dict = load_from_pickle(docstore_path)

    store = InMemoryStore()
    store.mset(list(store_dict.items()))

    retriever = ParentDocumentRetriever(
        vectorstore=db3,
        docstore=store,
        child_splitter=child_splitter,
        parent_splitter=parent_splitter,
        search_kwargs={"k": 2}
    )
    return retriever
def inspect(state):
    if "context_sources" not in st.session_state:
        st.session_state.context_sources = []
    context = state['normal_context']
    st.session_state.context_sources =[doc.metadata['source']  for doc in context]
    st.session_state.context_content = [doc.page_content for doc in context]
    return state
def retrieve_normal_context(retriever, question):
    docs = retriever.invoke(question)
    return docs

# Your OLMOLLM class implementation here (adapted for the Hugging Face model)

@st.cache_resource
def get_chain(temperature,selected_model):
    embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L12-v2")
    
    docstore_path = 'ohw_proj_chorma_db.pcl'
    chroma_path   = 'ohw_proj_chorma_db'
    parent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000,
                                                    chunk_overlap=500)

    # create the child documents - The small chunks
    child_splitter = RecursiveCharacterTextSplitter(chunk_size=300,
                                                    chunk_overlap=50)
    retriever = load_retriever(docstore_path,chroma_path,embeddings,child_splitter,parent_splitter)
    # llm_api = 'glpat-AMzMevbqaVjp4HbLcVum'
    llm_api = os.getenv("blablador_api")
    llm = ChatOpenAI(model_name=selected_model,
                    temperature=temperature,
                    openai_api_key=llm_api,
                    openai_api_base=blablador_base,
                    streaming=True)


    
    today = date.today()
    # Response prompt 
    response_prompt_template = """You are an assistant who helps Ocean Hack Week community to answer their questions. I am going to ask you a question. Your response should be comprehensive and not contradicted with the following context if they are relevant. Otherwise, ignore them if they are not relevant.
    Keep track of chat history: {chat_history}
    Today's date: {date}
    ## Normal Context:
    {normal_context}
 
    # Original Question: {question}

    # Answer:
    
    """
    response_prompt = ChatPromptTemplate.from_template(response_prompt_template)
    context_chain = RunnableLambda(lambda x: {
    "question": x["question"],
    "normal_context": retrieve_normal_context(retriever,x["question"]),
    # "step_back_context": retrieve_step_back_context(retriever,generate_queries_step_back.invoke({"question": x["question"]})),
    "chat_history": x["chat_history"],
    "date": today})
    chain = (
        context_chain
        | RunnableLambda(inspect)
        | response_prompt
        | llm
        | StrOutputParser()
    )
    return chain

def clear_chat_history():
    st.session_state.messages = []
    st.session_state.context_sources = []
    st.session_state.key = 0

# Sidebar
with st.sidebar:
    st.title("OHW Assistant")
    selected_model = st.sidebar.selectbox('Choose a LLM model',
                                           llm_list,
                                             key='selected_model',
                                             index = None)

    temperature = st.slider("Temperature: ", 0.0, 1.0, 0.5, 0.1)
    if selected_model in ['Mistral-7B-Instruct-v0.2', 'Mixtral-8x7B-Instruct-v0.1']:
        if selected_model == 'Mistral-7B-Instruct-v0.2':
            selected_model = 'alias-fast'
        elif selected_model == 'Mixtral-8x7B-Instruct-v0.1':
            selected_model = 'alias-large'
        chain = get_chain(temperature,selected_model)
    st.button('Clear Chat History', on_click=clear_chat_history)

# Main app
# Initialize session state variables
if "messages" not in st.session_state:
    st.session_state.messages = []
if "context_sources" not in st.session_state:
    st.session_state.context_sources = []
if "context_content" not in st.session_state:
    st.session_state.context_content = []


for q, message in enumerate(st.session_state.messages):
    if (message["role"] == 'assistant'):
        with st.chat_message(message["role"]):
            tab1, tab2 = st.tabs(["Answer", "Sources"])
            with tab1:
                st.markdown(message["content"])
    
            with tab2:
                for i, source in enumerate(message["sources"]):
                    name = f'{source}'
                    with st.expander(name):
                        st.markdown(f'{message["context"][i]}')
            
    else:
        question = message["content"]
        with st.chat_message(message["role"]):
            st.markdown(message["content"])


if prompt := st.chat_input("How may I assist you today?"):
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)

    with st.chat_message("assistant"):
        query=st.session_state.messages[-1]['content']
        tab1, tab2 = st.tabs(["Answer", "Sources"])
        with tab1:
            start_time = time.time()
            placeholder = st.empty()  # Create a placeholder in Streamlit
            full_answer = ""
            for chunk in chain.stream({"question": query, "chat_history":st.session_state.messages}):
                
                full_answer += chunk
                placeholder.markdown(full_answer,unsafe_allow_html=True)
            end_time = time.time()
            st.caption(f"Response time: {end_time - start_time:.2f} seconds")
        with tab2:
            if st.session_state.context_sources:
                for i, source in enumerate(st.session_state.context_sources):
                    name = f'{source}'
                    with st.expander(name):
                        st.markdown(f'{st.session_state.context_content[i]}')
            else:
                st.write("No sources available for this query.")


    st.session_state.messages.append({"role": "assistant", "content": full_answer})
    st.session_state.messages[-1]['sources'] = st.session_state.context_sources
    st.session_state.messages[-1]['context'] = st.session_state.context_content