Spaces:
Build error
Build error
Update app.py
Browse files9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939423 unmodified lines1181191201211221231241251269 unmodified linesimport bcryptimport os# Define the data directory for loading documentsDATA_DIR = "docs"# Mengecek apakah 'is_initialized' sudah ada di session stateif 'is_initialized' not in st.session_state:st.session_state.is_initialized = False# Inisialisasi yang hanya dilakukan sekali saat pertama kali loadif not st.session_state.is_initialized:st.session_state.is_initialized = TrueSettings.llm = HuggingFaceInferenceAPI(model_name="HuggingFaceH4/zephyr-7b-beta",tokenizer_name="HuggingFaceH4/zephyr-7b-beta",context_window=2048,max_new_tokens=512,generate_kwargs={"temperature": 0.1},# stream=True)Settings.embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")# Set the global tokenizer to use the tokenizer from HuggingFace for encoding inputsset_global_tokenizer(AutoTokenizer.from_pretrained("BAAI/bge-base-en-v1.5").encode)print("# load data", datetime.now())# Load documents from the data directory into the Vector Store Indexdocuments = SimpleDirectoryReader(DATA_DIR).load_data()# Create Vector Store Index with HuggingFace Embeddingindex = VectorStoreIndex.from_documents(documents)# Create Prompt Template for Text-based Q&Achat_text_qa_msgs = [("user","""You are a Q&A assistant. For all other inquiries, your main goal is to provide answers as accurately as possible, based on the instructions and context you have been given. If a question does not match the provided context or is outside the scope of the document, kindly advise the user to ask questions within the context of the document.Context:{context_str}Question:{query_str} (jawab dalam bahasa Indonesia)""")]text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)# Initialize Chat Memory Buffer for Conversation Memorymemory = ChatMemoryBuffer.from_defaults(token_limit=3900)# Create Query Engine with LLM and Templatequery_engine = index.as_query_engine(text_qa_template=text_qa_template,# streaming=True,memory=memory)if 'query_engine' not in st.session_state:st.session_state.query_engine = query_engineprint("# loaded", datetime.now())# Function to handle queriesdef handle_query(query):query += " (jawab dalam bahasa Indonesia)"answer = st.session_state.query_engine.query(query)if hasattr(answer, 'response'):return answer.responseelif isinstance(answer, dict) and 'response' in answer:return answer['response']else:return "Sorry, I couldn't find an answer."# print("-- check", datetime.now())pswd = os.getenv("PSWD")23 unmodified linesst.error("Incorrect password. Please try again.")def show_main_page():# ============== Streamlit App ===============# st.title("Chatbot Kementrian Perhubungan ✅")# st.markdown("Retrieval-Augmented Generation (RAG) with Large Language Model (LLM)")st.markdown("start chat ...🚀")if 'messages' not in st.session_state:9 unmodified lines1011121314151623 unmodified lines4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261279 unmodified linesimport bcryptimport ospswd = os.getenv("PSWD")23 unmodified linesst.error("Incorrect password. Please try again.")def show_main_page():# Define the data directory for loading documentsDATA_DIR = "docs"# Mengecek apakah 'is_initialized' sudah ada di session stateif 'is_initialized' not in st.session_state:st.session_state.is_initialized = False# Inisialisasi yang hanya dilakukan sekali saat pertama kali loadif not st.session_state.is_initialized:st.session_state.is_initialized = TrueSettings.llm = HuggingFaceInferenceAPI(model_name="HuggingFaceH4/zephyr-7b-beta",tokenizer_name="HuggingFaceH4/zephyr-7b-beta",context_window=2048,max_new_tokens=512,generate_kwargs={"temperature": 0.1},# stream=True)Settings.embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")# Set the global tokenizer to use the tokenizer from HuggingFace for encoding inputsset_global_tokenizer(AutoTokenizer.from_pretrained("BAAI/bge-base-en-v1.5").encode)print("# load data", datetime.now())# Load documents from the data directory into the Vector Store Indexdocuments = SimpleDirectoryReader(DATA_DIR).load_data()# Create Vector Store Index with HuggingFace Embeddingindex = VectorStoreIndex.from_documents(documents)# Create Prompt Template for Text-based Q&Achat_text_qa_msgs = [("user","""You are a Q&A assistant. For all other inquiries, your main goal is to provide answers as accurately as possible, based on the instructions and context you have been given. If a question does not match the provided context or is outside the scope of the document, kindly advise the user to ask questions within the context of the document.Context:{context_str}Question:{query_str} (jawab dalam bahasa Indonesia)""")]text_qa_template = ChatPromptTemplate.from_messages(chat_text_qa_msgs)# Initialize Chat Memory Buffer for Conversation Memorymemory = ChatMemoryBuffer.from_defaults(token_limit=3900)# Create Query Engine with LLM and Templatequery_engine = index.as_query_engine(text_qa_template=text_qa_template,# streaming=True,memory=memory)if 'query_engine' not in st.session_state:st.session_state.query_engine = query_engineprint("# loaded", datetime.now())# Function to handle queriesdef handle_query(query):query += " (jawab dalam bahasa Indonesia)"answer = st.session_state.query_engine.query(query)if hasattr(answer, 'response'):return answer.responseelif isinstance(answer, dict) and 'response' in answer:return answer['response']else:return "Sorry, I couldn't find an answer."# print("-- check", datetime.now())# ============== Streamlit App ===============# st.title("Chatbot Kementrian Perhubungan ✅")st.markdown("Retrieval-Augmented Generation (RAG) with Large Language Model (LLM)")st.markdown("start chat ...🚀")if 'messages' not in st.session_state:
app.py+80-79