2023-04-10 22:55:22 +08:00
|
|
|
|
from langchain.chains import RetrievalQA
|
2023-04-12 22:41:41 +08:00
|
|
|
|
from langchain.prompts import PromptTemplate
|
2023-03-31 20:09:40 +08:00
|
|
|
|
from langchain.embeddings.huggingface import HuggingFaceEmbeddings
|
|
|
|
|
|
from langchain.vectorstores import FAISS
|
|
|
|
|
|
from langchain.document_loaders import UnstructuredFileLoader
|
|
|
|
|
|
from chatglm_llm import ChatGLM
|
2023-04-11 21:55:42 +08:00
|
|
|
|
import sentence_transformers
|
|
|
|
|
|
import torch
|
|
|
|
|
|
import os
|
2023-04-11 22:13:15 +08:00
|
|
|
|
import readline
|
2023-04-11 21:55:42 +08:00
|
|
|
|
|
2023-03-31 20:09:40 +08:00
|
|
|
|
|
2023-04-10 22:55:22 +08:00
|
|
|
|
# Global Parameters
|
2023-04-11 22:13:15 +08:00
|
|
|
|
EMBEDDING_MODEL = "text2vec"
|
2023-04-10 22:55:22 +08:00
|
|
|
|
VECTOR_SEARCH_TOP_K = 6
|
2023-04-11 22:13:15 +08:00
|
|
|
|
LLM_MODEL = "chatglm-6b"
|
2023-04-10 22:55:22 +08:00
|
|
|
|
LLM_HISTORY_LEN = 3
|
2023-04-11 21:55:42 +08:00
|
|
|
|
DEVICE = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
2023-04-10 22:55:22 +08:00
|
|
|
|
|
|
|
|
|
|
# Show reply with source text from input document
|
|
|
|
|
|
REPLY_WITH_SOURCE = True
|
|
|
|
|
|
|
2023-04-07 12:01:15 +08:00
|
|
|
|
embedding_model_dict = {
|
|
|
|
|
|
"ernie-tiny": "nghuyong/ernie-3.0-nano-zh",
|
|
|
|
|
|
"ernie-base": "nghuyong/ernie-3.0-base-zh",
|
2023-04-10 22:55:22 +08:00
|
|
|
|
"text2vec": "GanymedeNil/text2vec-large-chinese",
|
2023-04-07 12:01:15 +08:00
|
|
|
|
}
|
2023-04-07 10:11:26 +08:00
|
|
|
|
|
2023-04-10 22:55:22 +08:00
|
|
|
|
llm_model_dict = {
|
2023-04-11 19:52:59 +08:00
|
|
|
|
"chatglm-6b-int4-qe": "THUDM/chatglm-6b-int4-qe",
|
|
|
|
|
|
"chatglm-6b-int4": "THUDM/chatglm-6b-int4",
|
2023-04-10 22:55:22 +08:00
|
|
|
|
"chatglm-6b": "THUDM/chatglm-6b",
|
|
|
|
|
|
}
|
2023-04-09 23:10:44 +08:00
|
|
|
|
|
2023-04-11 12:30:36 +08:00
|
|
|
|
|
2023-04-11 19:52:59 +08:00
|
|
|
|
def init_cfg(LLM_MODEL, EMBEDDING_MODEL, LLM_HISTORY_LEN, V_SEARCH_TOP_K=6):
|
|
|
|
|
|
global chatglm, embeddings, VECTOR_SEARCH_TOP_K
|
|
|
|
|
|
VECTOR_SEARCH_TOP_K = V_SEARCH_TOP_K
|
2023-04-11 12:30:36 +08:00
|
|
|
|
|
|
|
|
|
|
chatglm = ChatGLM()
|
|
|
|
|
|
chatglm.load_model(model_name_or_path=llm_model_dict[LLM_MODEL])
|
|
|
|
|
|
chatglm.history_len = LLM_HISTORY_LEN
|
2023-03-31 20:09:40 +08:00
|
|
|
|
|
2023-04-11 21:55:42 +08:00
|
|
|
|
embeddings = HuggingFaceEmbeddings(model_name=embedding_model_dict[EMBEDDING_MODEL],)
|
|
|
|
|
|
embeddings.client = sentence_transformers.SentenceTransformer(embeddings.model_name,
|
|
|
|
|
|
device=DEVICE)
|
2023-04-11 12:30:36 +08:00
|
|
|
|
|
2023-04-11 19:52:59 +08:00
|
|
|
|
|
2023-04-11 21:55:42 +08:00
|
|
|
|
def init_knowledge_vector_store(filepath:str):
|
2023-04-11 22:13:15 +08:00
|
|
|
|
if not os.path.exists(filepath):
|
|
|
|
|
|
print("路径不存在")
|
|
|
|
|
|
return None
|
|
|
|
|
|
elif os.path.isfile(filepath):
|
2023-04-11 23:02:24 +08:00
|
|
|
|
file = os.path.split(filepath)[-1]
|
|
|
|
|
|
try:
|
|
|
|
|
|
loader = UnstructuredFileLoader(filepath, mode="elements")
|
|
|
|
|
|
docs = loader.load()
|
|
|
|
|
|
print(f"{file} 已成功加载")
|
|
|
|
|
|
except:
|
|
|
|
|
|
print(f"{file} 未能成功加载")
|
|
|
|
|
|
return None
|
2023-04-11 21:55:42 +08:00
|
|
|
|
elif os.path.isdir(filepath):
|
|
|
|
|
|
docs = []
|
|
|
|
|
|
for file in os.listdir(filepath):
|
|
|
|
|
|
fullfilepath = os.path.join(filepath, file)
|
|
|
|
|
|
try:
|
|
|
|
|
|
loader = UnstructuredFileLoader(fullfilepath, mode="elements")
|
|
|
|
|
|
docs += loader.load()
|
|
|
|
|
|
print(f"{file} 已成功加载")
|
|
|
|
|
|
except:
|
|
|
|
|
|
print(f"{file} 未能成功加载")
|
2023-04-11 22:13:15 +08:00
|
|
|
|
|
2023-03-31 20:09:40 +08:00
|
|
|
|
vector_store = FAISS.from_documents(docs, embeddings)
|
|
|
|
|
|
return vector_store
|
|
|
|
|
|
|
|
|
|
|
|
|
2023-04-03 19:13:05 +08:00
|
|
|
|
def get_knowledge_based_answer(query, vector_store, chat_history=[]):
|
2023-04-11 19:52:59 +08:00
|
|
|
|
global chatglm, embeddings
|
2023-03-31 20:09:40 +08:00
|
|
|
|
|
2023-04-12 22:41:41 +08:00
|
|
|
|
prompt_template = """基于以下已知信息,简洁和专业的来回答用户的问题。
|
|
|
|
|
|
如果无法从中得到答案,请说 "根据已知信息无法回答该问题" 或 "没有提供足够的相关信息",不允许在答案中添加编造成分,答案请使用中文。
|
|
|
|
|
|
|
|
|
|
|
|
已知内容:
|
|
|
|
|
|
{context}
|
|
|
|
|
|
|
|
|
|
|
|
问题:
|
|
|
|
|
|
{question}"""
|
|
|
|
|
|
prompt = PromptTemplate(
|
|
|
|
|
|
template=prompt_template,
|
|
|
|
|
|
input_variables=["context", "question"]
|
|
|
|
|
|
)
|
2023-03-31 20:09:40 +08:00
|
|
|
|
chatglm.history = chat_history
|
2023-04-10 22:55:22 +08:00
|
|
|
|
knowledge_chain = RetrievalQA.from_llm(
|
2023-03-31 20:09:40 +08:00
|
|
|
|
llm=chatglm,
|
2023-04-10 22:55:22 +08:00
|
|
|
|
retriever=vector_store.as_retriever(search_kwargs={"k": VECTOR_SEARCH_TOP_K}),
|
|
|
|
|
|
prompt=prompt
|
2023-03-31 20:09:40 +08:00
|
|
|
|
)
|
2023-04-12 22:41:41 +08:00
|
|
|
|
knowledge_chain.combine_documents_chain.document_prompt = PromptTemplate(
|
|
|
|
|
|
input_variables=["page_content"], template="{page_content}"
|
|
|
|
|
|
)
|
2023-03-31 20:09:40 +08:00
|
|
|
|
|
|
|
|
|
|
knowledge_chain.return_source_documents = True
|
|
|
|
|
|
|
2023-04-10 22:55:22 +08:00
|
|
|
|
result = knowledge_chain({"query": query})
|
|
|
|
|
|
chatglm.history[-1][0] = query
|
2023-03-31 20:09:40 +08:00
|
|
|
|
return result, chatglm.history
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2023-04-11 19:52:59 +08:00
|
|
|
|
init_cfg(LLM_MODEL, EMBEDDING_MODEL, LLM_HISTORY_LEN)
|
2023-04-11 22:13:15 +08:00
|
|
|
|
vector_store = None
|
|
|
|
|
|
while not vector_store:
|
|
|
|
|
|
filepath = input("Input your local knowledge file path 请输入本地知识文件路径:")
|
|
|
|
|
|
vector_store = init_knowledge_vector_store(filepath)
|
2023-03-31 20:09:40 +08:00
|
|
|
|
history = []
|
|
|
|
|
|
while True:
|
|
|
|
|
|
query = input("Input your question 请输入问题:")
|
2023-04-03 19:13:05 +08:00
|
|
|
|
resp, history = get_knowledge_based_answer(query=query,
|
|
|
|
|
|
vector_store=vector_store,
|
|
|
|
|
|
chat_history=history)
|
2023-04-10 22:55:22 +08:00
|
|
|
|
if REPLY_WITH_SOURCE:
|
|
|
|
|
|
print(resp)
|
|
|
|
|
|
else:
|
|
|
|
|
|
print(resp["result"])
|