local_doc_qa.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. from langchain.embeddings.huggingface import HuggingFaceEmbeddings
  2. from langchain.vectorstores import FAISS
  3. from langchain.document_loaders import UnstructuredFileLoader
  4. from models.chatglm_llm import ChatGLM
  5. from configs.model_config import *
  6. import datetime
  7. from textsplitter import ChineseTextSplitter
  8. from typing import List, Tuple
  9. from langchain.docstore.document import Document
  10. import numpy as np
  11. from utils import torch_gc
  12. # return top-k text chunk from vector store
  13. VECTOR_SEARCH_TOP_K = 6
  14. # LLM input history length
  15. LLM_HISTORY_LEN = 3
  16. DEVICE_ = EMBEDDING_DEVICE
  17. DEVICE_ID = "0" if torch.cuda.is_available() else None
  18. DEVICE = f"{DEVICE_}:{DEVICE_ID}" if DEVICE_ID else DEVICE_
  19. def load_file(filepath):
  20. if filepath.lower().endswith(".md"):
  21. loader = UnstructuredFileLoader(filepath, mode="elements")
  22. docs = loader.load()
  23. elif filepath.lower().endswith(".pdf"):
  24. loader = UnstructuredFileLoader(filepath)
  25. textsplitter = ChineseTextSplitter(pdf=True)
  26. docs = loader.load_and_split(textsplitter)
  27. else:
  28. loader = UnstructuredFileLoader(filepath, mode="elements")
  29. textsplitter = ChineseTextSplitter(pdf=False)
  30. docs = loader.load_and_split(text_splitter=textsplitter)
  31. return docs
  32. def generate_prompt(related_docs: List[str],
  33. query: str,
  34. prompt_template=PROMPT_TEMPLATE) -> str:
  35. context = "\n".join([doc.page_content for doc in related_docs])
  36. prompt = prompt_template.replace("{question}", query).replace("{context}", context)
  37. return prompt
  38. def get_docs_with_score(docs_with_score):
  39. docs = []
  40. for doc, score in docs_with_score:
  41. doc.metadata["score"] = score
  42. docs.append(doc)
  43. return docs
  44. def seperate_list(ls: List[int]) -> List[List[int]]:
  45. lists = []
  46. ls1 = [ls[0]]
  47. for i in range(1, len(ls)):
  48. if ls[i - 1] + 1 == ls[i]:
  49. ls1.append(ls[i])
  50. else:
  51. lists.append(ls1)
  52. ls1 = [ls[i]]
  53. lists.append(ls1)
  54. return lists
  55. def similarity_search_with_score_by_vector(
  56. self,
  57. embedding: List[float],
  58. k: int = 4,
  59. ) -> List[Tuple[Document, float]]:
  60. scores, indices = self.index.search(np.array([embedding], dtype=np.float32), k)
  61. docs = []
  62. id_set = set()
  63. for j, i in enumerate(indices[0]):
  64. if i == -1:
  65. # This happens when not enough docs are returned.
  66. continue
  67. _id = self.index_to_docstore_id[i]
  68. doc = self.docstore.search(_id)
  69. id_set.add(i)
  70. docs_len = len(doc.page_content)
  71. for k in range(1, max(i, len(docs) - i)):
  72. break_flag = False
  73. for l in [i + k, i - k]:
  74. if 0 <= l < len(self.index_to_docstore_id):
  75. _id0 = self.index_to_docstore_id[l]
  76. doc0 = self.docstore.search(_id0)
  77. if docs_len + len(doc0.page_content) > self.chunk_size:
  78. break_flag=True
  79. break
  80. elif doc0.metadata["source"] == doc.metadata["source"]:
  81. docs_len += len(doc0.page_content)
  82. id_set.add(l)
  83. if break_flag:
  84. break
  85. id_list = sorted(list(id_set))
  86. id_lists = seperate_list(id_list)
  87. for id_seq in id_lists:
  88. for id in id_seq:
  89. if id == id_seq[0]:
  90. _id = self.index_to_docstore_id[id]
  91. doc = self.docstore.search(_id)
  92. else:
  93. _id0 = self.index_to_docstore_id[id]
  94. doc0 = self.docstore.search(_id0)
  95. doc.page_content += doc0.page_content
  96. if not isinstance(doc, Document):
  97. raise ValueError(f"Could not find document for id {_id}, got {doc}")
  98. docs.append((doc, scores[0][j]))
  99. torch_gc(DEVICE)
  100. return docs
  101. class LocalDocQA:
  102. llm: object = None
  103. embeddings: object = None
  104. top_k: int = VECTOR_SEARCH_TOP_K
  105. chunk_size: int = CHUNK_SIZE
  106. def init_cfg(self,
  107. embedding_model: str = EMBEDDING_MODEL,
  108. embedding_device=EMBEDDING_DEVICE,
  109. llm_history_len: int = LLM_HISTORY_LEN,
  110. llm_model: str = LLM_MODEL,
  111. llm_device=LLM_DEVICE,
  112. top_k=VECTOR_SEARCH_TOP_K,
  113. use_ptuning_v2: bool = USE_PTUNING_V2
  114. ):
  115. self.llm = ChatGLM()
  116. self.llm.load_model(model_name_or_path=llm_model_dict[llm_model],
  117. llm_device=llm_device,
  118. use_ptuning_v2=use_ptuning_v2)
  119. self.llm.history_len = llm_history_len
  120. self.embeddings = HuggingFaceEmbeddings(model_name=embedding_model_dict[embedding_model],
  121. model_kwargs={'device': embedding_device})
  122. self.top_k = top_k
  123. def init_knowledge_vector_store(self,
  124. filepath: str or List[str],
  125. vs_path: str or os.PathLike = None):
  126. loaded_files = []
  127. if isinstance(filepath, str):
  128. if not os.path.exists(filepath):
  129. print("路径不存在")
  130. return None
  131. elif os.path.isfile(filepath):
  132. file = os.path.split(filepath)[-1]
  133. try:
  134. docs = load_file(filepath)
  135. print(f"{file} 已成功加载")
  136. loaded_files.append(filepath)
  137. except Exception as e:
  138. print(e)
  139. print(f"{file} 未能成功加载")
  140. return None
  141. elif os.path.isdir(filepath):
  142. docs = []
  143. for file in os.listdir(filepath):
  144. fullfilepath = os.path.join(filepath, file)
  145. try:
  146. docs += load_file(fullfilepath)
  147. print(f"{file} 已成功加载")
  148. loaded_files.append(fullfilepath)
  149. except Exception as e:
  150. print(e)
  151. print(f"{file} 未能成功加载")
  152. else:
  153. docs = []
  154. for file in filepath:
  155. try:
  156. docs += load_file(file)
  157. print(f"{file} 已成功加载")
  158. loaded_files.append(file)
  159. except Exception as e:
  160. print(e)
  161. print(f"{file} 未能成功加载")
  162. if len(docs) > 0:
  163. if vs_path and os.path.isdir(vs_path):
  164. vector_store = FAISS.load_local(vs_path, self.embeddings)
  165. vector_store.add_documents(docs)
  166. torch_gc(DEVICE)
  167. else:
  168. if not vs_path:
  169. vs_path = f"""{VS_ROOT_PATH}{os.path.splitext(file)[0]}_FAISS_{datetime.datetime.now().strftime("%Y%m%d_%H%M%S")}"""
  170. vector_store = FAISS.from_documents(docs, self.embeddings)
  171. torch_gc(DEVICE)
  172. vector_store.save_local(vs_path)
  173. return vs_path, loaded_files
  174. else:
  175. print("文件均未成功加载,请检查依赖包或替换为其他文件再次上传。")
  176. return None, loaded_files
  177. def get_knowledge_based_answer(self,
  178. query,
  179. vs_path,
  180. chat_history=[],
  181. streaming: bool = STREAMING):
  182. vector_store = FAISS.load_local(vs_path, self.embeddings)
  183. FAISS.similarity_search_with_score_by_vector = similarity_search_with_score_by_vector
  184. vector_store.chunk_size = self.chunk_size
  185. related_docs_with_score = vector_store.similarity_search_with_score(query,
  186. k=self.top_k)
  187. related_docs = get_docs_with_score(related_docs_with_score)
  188. prompt = generate_prompt(related_docs, query)
  189. # if streaming:
  190. # for result, history in self.llm._stream_call(prompt=prompt,
  191. # history=chat_history):
  192. # history[-1][0] = query
  193. # response = {"query": query,
  194. # "result": result,
  195. # "source_documents": related_docs}
  196. # yield response, history
  197. # else:
  198. for result, history in self.llm._call(prompt=prompt,
  199. history=chat_history,
  200. streaming=streaming):
  201. history[-1][0] = query
  202. response = {"query": query,
  203. "result": result,
  204. "source_documents": related_docs}
  205. yield response, history
  206. if __name__ == "__main__":
  207. local_doc_qa = LocalDocQA()
  208. local_doc_qa.init_cfg()
  209. query = "本项目使用的embedding模型是什么,消耗多少显存"
  210. vs_path = "/Users/liuqian/Downloads/glm-dev/vector_store/aaa"
  211. last_print_len = 0
  212. for resp, history in local_doc_qa.get_knowledge_based_answer(query=query,
  213. vs_path=vs_path,
  214. chat_history=[],
  215. streaming=True):
  216. print(resp["result"][last_print_len:], end="", flush=True)
  217. last_print_len = len(resp["result"])
  218. source_text = [f"""出处 [{inum + 1}] {os.path.split(doc.metadata['source'])[-1]}:\n\n{doc.page_content}\n\n"""
  219. # f"""相关度:{doc.metadata['score']}\n\n"""
  220. for inum, doc in
  221. enumerate(resp["source_documents"])]
  222. print("\n\n" + "\n\n".join(source_text))
  223. # for resp, history in local_doc_qa.get_knowledge_based_answer(query=query,
  224. # vs_path=vs_path,
  225. # chat_history=[],
  226. # streaming=False):
  227. # print(resp["result"])
  228. pass