Langchain-Chatchat/webui.py

294 lines
13 KiB
Python
Raw Normal View History

import gradio as gr
import os
import shutil
2023-04-14 00:42:21 +08:00
from chains.local_doc_qa import LocalDocQA
from configs.model_config import *
2023-04-16 23:38:25 +08:00
import nltk
nltk.data.path = [os.path.join(os.path.dirname(__file__), "nltk_data")] + nltk.data.path
# return top-k text chunk from vector store
VECTOR_SEARCH_TOP_K = 6
# LLM input history length
LLM_HISTORY_LEN = 3
2023-04-16 08:59:06 +08:00
2023-04-18 22:31:55 +08:00
def get_vs_list():
2023-04-19 21:54:59 +08:00
if not os.path.exists(VS_ROOT_PATH):
2023-04-18 22:31:55 +08:00
return []
2023-04-22 16:53:04 +08:00
return os.listdir(VS_ROOT_PATH)
2023-04-18 22:31:55 +08:00
2023-04-22 16:53:04 +08:00
vs_list = ["新建知识库"] + get_vs_list()
2023-04-14 00:42:21 +08:00
embedding_model_dict_list = list(embedding_model_dict.keys())
2023-04-14 00:42:21 +08:00
llm_model_dict_list = list(llm_model_dict.keys())
local_doc_qa = LocalDocQA()
2023-04-19 21:54:59 +08:00
def get_answer(query, vs_path, history, mode):
if mode == "知识库问答" and vs_path:
if local_doc_qa.llm.streaming:
2023-04-25 20:36:16 +08:00
for resp, history in local_doc_qa.get_knowledge_based_answer(
2023-04-26 23:19:11 +08:00
query=query, vs_path=vs_path, chat_history=history):
source = "\n\n"
source += "".join(
[f"""<details> <summary>出处 [{i + 1}] {os.path.split(doc.metadata["source"])[-1]}</summary>\n"""
f"""{doc.page_content}\n"""
f"""</details>"""
for i, doc in
enumerate(resp["source_documents"])])
history[-1][-1] += source
2023-04-25 20:36:16 +08:00
yield history, ""
else:
resp, history = local_doc_qa.get_knowledge_based_answer(
query=query, vs_path=vs_path, chat_history=history)
source = "\n\n"
source += "".join(
[f"""<details> <summary>出处 [{i + 1}] {os.path.split(doc.metadata["source"])[-1]}</summary>\n"""
f"""{doc.page_content}\n"""
f"""</details>"""
for i, doc in
enumerate(resp["source_documents"])])
history[-1][-1] += source
return history, ""
else:
if local_doc_qa.llm.streaming:
2023-04-26 23:19:11 +08:00
for resp, history in local_doc_qa.llm._call(query, history):
2023-04-25 20:36:16 +08:00
history[-1][-1] = resp + (
"\n\n当前知识库为空,如需基于知识库进行问答,请先加载知识库后,再进行提问。" if mode == "知识库问答" else "")
yield history, ""
else:
resp, history = local_doc_qa.llm._call(query, history)
history[-1][-1] = resp + (
"\n\n当前知识库为空,如需基于知识库进行问答,请先加载知识库后,再进行提问。" if mode == "知识库问答" else "")
return history, ""
2023-04-14 22:55:51 +08:00
def update_status(history, status):
history = history + [[None, status]]
print(status)
return history
2023-04-11 19:52:59 +08:00
2023-04-14 00:42:21 +08:00
def init_model():
try:
local_doc_qa.init_cfg(streaming=STREAMING)
2023-04-18 22:31:55 +08:00
local_doc_qa.llm._call("你好")
reply = """模型已成功加载,可以开始对话,或从右侧选择模式后开始对话"""
print(reply)
return reply
2023-04-16 08:59:06 +08:00
except Exception as e:
print(e)
reply = """模型未成功加载,请到页面左上角"模型配置"选项卡中重新选择后点击"加载模型"按钮"""
if str(e) == "Unknown platform: darwin":
2023-04-25 20:36:16 +08:00
print("该报错可能因为您使用的是 macOS 操作系统,需先下载模型至本地后执行 Web UI具体方法请参考项目 README 中本地部署方法及常见问题:"
" https://github.com/imClumsyPanda/langchain-ChatGLM")
else:
print(reply)
return reply
2023-04-14 00:42:21 +08:00
2023-04-15 14:43:12 +08:00
def reinit_model(llm_model, embedding_model, llm_history_len, use_ptuning_v2, top_k, history):
2023-04-14 22:55:51 +08:00
try:
local_doc_qa.init_cfg(llm_model=llm_model,
embedding_model=embedding_model,
llm_history_len=llm_history_len,
2023-04-15 14:43:12 +08:00
use_ptuning_v2=use_ptuning_v2,
top_k=top_k,
streaming=STREAMING)
2023-04-19 22:28:49 +08:00
model_status = """模型已成功重新加载,可以开始对话,或从右侧选择模式后开始对话"""
print(model_status)
2023-04-16 08:59:06 +08:00
except Exception as e:
print(e)
2023-04-19 22:28:49 +08:00
model_status = """模型未成功重新加载,请到页面左上角"模型配置"选项卡中重新选择后点击"加载模型"按钮"""
print(model_status)
2023-04-14 23:30:37 +08:00
return history + [[None, model_status]]
2023-04-14 22:55:51 +08:00
2023-04-14 00:42:21 +08:00
2023-04-19 21:54:59 +08:00
def get_vector_store(vs_id, files, history):
vs_path = VS_ROOT_PATH + vs_id
filelist = []
for file in files:
filename = os.path.split(file.name)[-1]
shutil.move(file.name, UPLOAD_ROOT_PATH + filename)
filelist.append(UPLOAD_ROOT_PATH + filename)
2023-04-16 08:59:06 +08:00
if local_doc_qa.llm and local_doc_qa.embeddings:
2023-04-19 21:54:59 +08:00
vs_path, loaded_files = local_doc_qa.init_knowledge_vector_store(filelist, vs_path)
if len(loaded_files):
file_status = f"已上传 {''.join([os.path.split(i)[-1] for i in loaded_files])} 至知识库,并已加载知识库,请开始提问"
2023-04-14 23:30:37 +08:00
else:
file_status = "文件未成功加载,请重新上传文件"
2023-04-14 22:55:51 +08:00
else:
2023-04-14 23:30:37 +08:00
file_status = "模型未完成加载,请先在加载模型后再导入文件"
vs_path = None
print(file_status)
2023-04-19 21:54:59 +08:00
return vs_path, None, history + [[None, file_status]]
2023-04-14 01:06:13 +08:00
2023-04-19 22:28:49 +08:00
def change_vs_name_input(vs_id):
if vs_id == "新建知识库":
return gr.update(visible=True), gr.update(visible=True), gr.update(visible=False), None
2023-04-19 07:58:58 +08:00
else:
2023-04-19 22:28:49 +08:00
return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), VS_ROOT_PATH + vs_id
2023-04-19 07:58:58 +08:00
def change_mode(mode):
if mode == "知识库问答":
return gr.update(visible=True)
2023-04-18 23:43:57 +08:00
else:
return gr.update(visible=False)
2023-04-19 21:54:59 +08:00
2023-04-19 07:58:58 +08:00
def add_vs_name(vs_name, vs_list, chatbot):
if vs_name in vs_list:
vs_status = "与已有知识库名称冲突,请重新选择其他名称后提交"
chatbot = chatbot + [[None, vs_status]]
2023-04-19 21:54:59 +08:00
return gr.update(visible=True), vs_list, chatbot
2023-04-19 07:58:58 +08:00
else:
vs_status = f"""已新增知识库"{vs_name}",将在上传文件并载入成功后进行存储。请在开始对话前,先完成文件上传。 """
chatbot = chatbot + [[None, vs_status]]
2023-04-19 21:54:59 +08:00
return gr.update(visible=True, choices=vs_list + [vs_name], value=vs_name), vs_list + [vs_name], chatbot
2023-04-19 07:58:58 +08:00
2023-04-18 23:43:57 +08:00
2023-04-14 22:55:51 +08:00
block_css = """.importantButton {
background: linear-gradient(45deg, #7e0570,#5d1c99, #6e00ff) !important;
border: none !important;
}
.importantButton:hover {
background: linear-gradient(45deg, #ff00e0,#8500ff, #6e00ff) !important;
border: none !important;
2023-04-14 22:55:51 +08:00
}"""
2023-04-14 22:55:51 +08:00
webui_title = """
# 🎉langchain-ChatGLM WebUI🎉
👍 [https://github.com/imClumsyPanda/langchain-ChatGLM](https://github.com/imClumsyPanda/langchain-ChatGLM)
2023-04-14 22:55:51 +08:00
"""
2023-04-19 22:28:49 +08:00
init_message = """欢迎使用 langchain-ChatGLM Web UI
请在右侧切换模式目前支持直接与 LLM 模型对话或基于本地知识库问答
知识库问答模式中选择知识库名称后即可开始问答如有需要可以在选择知识库名称后上传文件/文件夹至知识库
知识库暂不支持文件删除该功能将在后续版本中推出
"""
2023-04-14 22:55:51 +08:00
model_status = init_model()
with gr.Blocks(css=block_css) as demo:
2023-04-19 21:54:59 +08:00
vs_path, file_status, model_status, vs_list = gr.State(""), gr.State(""), gr.State(model_status), gr.State(vs_list)
2023-04-14 22:55:51 +08:00
gr.Markdown(webui_title)
2023-04-19 07:58:58 +08:00
with gr.Tab("对话"):
2023-04-18 22:31:55 +08:00
with gr.Row():
2023-04-19 07:58:58 +08:00
with gr.Column(scale=10):
2023-04-18 22:31:55 +08:00
chatbot = gr.Chatbot([[None, init_message], [None, model_status.value]],
elem_id="chat-box",
show_label=False).style(height=750)
query = gr.Textbox(show_label=False,
placeholder="请输入提问内容,按回车进行提交",
).style(container=False)
2023-04-19 07:58:58 +08:00
with gr.Column(scale=5):
mode = gr.Radio(["LLM 对话", "知识库问答"],
label="请选择使用模式",
2023-04-19 21:54:59 +08:00
value="知识库问答", )
2023-04-19 07:58:58 +08:00
vs_setting = gr.Accordion("配置知识库")
mode.change(fn=change_mode,
inputs=mode,
outputs=vs_setting)
with vs_setting:
2023-04-19 21:54:59 +08:00
select_vs = gr.Dropdown(vs_list.value,
2023-04-18 23:43:57 +08:00
label="请选择要加载的知识库",
interactive=True,
2023-04-19 21:54:59 +08:00
value=vs_list.value[0] if len(vs_list.value) > 0 else None
)
2023-04-18 23:43:57 +08:00
vs_name = gr.Textbox(label="请输入新建知识库名称",
lines=1,
interactive=True)
2023-04-19 07:58:58 +08:00
vs_add = gr.Button(value="添加至知识库选项")
vs_add.click(fn=add_vs_name,
inputs=[vs_name, vs_list, chatbot],
outputs=[select_vs, vs_list, chatbot])
2023-04-19 21:54:59 +08:00
2023-04-19 22:28:49 +08:00
file2vs = gr.Column(visible=False)
2023-04-19 21:54:59 +08:00
with file2vs:
2023-04-19 22:28:49 +08:00
# load_vs = gr.Button("加载知识库")
2023-04-19 21:54:59 +08:00
gr.Markdown("向知识库中添加文件")
with gr.Tab("上传文件"):
files = gr.File(label="添加文件",
file_types=['.txt', '.md', '.docx', '.pdf'],
file_count="multiple",
show_label=False
)
2023-04-19 22:28:49 +08:00
load_file_button = gr.Button("上传文件并加载知识库")
2023-04-19 21:54:59 +08:00
with gr.Tab("上传文件夹"):
folder_files = gr.File(label="添加文件",
# file_types=['.txt', '.md', '.docx', '.pdf'],
file_count="directory",
show_label=False
)
2023-04-19 22:28:49 +08:00
load_folder_button = gr.Button("上传文件夹并加载知识库")
# load_vs.click(fn=)
2023-04-18 23:43:57 +08:00
select_vs.change(fn=change_vs_name_input,
inputs=select_vs,
2023-04-19 22:28:49 +08:00
outputs=[vs_name, vs_add, file2vs, vs_path])
2023-04-19 21:54:59 +08:00
# 将上传的文件保存到content文件夹下,并更新下拉框
load_file_button.click(get_vector_store,
show_progress=True,
inputs=[select_vs, files, chatbot],
outputs=[vs_path, files, chatbot],
)
load_folder_button.click(get_vector_store,
show_progress=True,
inputs=[select_vs, folder_files, chatbot],
outputs=[vs_path, folder_files, chatbot],
)
query.submit(get_answer,
[query, vs_path, chatbot, mode],
[chatbot, query],
)
2023-04-18 22:31:55 +08:00
with gr.Tab("模型配置"):
llm_model = gr.Radio(llm_model_dict_list,
label="LLM 模型",
value=LLM_MODEL,
interactive=True)
llm_history_len = gr.Slider(0,
10,
value=LLM_HISTORY_LEN,
step=1,
2023-04-19 21:54:59 +08:00
label="LLM 对话轮数",
2023-04-18 22:31:55 +08:00
interactive=True)
use_ptuning_v2 = gr.Checkbox(USE_PTUNING_V2,
label="使用p-tuning-v2微调过的模型",
interactive=True)
embedding_model = gr.Radio(embedding_model_dict_list,
label="Embedding 模型",
value=EMBEDDING_MODEL,
interactive=True)
top_k = gr.Slider(1,
20,
value=VECTOR_SEARCH_TOP_K,
step=1,
label="向量匹配 top k",
interactive=True)
load_model_button = gr.Button("重新加载模型")
2023-04-14 00:42:21 +08:00
load_model_button.click(reinit_model,
show_progress=True,
2023-04-15 14:43:12 +08:00
inputs=[llm_model, embedding_model, llm_history_len, use_ptuning_v2, top_k, chatbot],
2023-04-14 23:30:37 +08:00
outputs=chatbot
)
2023-04-26 23:19:11 +08:00
(demo
.queue(concurrency_count=3)
.launch(server_name='0.0.0.0',
server_port=7860,
show_api=False,
share=False,
inbrowser=False))