Spaces:
Sleeping
Sleeping
Delete app1.py
#2
by
Niooooor
- opened
app1.py
DELETED
|
@@ -1,154 +0,0 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
-
import os
|
| 3 |
-
import requests
|
| 4 |
-
from dotenv import load_dotenv # Only needed if using a .env file
|
| 5 |
-
|
| 6 |
-
# Langchain and HuggingFace
|
| 7 |
-
from langchain.vectorstores import Chroma
|
| 8 |
-
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 9 |
-
from langchain_groq import ChatGroq
|
| 10 |
-
from langchain.chains import RetrievalQA
|
| 11 |
-
|
| 12 |
-
# Load the .env file (if using it)
|
| 13 |
-
load_dotenv()
|
| 14 |
-
groq_api_key = os.getenv("GROQ_API_KEY")
|
| 15 |
-
|
| 16 |
-
# Load embeddings, model, and vector store
|
| 17 |
-
@st.cache_resource # Singleton, prevent multiple initializations
|
| 18 |
-
def init_chain():
|
| 19 |
-
|
| 20 |
-
model_kwargs = {'trust_remote_code': True}
|
| 21 |
-
embedding = HuggingFaceEmbeddings(model_name='nomic-ai/nomic-embed-text-v1.5', model_kwargs=model_kwargs)
|
| 22 |
-
llm = ChatGroq(groq_api_key=groq_api_key, model_name="llama3-70b-8192", temperature=0.2)
|
| 23 |
-
vectordb = Chroma(persist_directory='updated_CSPCDB2', embedding_function=embedding)
|
| 24 |
-
|
| 25 |
-
# Create chain
|
| 26 |
-
chain = RetrievalQA.from_chain_type(llm=llm,
|
| 27 |
-
chain_type="stuff",
|
| 28 |
-
retriever=vectordb.as_retriever(k=5),
|
| 29 |
-
return_source_documents=True)
|
| 30 |
-
return chain
|
| 31 |
-
|
| 32 |
-
# Streamlit app layout
|
| 33 |
-
st.set_page_config(
|
| 34 |
-
page_title="CSPC Citizens Charter Conversational Agent",
|
| 35 |
-
page_icon="cspclogo.png"
|
| 36 |
-
)
|
| 37 |
-
|
| 38 |
-
with st.sidebar:
|
| 39 |
-
st.title('CSPCean Conversational Agent')
|
| 40 |
-
st.subheader('Ask anything CSPC Related here!')
|
| 41 |
-
|
| 42 |
-
st.markdown('''**About CSPC:**
|
| 43 |
-
History, Core Values, Mission and Vision''')
|
| 44 |
-
|
| 45 |
-
st.markdown('''**Admission & Graduation:**
|
| 46 |
-
Apply, Requirements, Process, Graduation''')
|
| 47 |
-
|
| 48 |
-
st.markdown('''**Student Services:**
|
| 49 |
-
Scholarships, Orgs, Facilities''')
|
| 50 |
-
|
| 51 |
-
st.markdown('''**Academics:**
|
| 52 |
-
Degrees, Courses, Faculty''')
|
| 53 |
-
|
| 54 |
-
st.markdown('''**Officials:**
|
| 55 |
-
President, VPs, Deans, Admin''')
|
| 56 |
-
|
| 57 |
-
st.markdown('''
|
| 58 |
-
Access the resources here:
|
| 59 |
-
|
| 60 |
-
- [CSPC Citizen’s Charter](https://cspc.edu.ph/governance/citizens-charter/)
|
| 61 |
-
- [About CSPC](https://cspc.edu.ph/about/)
|
| 62 |
-
- [College Officials](https://cspc.edu.ph/college-officials/)
|
| 63 |
-
''')
|
| 64 |
-
st.markdown('Team XceptionNet')
|
| 65 |
-
|
| 66 |
-
# Store LLM generated responses
|
| 67 |
-
if "messages" not in st.session_state:
|
| 68 |
-
st.session_state.chain = init_chain()
|
| 69 |
-
st.session_state.messages = [{"role": "assistant", "content": "How may I help you today?"}]
|
| 70 |
-
|
| 71 |
-
# Function for generating response using the last three conversations
|
| 72 |
-
def generate_response(prompt_input):
|
| 73 |
-
# Initialize result
|
| 74 |
-
result = ''
|
| 75 |
-
|
| 76 |
-
# Prepare conversation history: get the last 3 user and assistant messages
|
| 77 |
-
conversation_history = ""
|
| 78 |
-
recent_messages = st.session_state.messages[-3:] # Last 3 user and assistant exchanges (each exchange is 2 messages)
|
| 79 |
-
|
| 80 |
-
for message in recent_messages:
|
| 81 |
-
conversation_history += f"{message['role']}: {message['content']}\n"
|
| 82 |
-
|
| 83 |
-
# Append the current user prompt to the conversation history
|
| 84 |
-
conversation_history += f"user: {prompt_input}\n"
|
| 85 |
-
|
| 86 |
-
# Invoke chain with the truncated conversation history
|
| 87 |
-
res = st.session_state.chain.invoke(conversation_history)
|
| 88 |
-
|
| 89 |
-
# Process response (as in the original code)
|
| 90 |
-
if res['result'].startswith('According to the provided context, '):
|
| 91 |
-
res['result'] = res['result'][35:]
|
| 92 |
-
res['result'] = res['result'][0].upper() + res['result'][1:]
|
| 93 |
-
elif res['result'].startswith('Based on the provided context, '):
|
| 94 |
-
res['result'] = res['result'][31:]
|
| 95 |
-
res['result'] = res['result'][0].upper() + res['result'][1:]
|
| 96 |
-
elif res['result'].startswith('According to the provided text, '):
|
| 97 |
-
res['result'] = res['result'][34:]
|
| 98 |
-
res['result'] = res['result'][0].upper() + res['result'][1:]
|
| 99 |
-
elif res['result'].startswith('According to the context, '):
|
| 100 |
-
res['result'] = res['result'][26:]
|
| 101 |
-
res['result'] = res['result'][0].upper() + res['result'][1:]
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
# result += res['result']
|
| 105 |
-
|
| 106 |
-
# # Process sources
|
| 107 |
-
# result += '\n\nSources: '
|
| 108 |
-
# sources = []
|
| 109 |
-
# for source in res["source_documents"]:
|
| 110 |
-
# sources.append(source.metadata['source'][122:-4]) # Adjust as per your source format
|
| 111 |
-
|
| 112 |
-
# sources = list(set(sources)) # Remove duplicates
|
| 113 |
-
# source_list = ", ".join(sources)
|
| 114 |
-
|
| 115 |
-
# result += source_list
|
| 116 |
-
|
| 117 |
-
# return result, res['result'], source_list
|
| 118 |
-
# return result, res['result']
|
| 119 |
-
return res['result']
|
| 120 |
-
|
| 121 |
-
# Display chat messages
|
| 122 |
-
for message in st.session_state.messages:
|
| 123 |
-
with st.chat_message(message["role"]):
|
| 124 |
-
st.write(message["content"])
|
| 125 |
-
|
| 126 |
-
# User-provided prompt for input box
|
| 127 |
-
if prompt := st.chat_input(placeholder="Ask a question..."):
|
| 128 |
-
# Append user query to session state
|
| 129 |
-
st.session_state.messages.append({"role": "user", "content": prompt})
|
| 130 |
-
with st.chat_message("user"):
|
| 131 |
-
st.write(prompt)
|
| 132 |
-
|
| 133 |
-
# Generate and display placeholder for assistant response
|
| 134 |
-
with st.chat_message("assistant"):
|
| 135 |
-
message_placeholder = st.empty() # Placeholder for response while it's being generated
|
| 136 |
-
with st.spinner("Generating response..."):
|
| 137 |
-
# Use conversation history when generating response
|
| 138 |
-
response = generate_response(prompt)
|
| 139 |
-
message_placeholder.markdown(response) # Replace placeholder with actual response
|
| 140 |
-
st.session_state.messages.append({"role": "assistant", "content": response})
|
| 141 |
-
|
| 142 |
-
# Clear chat history function
|
| 143 |
-
def clear_chat_history():
|
| 144 |
-
# Clear chat messages (reset the assistant greeting)
|
| 145 |
-
st.session_state.messages = [{"role": "assistant", "content": "How may I help you today?"}]
|
| 146 |
-
|
| 147 |
-
# Reinitialize the chain to clear any stored history (ensures it forgets previous user inputs)
|
| 148 |
-
st.session_state.chain = init_chain()
|
| 149 |
-
|
| 150 |
-
# Clear any additional session state that might be remembering user inquiries
|
| 151 |
-
if "recent_user_messages" in st.session_state:
|
| 152 |
-
del st.session_state["recent_user_messages"] # Clear remembered user inputs
|
| 153 |
-
|
| 154 |
-
st.sidebar.button('Clear Chat History', on_click=clear_chat_history)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|