webui.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. def get_vs_list():
  13. if not os.path.exists(VS_ROOT_PATH):
  14. return []
  15. return os.listdir(VS_ROOT_PATH)
  16. vs_list = ["新建知识库"] + get_vs_list()
  17. embedding_model_dict_list = list(embedding_model_dict.keys())
  18. llm_model_dict_list = list(llm_model_dict.keys())
  19. local_doc_qa = LocalDocQA()
  20. def get_answer(query, vs_path, history, mode):
  21. if vs_path and mode == "知识库问答":
  22. resp, history = local_doc_qa.get_knowledge_based_answer(
  23. query=query, vs_path=vs_path, chat_history=history)
  24. source = "".join([f"""<details> <summary>出处 {i + 1}</summary>
  25. {doc.page_content}
  26. <b>所属文件:</b>{doc.metadata["source"]}
  27. </details>""" for i, doc in enumerate(resp["source_documents"])])
  28. history[-1][-1] += source
  29. else:
  30. resp = local_doc_qa.llm._call(query)
  31. history = history + [[query, resp + ("\n\n当前知识库为空,如需基于知识库进行问答,请先加载知识库后,再进行提问。" if mode == "知识库问答" else "")]]
  32. return history, ""
  33. def update_status(history, status):
  34. history = history + [[None, status]]
  35. print(status)
  36. return history
  37. def init_model():
  38. try:
  39. local_doc_qa.init_cfg()
  40. local_doc_qa.llm._call("你好")
  41. return """模型已成功加载,可以开始对话,或从右侧选择模式后开始对话"""
  42. except Exception as e:
  43. print(e)
  44. return """模型未成功加载,请到页面左上角"模型配置"选项卡中重新选择后点击"加载模型"按钮"""
  45. def reinit_model(llm_model, embedding_model, llm_history_len, use_ptuning_v2, top_k, history):
  46. try:
  47. local_doc_qa.init_cfg(llm_model=llm_model,
  48. embedding_model=embedding_model,
  49. llm_history_len=llm_history_len,
  50. use_ptuning_v2=use_ptuning_v2,
  51. top_k=top_k)
  52. model_status = """模型已成功重新加载,可以开始对话,或从右侧选择模式后开始对话"""
  53. except Exception as e:
  54. print(e)
  55. model_status = """模型未成功重新加载,请到页面左上角"模型配置"选项卡中重新选择后点击"加载模型"按钮"""
  56. return history + [[None, model_status]]
  57. def get_vector_store(vs_id, files, history):
  58. vs_path = VS_ROOT_PATH + vs_id
  59. filelist = []
  60. for file in files:
  61. filename = os.path.split(file.name)[-1]
  62. shutil.move(file.name, UPLOAD_ROOT_PATH + filename)
  63. filelist.append(UPLOAD_ROOT_PATH + filename)
  64. if local_doc_qa.llm and local_doc_qa.embeddings:
  65. vs_path, loaded_files = local_doc_qa.init_knowledge_vector_store(filelist, vs_path)
  66. if len(loaded_files):
  67. file_status = f"已上传 {'、'.join([os.path.split(i)[-1] for i in loaded_files])} 至知识库,并已加载知识库,请开始提问"
  68. else:
  69. file_status = "文件未成功加载,请重新上传文件"
  70. else:
  71. file_status = "模型未完成加载,请先在加载模型后再导入文件"
  72. vs_path = None
  73. return vs_path, None, history + [[None, file_status]]
  74. def change_vs_name_input(vs_id):
  75. if vs_id == "新建知识库":
  76. return gr.update(visible=True), gr.update(visible=True), gr.update(visible=False), None
  77. else:
  78. return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), VS_ROOT_PATH + vs_id
  79. def change_mode(mode):
  80. if mode == "知识库问答":
  81. return gr.update(visible=True)
  82. else:
  83. return gr.update(visible=False)
  84. def add_vs_name(vs_name, vs_list, chatbot):
  85. if vs_name in vs_list:
  86. chatbot = chatbot + [[None, "与已有知识库名称冲突,请重新选择其他名称后提交"]]
  87. return gr.update(visible=True), vs_list, chatbot
  88. else:
  89. chatbot = chatbot + [
  90. [None, f"""已新增知识库"{vs_name}",将在上传文件并载入成功后进行存储。请在开始对话前,先完成文件上传。 """]]
  91. return gr.update(visible=True, choices=vs_list + [vs_name], value=vs_name), vs_list + [vs_name], chatbot
  92. block_css = """.importantButton {
  93. background: linear-gradient(45deg, #7e0570,#5d1c99, #6e00ff) !important;
  94. border: none !important;
  95. }
  96. .importantButton:hover {
  97. background: linear-gradient(45deg, #ff00e0,#8500ff, #6e00ff) !important;
  98. border: none !important;
  99. }"""
  100. webui_title = """
  101. # 🎉langchain-ChatGLM WebUI🎉
  102. 👍 [https://github.com/imClumsyPanda/langchain-ChatGLM](https://github.com/imClumsyPanda/langchain-ChatGLM)
  103. """
  104. init_message = """欢迎使用 langchain-ChatGLM Web UI!
  105. 请在右侧切换模式,目前支持直接与 LLM 模型对话或基于本地知识库问答。
  106. 知识库问答模式中,选择知识库名称后,即可开始问答,如有需要可以在选择知识库名称后上传文件/文件夹至知识库。
  107. 知识库暂不支持文件删除,该功能将在后续版本中推出。
  108. """
  109. model_status = init_model()
  110. with gr.Blocks(css=block_css) as demo:
  111. vs_path, file_status, model_status, vs_list = gr.State(""), gr.State(""), gr.State(model_status), gr.State(vs_list)
  112. gr.Markdown(webui_title)
  113. with gr.Tab("对话"):
  114. with gr.Row():
  115. with gr.Column(scale=10):
  116. chatbot = gr.Chatbot([[None, init_message], [None, model_status.value]],
  117. elem_id="chat-box",
  118. show_label=False).style(height=750)
  119. query = gr.Textbox(show_label=False,
  120. placeholder="请输入提问内容,按回车进行提交",
  121. ).style(container=False)
  122. with gr.Column(scale=5):
  123. mode = gr.Radio(["LLM 对话", "知识库问答"],
  124. label="请选择使用模式",
  125. value="知识库问答", )
  126. vs_setting = gr.Accordion("配置知识库")
  127. mode.change(fn=change_mode,
  128. inputs=mode,
  129. outputs=vs_setting)
  130. with vs_setting:
  131. select_vs = gr.Dropdown(vs_list.value,
  132. label="请选择要加载的知识库",
  133. interactive=True,
  134. value=vs_list.value[0] if len(vs_list.value) > 0 else None
  135. )
  136. vs_name = gr.Textbox(label="请输入新建知识库名称",
  137. lines=1,
  138. interactive=True)
  139. vs_add = gr.Button(value="添加至知识库选项")
  140. vs_add.click(fn=add_vs_name,
  141. inputs=[vs_name, vs_list, chatbot],
  142. outputs=[select_vs, vs_list, chatbot])
  143. file2vs = gr.Column(visible=False)
  144. with file2vs:
  145. # load_vs = gr.Button("加载知识库")
  146. gr.Markdown("向知识库中添加文件")
  147. with gr.Tab("上传文件"):
  148. files = gr.File(label="添加文件",
  149. file_types=['.txt', '.md', '.docx', '.pdf'],
  150. file_count="multiple",
  151. show_label=False
  152. )
  153. load_file_button = gr.Button("上传文件并加载知识库")
  154. with gr.Tab("上传文件夹"):
  155. folder_files = gr.File(label="添加文件",
  156. # file_types=['.txt', '.md', '.docx', '.pdf'],
  157. file_count="directory",
  158. show_label=False
  159. )
  160. load_folder_button = gr.Button("上传文件夹并加载知识库")
  161. # load_vs.click(fn=)
  162. select_vs.change(fn=change_vs_name_input,
  163. inputs=select_vs,
  164. outputs=[vs_name, vs_add, file2vs, vs_path])
  165. # 将上传的文件保存到content文件夹下,并更新下拉框
  166. load_file_button.click(get_vector_store,
  167. show_progress=True,
  168. inputs=[select_vs, files, chatbot],
  169. outputs=[vs_path, files, chatbot],
  170. )
  171. load_folder_button.click(get_vector_store,
  172. show_progress=True,
  173. inputs=[select_vs, folder_files, chatbot],
  174. outputs=[vs_path, folder_files, chatbot],
  175. )
  176. query.submit(get_answer,
  177. [query, vs_path, chatbot, mode],
  178. [chatbot, query],
  179. )
  180. with gr.Tab("模型配置"):
  181. llm_model = gr.Radio(llm_model_dict_list,
  182. label="LLM 模型",
  183. value=LLM_MODEL,
  184. interactive=True)
  185. llm_history_len = gr.Slider(0,
  186. 10,
  187. value=LLM_HISTORY_LEN,
  188. step=1,
  189. label="LLM 对话轮数",
  190. interactive=True)
  191. use_ptuning_v2 = gr.Checkbox(USE_PTUNING_V2,
  192. label="使用p-tuning-v2微调过的模型",
  193. interactive=True)
  194. embedding_model = gr.Radio(embedding_model_dict_list,
  195. label="Embedding 模型",
  196. value=EMBEDDING_MODEL,
  197. interactive=True)
  198. top_k = gr.Slider(1,
  199. 20,
  200. value=VECTOR_SEARCH_TOP_K,
  201. step=1,
  202. label="向量匹配 top k",
  203. interactive=True)
  204. load_model_button = gr.Button("重新加载模型")
  205. load_model_button.click(reinit_model,
  206. show_progress=True,
  207. inputs=[llm_model, embedding_model, llm_history_len, use_ptuning_v2, top_k, chatbot],
  208. outputs=chatbot
  209. )
  210. demo.queue(concurrency_count=3
  211. ).launch(server_name='0.0.0.0',
  212. server_port=7860,
  213. show_api=False,
  214. share=False,
  215. inbrowser=False)