webui.py 12 KB

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