webui.py 13 KB

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