local_doc_qa.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. from langchain.chains import RetrievalQA
  2. from langchain.prompts import PromptTemplate
  3. from langchain.embeddings.huggingface import HuggingFaceEmbeddings
  4. from langchain.vectorstores import FAISS
  5. from langchain.document_loaders import UnstructuredFileLoader
  6. from models.chatglm_llm import ChatGLM
  7. import sentence_transformers
  8. import os
  9. from configs.model_config import *
  10. import datetime
  11. from typing import List
  12. from textsplitter import ChineseTextSplitter
  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 load_file(filepath):
  18. if filepath.lower().endswith(".pdf"):
  19. loader = UnstructuredFileLoader(filepath)
  20. textsplitter = ChineseTextSplitter(pdf=True)
  21. docs = loader.load_and_split(textsplitter)
  22. else:
  23. loader = UnstructuredFileLoader(filepath, mode="elements")
  24. textsplitter = ChineseTextSplitter(pdf=False)
  25. docs = loader.load_and_split(text_splitter=textsplitter)
  26. return docs
  27. class LocalDocQA:
  28. llm: object = None
  29. embeddings: object = None
  30. top_k: int = VECTOR_SEARCH_TOP_K
  31. def init_cfg(self,
  32. embedding_model: str = EMBEDDING_MODEL,
  33. embedding_device=EMBEDDING_DEVICE,
  34. llm_history_len: int = LLM_HISTORY_LEN,
  35. llm_model: str = LLM_MODEL,
  36. llm_device=LLM_DEVICE,
  37. top_k=VECTOR_SEARCH_TOP_K,
  38. use_ptuning_v2: bool = USE_PTUNING_V2
  39. ):
  40. self.llm = ChatGLM()
  41. self.llm.load_model(model_name_or_path=llm_model_dict[llm_model],
  42. llm_device=llm_device,
  43. use_ptuning_v2=use_ptuning_v2)
  44. self.llm.history_len = llm_history_len
  45. self.embeddings = HuggingFaceEmbeddings(model_name=embedding_model_dict[embedding_model],
  46. model_kwargs={'device': embedding_device})
  47. # self.embeddings.client = sentence_transformers.SentenceTransformer(self.embeddings.model_name,
  48. # device=embedding_device)
  49. self.top_k = top_k
  50. def init_knowledge_vector_store(self,
  51. filepath: str or List[str],
  52. vs_path: str or os.PathLike = None):
  53. loaded_files = []
  54. if isinstance(filepath, str):
  55. if not os.path.exists(filepath):
  56. print("路径不存在")
  57. return None
  58. elif os.path.isfile(filepath):
  59. file = os.path.split(filepath)[-1]
  60. try:
  61. docs = load_file(filepath)
  62. print(f"{file} 已成功加载")
  63. loaded_files.append(filepath)
  64. except Exception as e:
  65. print(e)
  66. print(f"{file} 未能成功加载")
  67. return None
  68. elif os.path.isdir(filepath):
  69. docs = []
  70. for file in os.listdir(filepath):
  71. fullfilepath = os.path.join(filepath, file)
  72. try:
  73. docs += load_file(fullfilepath)
  74. print(f"{file} 已成功加载")
  75. loaded_files.append(fullfilepath)
  76. except Exception as e:
  77. print(e)
  78. print(f"{file} 未能成功加载")
  79. else:
  80. docs = []
  81. for file in filepath:
  82. try:
  83. docs += load_file(file)
  84. print(f"{file} 已成功加载")
  85. loaded_files.append(file)
  86. except Exception as e:
  87. print(e)
  88. print(f"{file} 未能成功加载")
  89. if vs_path and os.path.isdir(vs_path):
  90. vector_store = FAISS.load_local(vs_path, self.embeddings)
  91. vector_store.add_documents(docs)
  92. else:
  93. if not vs_path:
  94. vs_path = f"""{VS_ROOT_PATH}{os.path.splitext(file)[0]}_FAISS_{datetime.datetime.now().strftime("%Y%m%d_%H%M%S")}"""
  95. vector_store = FAISS.from_documents(docs, self.embeddings)
  96. vector_store.save_local(vs_path)
  97. return vs_path if len(docs) > 0 else None, loaded_files
  98. def get_knowledge_based_answer(self,
  99. query,
  100. vs_path,
  101. chat_history=[], ):
  102. prompt_template = """基于以下已知信息,简洁和专业的来回答用户的问题。
  103. 如果无法从中得到答案,请说 "根据已知信息无法回答该问题" 或 "没有提供足够的相关信息",不允许在答案中添加编造成分,答案请使用中文。
  104. 已知内容:
  105. {context}
  106. 问题:
  107. {question}"""
  108. prompt = PromptTemplate(
  109. template=prompt_template,
  110. input_variables=["context", "question"]
  111. )
  112. self.llm.history = chat_history
  113. vector_store = FAISS.load_local(vs_path, self.embeddings)
  114. knowledge_chain = RetrievalQA.from_llm(
  115. llm=self.llm,
  116. retriever=vector_store.as_retriever(search_kwargs={"k": self.top_k}),
  117. prompt=prompt
  118. )
  119. knowledge_chain.combine_documents_chain.document_prompt = PromptTemplate(
  120. input_variables=["page_content"], template="{page_content}"
  121. )
  122. knowledge_chain.return_source_documents = True
  123. result = knowledge_chain({"query": query})
  124. self.llm.history[-1][0] = query
  125. return result, self.llm.history