import os import gradio as gr from langchain_community.vectorstores import FAISS from langchain_community.document_loaders import PyPDFLoader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.chains import ConversationalRetrievalChain from langchain.memory import ConversationBufferMemory from langchain_community.embeddings import HuggingFaceEmbeddings from langchain_community.llms import HuggingFaceEndpoint # ------------------------------ # Configuration & LLM Selection # ------------------------------ list_llm = [ "meta-llama/Meta-Llama-3-8B-Instruct", "mistralai/Mistral-7B-Instruct-v0.2" ] list_llm_simple = [os.path.basename(llm) for llm in list_llm] # Token đọc từ Space secret api_token = os.getenv("hf_token") # Space secret, không hardcode # ------------------------------ # PDF Loading & Splitting # ------------------------------ def load_doc(list_file_path): pages = [] for file_path in list_file_path: try: loader = PyPDFLoader(file_path) pages.extend(loader.load()) except Exception as e: print(f"Error loading {file_path}: {e}") text_splitter = RecursiveCharacterTextSplitter( chunk_size=1024, chunk_overlap=32 ) return text_splitter.split_documents(pages) # ------------------------------ # Vector Database Creation # ------------------------------ def create_db(doc_splits): embeddings = HuggingFaceEmbeddings() # CPU-only vectordb = FAISS.from_documents(doc_splits, embeddings) return vectordb # ------------------------------ # Initialize LLM + QA Chain # ------------------------------ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db): llm = HuggingFaceEndpoint( repo_id=llm_model, huggingfacehub_api_token=api_token, temperature=temperature, max_new_tokens=max_tokens, top_k=top_k, ) memory = ConversationBufferMemory( memory_key="chat_history", output_key='answer', return_messages=True ) retriever = vector_db.as_retriever() qa_chain = ConversationalRetrievalChain.from_llm( llm, retriever=retriever, chain_type="stuff", memory=memory, return_source_documents=True, verbose=False, ) return qa_chain # ------------------------------ # Database Initialization # ------------------------------ def initialize_database(list_file_obj): list_file_path = [x.name for x in list_file_obj if x is not None] doc_splits = load_doc(list_file_path) vector_db = create_db(doc_splits) return vector_db, "Database created!" # ------------------------------ # LLM Initialization # ------------------------------ def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db): llm_name = list_llm[llm_option] qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db) return qa_chain, "QA chain initialized. Chatbot is ready!" # ------------------------------ # Conversation Utilities # ------------------------------ def format_chat_history(chat_history, max_messages=5): formatted = [] for user_msg, bot_msg in chat_history[-max_messages:]: formatted.append(f"User: {user_msg}") formatted.append(f"Assistant: {bot_msg}") return formatted def conversation(qa_chain, message, history): formatted_history = format_chat_history(history) try: response = qa_chain.invoke({"question": message, "chat_history": formatted_history}) answer = response["answer"] if "Helpful Answer:" in answer: answer = answer.split("Helpful Answer:")[-1] sources = response["source_documents"] top_sources = [(s.page_content.strip(), s.metadata.get("page", 0) + 1) for s in sources[:3]] while len(top_sources) < 3: top_sources.append(("", 0)) new_history = history + [(message, answer)] return qa_chain, gr.update(value=""), new_history, *sum(top_sources, ()) except Exception as e: print(f"Conversation error: {e}") return qa_chain, gr.update(value=""), history, "", 0, "", 0, "", 0 # ------------------------------ # Gradio UI # ------------------------------ def demo(): with gr.Blocks(theme=gr.themes.Default(primary_hue="red", secondary_hue="pink")) as demo: vector_db = gr.State() qa_chain = gr.State() gr.HTML("