webui.py 13 KB

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