webui.py 13 KB

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