webui.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import gradio as gr
  2. import os
  3. import shutil
  4. from chains.local_doc_qa import LocalDocQA
  5. from configs.model_config import *
  6. import nltk
  7. nltk.data.path = [os.path.join(os.path.dirname(__file__), "nltk_data")] + nltk.data.path
  8. # return top-k text chunk from vector store
  9. VECTOR_SEARCH_TOP_K = 6
  10. # LLM input history length
  11. LLM_HISTORY_LEN = 3
  12. <<<<<<< HEAD
  13. =======
  14. <<<<<<< HEAD
  15. >>>>>>> f87a5f5 (fix bug in webui.py)
  16. =======
  17. # return top-k text chunk from vector store
  18. VECTOR_SEARCH_TOP_K = 6
  19. # LLM input history length
  20. LLM_HISTORY_LEN = 3
  21. >>>>>>> cba44ca (修复 webui.py 中 llm_history_len 和 vector_search_top_k 显示值与启动设置默认值不一致的问题)
  22. def get_file_list():
  23. if not os.path.exists("content"):
  24. return []
  25. return [f for f in os.listdir("content")]
  26. file_list = get_file_list()
  27. embedding_model_dict_list = list(embedding_model_dict.keys())
  28. llm_model_dict_list = list(llm_model_dict.keys())
  29. local_doc_qa = LocalDocQA()
  30. def upload_file(file):
  31. if not os.path.exists("content"):
  32. os.mkdir("content")
  33. filename = os.path.basename(file.name)
  34. shutil.move(file.name, "content/" + filename)
  35. # file_list首位插入新上传的文件
  36. file_list.insert(0, filename)
  37. return gr.Dropdown.update(choices=file_list, value=filename)
  38. def get_answer(query, vs_path, history):
  39. if vs_path:
  40. resp, history = local_doc_qa.get_knowledge_based_answer(
  41. query=query, vs_path=vs_path, chat_history=history)
  42. else:
  43. history = history + [[None, "请先加载文件后,再进行提问。"]]
  44. return history, ""
  45. def update_status(history, status):
  46. history = history + [[None, status]]
  47. print(status)
  48. return history
  49. def init_model():
  50. try:
  51. local_doc_qa.init_cfg()
  52. return """模型已成功加载,请选择文件后点击"加载文件"按钮"""
  53. except Exception as e:
  54. print(e)
  55. return """模型未成功加载,请重新选择后点击"加载模型"按钮"""
  56. def reinit_model(llm_model, embedding_model, llm_history_len, use_ptuning_v2, top_k, history):
  57. try:
  58. local_doc_qa.init_cfg(llm_model=llm_model,
  59. embedding_model=embedding_model,
  60. llm_history_len=llm_history_len,
  61. use_ptuning_v2=use_ptuning_v2,
  62. top_k=top_k)
  63. model_status = """模型已成功重新加载,请选择文件后点击"加载文件"按钮"""
  64. except Exception as e:
  65. print(e)
  66. model_status = """模型未成功重新加载,请重新选择后点击"加载模型"按钮"""
  67. return history + [[None, model_status]]
  68. def get_vector_store(filepath, history):
  69. if local_doc_qa.llm and local_doc_qa.embeddings:
  70. vs_path = local_doc_qa.init_knowledge_vector_store(["content/" + filepath])
  71. if vs_path:
  72. file_status = "文件已成功加载,请开始提问"
  73. else:
  74. file_status = "文件未成功加载,请重新上传文件"
  75. else:
  76. file_status = "模型未完成加载,请先在加载模型后再导入文件"
  77. vs_path = None
  78. return vs_path, history + [[None, file_status]]
  79. block_css = """.importantButton {
  80. background: linear-gradient(45deg, #7e0570,#5d1c99, #6e00ff) !important;
  81. border: none !important;
  82. }
  83. .importantButton:hover {
  84. background: linear-gradient(45deg, #ff00e0,#8500ff, #6e00ff) !important;
  85. border: none !important;
  86. }"""
  87. webui_title = """
  88. # 🎉langchain-ChatGLM WebUI🎉
  89. 👍 [https://github.com/imClumsyPanda/langchain-ChatGLM](https://github.com/imClumsyPanda/langchain-ChatGLM)
  90. """
  91. init_message = """欢迎使用 langchain-ChatGLM Web UI,开始提问前,请依次如下 3 个步骤:
  92. 1. 选择语言模型、Embedding 模型及相关参数,如果使用ptuning-v2方式微调过模型,将PrefixEncoder模型放在ptuning-v2文件夹里并勾选相关选项,然后点击"重新加载模型",并等待加载完成提示
  93. 2. 上传或选择已有文件作为本地知识文档输入后点击"重新加载文档",并等待加载完成提示
  94. 3. 输入要提交的问题后,点击回车提交 """
  95. model_status = init_model()
  96. with gr.Blocks(css=block_css) as demo:
  97. vs_path, file_status, model_status = gr.State(""), gr.State(""), gr.State(model_status)
  98. gr.Markdown(webui_title)
  99. with gr.Row():
  100. with gr.Column(scale=2):
  101. chatbot = gr.Chatbot([[None, init_message], [None, model_status.value]],
  102. elem_id="chat-box",
  103. show_label=False).style(height=750)
  104. query = gr.Textbox(show_label=False,
  105. placeholder="请输入提问内容,按回车进行提交",
  106. ).style(container=False)
  107. with gr.Column(scale=1):
  108. llm_model = gr.Radio(llm_model_dict_list,
  109. label="LLM 模型",
  110. value=LLM_MODEL,
  111. interactive=True)
  112. llm_history_len = gr.Slider(0,
  113. 10,
  114. value=LLM_HISTORY_LEN,
  115. step=1,
  116. label="LLM history len",
  117. interactive=True)
  118. use_ptuning_v2 = gr.Checkbox(USE_PTUNING_V2,
  119. label="使用p-tuning-v2微调过的模型",
  120. interactive=True)
  121. embedding_model = gr.Radio(embedding_model_dict_list,
  122. label="Embedding 模型",
  123. value=EMBEDDING_MODEL,
  124. interactive=True)
  125. top_k = gr.Slider(1,
  126. 20,
  127. value=VECTOR_SEARCH_TOP_K,
  128. step=1,
  129. label="向量匹配 top k",
  130. interactive=True)
  131. load_model_button = gr.Button("重新加载模型")
  132. # with gr.Column():
  133. with gr.Tab("select"):
  134. selectFile = gr.Dropdown(file_list,
  135. label="content file",
  136. interactive=True,
  137. value=file_list[0] if len(file_list) > 0 else None)
  138. with gr.Tab("upload"):
  139. file = gr.File(label="content file",
  140. file_types=['.txt', '.md', '.docx', '.pdf']
  141. ) # .style(height=100)
  142. load_file_button = gr.Button("加载文件")
  143. load_model_button.click(reinit_model,
  144. show_progress=True,
  145. inputs=[llm_model, embedding_model, llm_history_len, use_ptuning_v2, top_k, chatbot],
  146. outputs=chatbot
  147. )
  148. # 将上传的文件保存到content文件夹下,并更新下拉框
  149. file.upload(upload_file,
  150. inputs=file,
  151. outputs=selectFile)
  152. load_file_button.click(get_vector_store,
  153. show_progress=True,
  154. inputs=[selectFile, chatbot],
  155. outputs=[vs_path, chatbot],
  156. )
  157. query.submit(get_answer,
  158. [query, vs_path, chatbot],
  159. [chatbot, query],
  160. )
  161. demo.queue(concurrency_count=3
  162. ).launch(server_name='0.0.0.0',
  163. server_port=7860,
  164. show_api=False,
  165. share=False,
  166. inbrowser=False)