# -*- coding: utf-8 -*- import gradio as gr import os from langchain.retrievers import EnsembleRetriever from utils import * import requests from pyvi import ViTokenizer, ViPosTagger import time from transformers import AutoTokenizer, AutoModelForQuestionAnswering import torch from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain.chains import create_history_aware_retriever, create_retrieval_chain from langchain_community.chat_message_histories import ChatMessageHistory retriever = load_the_embedding_retrieve(is_ready=False, k=10) bm25_retriever = load_the_bm25_retrieve(k=1) ensemble_retriever = EnsembleRetriever( retrievers=[bm25_retriever, retriever], weights=[0.1, 0.9] ) parent_document_retrieve = load_the_parent_document_retrieve() # tokenizer = AutoTokenizer.from_pretrained("ShynBui/vie_qa", token=os.environ.get("HF_TOKEN")) # model = AutoModelForQuestionAnswering.from_pretrained("ShynBui/vie_qa", token=os.environ.get("HF_TOKEN")) os.environ["OPENAI_API_KEY"] = "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" llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=1,openai_api_key=os.environ["OPENAI_API_KEY"]) llm_long = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=1,max_tokens=1024, openai_api_key=os.environ["OPENAI_API_KEY"]) os.environ['PROMPT'] = ''' You are a helpful assistant specializing in answering questions related to academics and admissions at Ho Chi Minh City Open University. Based on information from "Context", give answers and suggest related topics. 1. Read the context carefully and remember concepts, terms or ideas. 2. Check if the context information can answer the question. 3. If the context information can answer the question, explain the answer in detail, don't try to make up an answer. If the context information can not answer the question, present the results as the following string: "I don't have information about the data". 4. Present the results in Vietnamese. Format into a string that includes only the answer to the question. Example: Context: A vector store-based retrieval engine is a system designed to retrieve documents based on their similarity to a query. This system is based on two main components: Vector store-backed retriever: A database specifically designed to store and manage high-dimensional vectors. These vectors represent the “meaning” or content of the document in numerical form. The vector store allows efficient retrieval of documents based on their vector similarity to a given query vector. Question: What is vector store-backed retriever? Output: Vector store-backed retriever is a database specifically designed to store and manage high-dimensional vectors. These vectors represent the “meaning” or content of the document in numerical form. The vector store allows efficient retrieval of documents based on their vector similarity to a given query vector. ''' os.environ['SUMARY_MESSAGE_PROMPT'] = ''' You are a professional summarizer in summarizing the conversation between the user and the AI. Your task is to summarize the content of the conversation from "History", the goal is for the language model to understand the context and hidden entities of the question so that it can give the most accurate answer. . 1. Read the context carefully and memorize concepts, terms or ideas. 2. Check which entity the conversation is talking about, and what issues are related to the entity. 3. Bring up the last mentioned entity in the conversation, so the AI can continue the conversation with the user. 4. Present the results in Vietnamese. History: Human: Ai là Hiệu trưởng của trường Đại học Mở TP.HCM? AI: Hiệu trưởng của trường Đại học Mở Thành phố Hồ Chí Minh là GS.TS. Nguyễn Minh Hà. Output: Cuộc trò chuyện trước đó nói về GS.TS. Nguyễn Minh Hà là hiệu trưởng của trường Đại học Mở TP.HCM. ''' os.environ['NEW_QUESTION_PROMPT'] = ''' You are an effective assistant specializing in answering questions related to academics and admissions at Ho Chi Minh City Open University. Answer all questions to the best of your ability. Based on "Summary" and "Questions" below. \ 1. Read "Summary" and "Question" carefully, check whether the question is related to the previous summary paragraph by examining the entities. 2. Decontextualize the "Question" by adding necessary modifiers to nouns or entire sentences and replacing pronouns (e.g. "it", "he", "she", "they" , "this", "that") by the full names of the entities they refer to. 3. Format the question so that the tracking system can find the answer from the question. Don't try to ask the opposite question. 4. Present results in Vietnamese. Format into a string that includes only the recreated question. Example: Summary: Trong cuộc trò chuyện, người dùng hỏi về Hiệu trưởng của trường Đại học Mở TP.HCM và AI đã trả lời rằng GS.TS. Nguyễn Minh Hà là Hiệu trưởng của trường này. Question: Ông ấy có trách nhiệm gì Output: Hiệu trưởng của trường Đại học Mở TP.HCM có trách nhiệm gì? Summary: Trong cuộc trò chuyện, người dùng hỏi về Hiệu trưởng của trường Đại học Mở TP.HCM và AI đã trả lời rằng GS.TS. Nguyễn Minh Hà là Hiệu trưởng của trường này. Question: Trách nhiệm của sinh viên là gì Output: Trách nhiệm của sinh viên trường Đại học Mở TP.HCM là gì? ''' def greet3(quote, history): # print(history) #check quote if quote[-1] != '?': quote += '?' demo_ephemeral_chat_history = ChatMessageHistory() if history == '': history = [("Bạn có thể giải thích về quy chế và quyền của sinh viên tại trường này không?", '''Quy chế và quyền của sinh viên tại trường Đại học Mở TP.HCM được quy định rõ trong các điều khoản sau: 1. Hiệu trưởng Trường có quyền ra quyết định thành lập và quy định cụ thể về chức năng, nhiệm vụ, tổ chức và hoạt động của Hội đồng khen thưởng và kỷ luật sinh viên. 2. Sinh viên có quyền khiếu nại về khen thưởng, kỷ luật. Khi có vi phạm kỷ luật, sinh viên có quyền được phân tích và đề nghị hình thức kỷ luật thông qua việc họp với các tổ chức sinh viên và gửi biên bản họp đến phòng Công tác sinh viên để trình Hội đồng. 3. Sinh viên có quyền đề đạt nguyện vọng và khiếu nại lên Hiệu trưởng Trường để giải quyết các vấn đề có liên quan đến quyền, lợi ích chính đáng của sinh viên. 4. Sinh viên được hỗ trợ giới thiệu nhà trọ theo quy định của trường. Các chủ đề liên quan mà bạn có thể muốn tìm hiểu thêm: - Quy chế và quyền của sinh viên tại các trường đại học khác. - Hệ thống hỗ trợ sinh viên tại trường Đại học Mở TP.HCM. - Quy trình khiếu nại và giải quyết tranh chấp sinh viên tại trường Đại học Mở TP.HCM. '''), ("Chào.", "Chào. Chúng ta vừa bắt đầu câu chuyện thôi.")] for user, assistant in history[-1:]: demo_ephemeral_chat_history.add_user_message(user) demo_ephemeral_chat_history.add_ai_message(assistant) else: for user, assistant in eval(history)[-1:]: demo_ephemeral_chat_history.add_user_message(user) demo_ephemeral_chat_history.add_ai_message(assistant) # Summary the message chat_history = summarize_messages(demo_ephemeral_chat_history=demo_ephemeral_chat_history, llm=llm).messages print("Chat history:", chat_history) # Get the new question new_question = get_question_from_summarize(chat_history[0].content, quote, llm) # Retrieve documents_query = ensemble_retriever.invoke(new_question) documents_query2 = ensemble_retriever.invoke(quote) parent_documents_query = parent_document_retrieve.invoke(new_question) parent_documents_query2 = parent_document_retrieve.invoke(quote) # print(documents_query) list_of_query = [documents_query, documents_query2, parent_documents_query, parent_documents_query2] list_context = [] for i in list_of_query: for j in i: list_context.append(j.page_content) list_context = set(list_context) context = '\n'.join(list_context) print(context) # Get answer answer = get_final_answer(question=new_question + ' ' + quote, context=context, prompt=os.environ['PROMPT'], llm=llm_long) return new_question + ' ' + quote, answer if __name__ == "__main__": quote = "Địa chỉ nhà trường?" iface = gr.Interface(fn=greet3, inputs=["text", "text"], outputs=["text", "text"]) iface.launch(share=True) #Những cái đã làm tốt hơn những gì - Đóng góp gì # 1. Dataset - Xu lý # 2. Tăng ngữ cảnh # 3. Tăng khả năng truy vết # 4.