Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532 unmodified lines2562572582592602612622632642652662672682692702712722732742752762772782792802812822832 unmodified lines28628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433511 unmodified lines347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379import gradio as grimport osfrom langchain_community.document_loaders import PyPDFLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_community.vectorstores import Chromafrom langchain.chains import ConversationalRetrievalChainfrom langchain_community.embeddings import HuggingFaceEmbeddingsfrom langchain_community.llms import HuggingFacePipelinefrom langchain.chains import ConversationChainfrom langchain.memory import ConversationBufferMemoryfrom langchain_community.llms import HuggingFaceEndpointimport spacesfrom pathlib import Pathimport chromadbfrom unidecode import unidecodefrom transformers import AutoTokenizerimport transformersimport torchimport tqdmimport accelerateimport re# default_persist_directory = './chroma_HF/'list_llm = ["mistralai/Mistral-7B-Instruct-v0.2", "mistralai/Mixtral-8x7B-Instruct-v0.1", "mistralai/Mistral-7B-Instruct-v0.1", \"google/gemma-7b-it","google/gemma-2b-it", \"HuggingFaceH4/zephyr-7b-beta", "HuggingFaceH4/zephyr-7b-gemma-v0.1", \"meta-llama/Llama-2-7b-chat-hf", "microsoft/phi-2", \"TinyLlama/TinyLlama-1.1B-Chat-v1.0", "mosaicml/mpt-7b-instruct", "tiiuae/falcon-7b-instruct", \"google/flan-t5-xxl"]list_llm_simple = [os.path.basename(llm) for llm in list_llm]@spaces.GPU# Load PDF document and create doc splitsdef load_doc(list_file_path, chunk_size, chunk_overlap):# Processing for one document only# loader = PyPDFLoader(file_path)# pages = loader.load()loaders = [PyPDFLoader(x) for x in list_file_path]pages = []for loader in loaders:pages.extend(loader.load())# text_splitter = RecursiveCharacterTextSplitter(chunk_size = 600, chunk_overlap = 50)text_splitter = RecursiveCharacterTextSplitter(chunk_size = chunk_size,chunk_overlap = chunk_overlap)doc_splits = text_splitter.split_documents(pages)return doc_splits# Create vector databasedef create_db(splits, collection_name):embedding = HuggingFaceEmbeddings()new_client = chromadb.EphemeralClient()vectordb = Chroma.from_documents(documents=splits,embedding=embedding,client=new_client,collection_name=collection_name,# persist_directory=default_persist_directory)return vectordb# Load vector databasedef load_db():embedding = HuggingFaceEmbeddings()vectordb = Chroma(# persist_directory=default_persist_directory,embedding_function=embedding)return vectordb# Initialize langchain LLM chaindef initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):progress(0.1, desc="Initializing HF tokenizer...")# HuggingFacePipeline uses local model# Note: it will download model locally...# tokenizer=AutoTokenizer.from_pretrained(llm_model)# progress(0.5, desc="Initializing HF pipeline...")# pipeline=transformers.pipeline(# "text-generation",# model=llm_model,# tokenizer=tokenizer,# torch_dtype=torch.bfloat16,# trust_remote_code=True,# device_map="auto",# # max_length=1024,# max_new_tokens=max_tokens,# do_sample=True,# top_k=top_k,# num_return_sequences=1,# eos_token_id=tokenizer.eos_token_id# )# llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature': temperature})# HuggingFaceHub uses HF inference endpointsprogress(0.5, desc="Initializing HF Hub...")# Use of trust_remote_code as model_kwargs# Warning: langchain issue# URL: https://github.com/langchain-ai/langchain/issues/6080if llm_model == "mistralai/Mixtral-8x7B-Instruct-v0.1":llm = HuggingFaceEndpoint(repo_id=llm_model,# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "load_in_8bit": True}temperature = temperature,max_new_tokens = max_tokens,top_k = top_k,load_in_8bit = True,)elif llm_model in ["HuggingFaceH4/zephyr-7b-gemma-v0.1","mosaicml/mpt-7b-instruct"]:raise gr.Error("LLM model is too large to be loaded automatically on free inference endpoint")llm = HuggingFaceEndpoint(repo_id=llm_model,temperature = temperature,max_new_tokens = max_tokens,top_k = top_k,)elif llm_model == "microsoft/phi-2":# raise gr.Error("phi-2 model requires 'trust_remote_code=True', currently not supported by langchain HuggingFaceHub...")llm = HuggingFaceEndpoint(repo_id=llm_model,# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}temperature = temperature,max_new_tokens = max_tokens,top_k = top_k,trust_remote_code = True,torch_dtype = "auto",)elif llm_model == "TinyLlama/TinyLlama-1.1B-Chat-v1.0":llm = HuggingFaceEndpoint(repo_id=llm_model,# model_kwargs={"temperature": temperature, "max_new_tokens": 250, "top_k": top_k}temperature = temperature,max_new_tokens = 250,top_k = top_k,)elif llm_model == "meta-llama/Llama-2-7b-chat-hf":raise gr.Error("Llama-2-7b-chat-hf model requires a Pro subscription...")llm = HuggingFaceEndpoint(repo_id=llm_model,# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}temperature = temperature,max_new_tokens = max_tokens,top_k = top_k,)else:llm = HuggingFaceEndpoint(repo_id=llm_model,# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}# model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}temperature = temperature,max_new_tokens = max_tokens,top_k = top_k,)progress(0.75, desc="Defining buffer memory...")memory = ConversationBufferMemory(memory_key="chat_history",output_key='answer',return_messages=True)# retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})retriever=vector_db.as_retriever()progress(0.8, desc="Defining retrieval chain...")qa_chain = ConversationalRetrievalChain.from_llm(llm,retriever=retriever,chain_type="stuff",memory=memory,# combine_docs_chain_kwargs={"prompt": your_prompt})return_source_documents=True,#return_generated_question=False,verbose=False,)progress(0.9, desc="Done!")return qa_chain# Generate collection name for vector database# - Use filepath as input, ensuring unicode textdef create_collection_name(filepath):# Extract filename without extensioncollection_name = Path(filepath).stem# Fix potential issues from naming convention## Remove spacecollection_name = collection_name.replace(" ","-")## ASCII transliterations of Unicode textcollection_name = unidecode(collection_name)## Remove special characters#collection_name = re.findall("[\dA-Za-z]*", collection_name)[0]collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)## Limit length to 50 characterscollection_name = collection_name[:50]## Minimum length of 3 charactersif len(collection_name) < 3:collection_name = collection_name + 'xyz'## Enforce start and end as alphanumeric characterif not collection_name[0].isalnum():collection_name = 'A' + collection_name[1:]if not collection_name[-1].isalnum():collection_name = collection_name[:-1] + 'Z'print('Filepath: ', filepath)print('Collection name: ', collection_name)return collection_name# Initialize databasedef initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):# Create list of documents (when valid)list_file_path = [x.name for x in list_file_obj if x is not None]# Create collection_name for vector databaseprogress(0.1, desc="Creating collection name...")collection_name = create_collection_name(list_file_path[0])progress(0.25, desc="Loading document...")# Load document and create splitsdoc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)# Create or load vector databaseprogress(0.5, desc="Generating vector database...")# global vector_dbvector_db = create_db(doc_splits, collection_name)progress(0.9, desc="Done!")return vector_db, collection_name, "Complete!"def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):# print("llm_option",llm_option)llm_name = list_llm[llm_option]print("llm_name: ",llm_name)qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)return qa_chain, "Complete!"def format_chat_history(message, chat_history):formatted_chat_history = []for user_message, bot_message in chat_history:formatted_chat_history.append(f"User: {user_message}")formatted_chat_history.append(f"Assistant: {bot_message}")return formatted_chat_historydef conversation(qa_chain, message, history):formatted_chat_history = format_chat_history(message, history)#print("formatted_chat_history",formatted_chat_history)# Generate response using QA chainresponse = qa_chain({"question": message, "chat_history": formatted_chat_history})response_answer = response["answer"]if response_answer.find("Helpful Answer:") != -1:2 unmodified linesresponse_source1 = response_sources[0].page_content.strip()response_source2 = response_sources[1].page_content.strip()response_source3 = response_sources[2].page_content.strip()# Langchain sources are zero-basedresponse_source1_page = response_sources[0].metadata["page"] + 1response_source2_page = response_sources[1].metadata["page"] + 1response_source3_page = response_sources[2].metadata["page"] + 1# print ('chat response: ', response_answer)# print('DB source', response_sources)# Append user message and response to chat historynew_history = history + [(message, response_answer)]# return gr.update(value=""), new_history, response_sources[0], response_sources[1]return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_pagedef upload_file(file_obj):list_file_path = []for idx, file in enumerate(file_obj):file_path = file_obj.namelist_file_path.append(file_path)# print(file_path)# initialize_database(file_path, progress)return list_file_pathdef demo():with gr.Blocks(theme="base") as demo:2 unmodified linescollection_name = gr.State()gr.Markdown("""<center><h2>PDF-based chatbot</center></h2><h3>Ask any questions about your PDF documents</h3>""")gr.Markdown("""<b>Note:</b> This AI assistant, using Langchain and open-source LLMs, performs retrieval-augmented generation (RAG) from your PDF documents. \The user interface explicitely shows multiple steps to help understand the RAG workflow.This chatbot takes past questions into account when generating answers (via conversational memory), and includes document references for clarity purposes.<br><br><b>Warning:</b> This space uses the free CPU Basic hardware from Hugging Face. Some steps and LLM models used below (free inference endpoints) can take some time to generate a reply.""")with gr.Tab("Step 1 - Upload PDF"):with gr.Row():document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")# upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)with gr.Tab("Step 2 - Process document"):with gr.Row():db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")with gr.Accordion("Advanced options - Document text splitter", open=False):with gr.Row():slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)with gr.Row():slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)with gr.Row():db_progress = gr.Textbox(label="Vector database initialization", value="None")with gr.Row():db_btn = gr.Button("Generate vector database")with gr.Tab("Step 3 - Initialize QA chain"):with gr.Row():llm_btn = gr.Radio(list_llm_simple, \label="LLM models", value = list_llm_simple[0], type="index", info="Choose your LLM model")with gr.Accordion("Advanced options - LLM model", open=False):with gr.Row():slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)with gr.Row():slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)with gr.Row():slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)with gr.Row():llm_progress = gr.Textbox(value="None",label="QA chain initialization")with gr.Row():qachain_btn = gr.Button("Initialize Question Answering chain")with gr.Tab("Step 4 - Chatbot"):chatbot = gr.Chatbot(height=300)with gr.Accordion("Advanced - Document references", open=False):with gr.Row():11 unmodified linessubmit_btn = gr.Button("Submit message")clear_btn = gr.ClearButton([msg, chatbot], value="Clear conversation")# Preprocessing events#upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])db_btn.click(initialize_database, \inputs=[document, slider_chunk_size, slider_chunk_overlap], \outputs=[vector_db, collection_name, db_progress])qachain_btn.click(initialize_LLM, \inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0], \inputs=None, \outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \queue=False)# Chatbot eventsmsg.submit(conversation, \inputs=[qa_chain, msg, chatbot], \outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \queue=False)submit_btn.click(conversation, \inputs=[qa_chain, msg, chatbot], \outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \queue=False)clear_btn.click(lambda:[None,"",0,"",0,"",0], \inputs=None, \outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \queue=False)demo.queue().launch(debug=True)if __name__ == "__main__":demo()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661672 unmodified lines1701711721731741751761771781791801812 unmodified lines18418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022111 unmodified lines233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271import gradio as grimport osfrom huggingface_hub import loginimport torchfrom transformers import AutoTokenizer, AutoModelForCausalLMimport transformersfrom langchain_community.document_loaders import PyPDFLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_community.vectorstores import Chromafrom langchain.chains import ConversationalRetrievalChainfrom langchain_community.embeddings import HuggingFaceEmbeddingsfrom langchain_community.llms import HuggingFacePipelinefrom langchain.memory import ConversationBufferMemoryimport spacesfrom pathlib import Pathimport chromadbfrom unidecode import unidecodeimport re# Global variablesglobal_llm = Noneglobal_tokenizer = Nonehf_token = os.environ.get("HF_TOKEN")if not hf_token:raise ValueError("Hugging Face token not found. Please set the HF_TOKEN environment variable.")# Log in to Hugging Facelogin(token=hf_token)list_llm = ["mistralai/Mistral-7B-Instruct-v0.2", "mistralai/Mixtral-8x7B-Instruct-v0.1", "mistralai/Mistral-7B-Instruct-v0.1"]list_llm_simple = [os.path.basename(llm) for llm in list_llm]@spaces.GPUdef load_doc(list_file_path, chunk_size, chunk_overlap):loaders = [PyPDFLoader(x) for x in list_file_path]pages = []for loader in loaders:pages.extend(loader.load())text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size,chunk_overlap=chunk_overlap)doc_splits = text_splitter.split_documents(pages)return doc_splitsdef create_db(splits, collection_name):if torch.cuda.is_available():os.environ["CUDA_VISIBLE_DEVICES"] = "0"embedding = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2",model_kwargs={"use_auth_token": hf_token})new_client = chromadb.EphemeralClient()vectordb = Chroma.from_documents(documents=splits,embedding=embedding,client=new_client,collection_name=collection_name,)return vectordbdef create_collection_name(filepath):collection_name = Path(filepath).stemcollection_name = collection_name.replace(" ", "-")collection_name = unidecode(collection_name)collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)collection_name = collection_name[:50]if len(collection_name) < 3:collection_name = collection_name + 'xyz'if not collection_name[0].isalnum():collection_name = 'A' + collection_name[1:]if not collection_name[-1].isalnum():collection_name = collection_name[:-1] + 'Z'return collection_namedef initialize_global_llm(llm_model, temperature, max_tokens, top_k, progress=gr.Progress()):global global_llm, global_tokenizerif global_llm is None:progress(0.1, desc="Initializing HF tokenizer...")global_tokenizer = AutoTokenizer.from_pretrained(llm_model, use_auth_token=hf_token)progress(0.3, desc="Loading model...")try:model = AutoModelForCausalLM.from_pretrained(llm_model,use_auth_token=hf_token,torch_dtype=torch.float16,device_map="auto")except RuntimeError as e:if "CUDA out of memory" in str(e):raise gr.Error("GPU memory exceeded. Try a smaller model or reduce batch size.")else:raise eprogress(0.5, desc="Initializing HF pipeline...")pipeline = transformers.pipeline("text-generation",model=model,tokenizer=global_tokenizer,torch_dtype=torch.float16,device_map="auto",max_new_tokens=max_tokens,do_sample=True,top_k=top_k,num_return_sequences=1,eos_token_id=global_tokenizer.eos_token_id)global_llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature': temperature})progress(0.9, desc="LLM initialization complete!")return "LLM initialized successfully!"else:progress(0.9, desc="Using previously initialized LLM.")return "Using previously initialized LLM."def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):if list_file_obj is None or len(list_file_obj) == 0:return None, None, "Error: No files uploaded. Please upload PDF files first."list_file_path = [x.name for x in list_file_obj if x is not None]if not list_file_path:return None, None, "Error: No valid files found. Please upload PDF files."progress(0.1, desc="Creating collection name...")collection_name = create_collection_name(list_file_path[0])progress(0.25, desc="Loading document...")doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)progress(0.5, desc="Generating vector database...")vector_db = create_db(doc_splits, collection_name)progress(0.9, desc="Done!")return vector_db, collection_name, "Complete!"def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):llm_name = list_llm[llm_option]global_llm = initialize_global_llm(llm_name, llm_temperature, max_tokens, top_k, progress)memory = ConversationBufferMemory(memory_key="chat_history",output_key='answer',return_messages=True)retriever = vector_db.as_retriever()qa_chain = ConversationalRetrievalChain.from_llm(global_llm,retriever=retriever,chain_type="stuff",memory=memory,return_source_documents=True,verbose=False,)return qa_chain, "Complete!"def format_chat_history(message, chat_history):formatted_chat_history = []for user_message, bot_message in chat_history:formatted_chat_history.append(f"User: {user_message}")formatted_chat_history.append(f"Assistant: {bot_message}")return formatted_chat_historydef conversation(qa_chain, message, history):formatted_chat_history = format_chat_history(message, history)response = qa_chain({"question": message, "chat_history": formatted_chat_history})response_answer = response["answer"]if response_answer.find("Helpful Answer:") != -1:2 unmodified linesresponse_source1 = response_sources[0].page_content.strip()response_source2 = response_sources[1].page_content.strip()response_source3 = response_sources[2].page_content.strip()response_source1_page = response_sources[0].metadata["page"] + 1response_source2_page = response_sources[1].metadata["page"] + 1response_source3_page = response_sources[2].metadata["page"] + 1new_history = history + [(message, response_answer)]return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_pagedef demo():with gr.Blocks(theme="base") as demo:2 unmodified linescollection_name = gr.State()gr.Markdown("""<center><h2>GPU-Accelerated PDF-based Chatbot</center></h2><h3>Ask any questions about your PDF documents</h3>""")gr.Markdown("""<b>Note:</b> This AI assistant uses GPU acceleration for faster processing.It performs retrieval-augmented generation (RAG) from your PDF documents using Langchain and open-source LLMs.This chatbot takes past questions into account and includes document references.""")with gr.Tab("Step 1 - Initialize LLM"):llm_btn = gr.Radio(list_llm_simple, label="LLM models", value=list_llm_simple[0], type="index", info="Choose your LLM model")with gr.Accordion("Advanced options - LLM model", open=False):slider_temperature = gr.Slider(minimum=0.01, maximum=1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)slider_maxtokens = gr.Slider(minimum=224, maximum=4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)slider_topk = gr.Slider(minimum=1, maximum=10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)llm_progress = gr.Textbox(value="Not initialized", label="LLM initialization status")init_llm_btn = gr.Button("Initialize LLM")with gr.Tab("Step 2 - Upload PDF"):document = gr.Files(height=100, file_count="multiple", file_types=["pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")with gr.Tab("Step 3 - Process document"):db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")with gr.Accordion("Advanced options - Document text splitter", open=False):slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)db_progress = gr.Textbox(label="Vector database initialization", value="None")db_btn = gr.Button("Generate vector database")with gr.Tab("Step 4 - Initialize QA chain"):llm_progress = gr.Textbox(value="None",label="QA chain initialization")qachain_btn = gr.Button("Initialize Question Answering chain")with gr.Tab("Step 5 - Chatbot"):chatbot = gr.Chatbot(height=300)with gr.Accordion("Advanced - Document references", open=False):with gr.Row():11 unmodified linessubmit_btn = gr.Button("Submit message")clear_btn = gr.ClearButton([msg, chatbot], value="Clear conversation")# Event handlersinit_llm_btn.click(initialize_global_llm,inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk],outputs=[llm_progress])db_btn.click(initialize_database,inputs=[document, slider_chunk_size, slider_chunk_overlap],outputs=[vector_db, collection_name, db_progress])qachain_btn.click(initialize_LLM,inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db],outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0],inputs=None,outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],queue=False)# Chatbot eventsmsg.submit(conversation,inputs=[qa_chain, msg, chatbot],outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],queue=False)submit_btn.click(conversation,inputs=[qa_chain, msg, chatbot],outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],queue=False)clear_btn.click(lambda:[None,"",0,"",0,"",0],inputs=None,outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page],queue=False)demo.queue().launch(debug=True)if __name__ == "__main__":demo()
app.py+138-246