local_doc_qa.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. for l in [i + k, i - k]:
  73. if 0 <= l < len(self.index_to_docstore_id):
  74. _id0 = self.index_to_docstore_id[l]
  75. doc0 = self.docstore.search(_id0)
  76. if docs_len + len(doc0.page_content) > self.chunk_size:
  77. break
  78. elif doc0.metadata["source"] == doc.metadata["source"]:
  79. docs_len += len(doc0.page_content)
  80. id_set.add(l)
  81. id_list = sorted(list(id_set))
  82. id_lists = seperate_list(id_list)
  83. for id_seq in id_lists:
  84. for id in id_seq:
  85. if id == id_seq[0]:
  86. _id = self.index_to_docstore_id[id]
  87. doc = self.docstore.search(_id)
  88. else:
  89. _id0 = self.index_to_docstore_id[id]
  90. doc0 = self.docstore.search(_id0)
  91. doc.page_content += doc0.page_content
  92. if not isinstance(doc, Document):
  93. raise ValueError(f"Could not find document for id {_id}, got {doc}")
  94. docs.append((doc, scores[0][j]))
  95. torch_gc(DEVICE)
  96. return docs
  97. class LocalDocQA:
  98. llm: object = None
  99. embeddings: object = None
  100. top_k: int = VECTOR_SEARCH_TOP_K
  101. chunk_size: int = CHUNK_SIZE
  102. def init_cfg(self,
  103. embedding_model: str = EMBEDDING_MODEL,
  104. embedding_device=EMBEDDING_DEVICE,
  105. llm_history_len: int = LLM_HISTORY_LEN,
  106. llm_model: str = LLM_MODEL,
  107. llm_device=LLM_DEVICE,
  108. top_k=VECTOR_SEARCH_TOP_K,
  109. use_ptuning_v2: bool = USE_PTUNING_V2
  110. ):
  111. self.llm = ChatGLM()
  112. self.llm.load_model(model_name_or_path=llm_model_dict[llm_model],
  113. llm_device=llm_device,
  114. use_ptuning_v2=use_ptuning_v2)
  115. self.llm.history_len = llm_history_len
  116. self.embeddings = HuggingFaceEmbeddings(model_name=embedding_model_dict[embedding_model],
  117. model_kwargs={'device': embedding_device})
  118. self.top_k = top_k
  119. def init_knowledge_vector_store(self,
  120. filepath: str or List[str],
  121. vs_path: str or os.PathLike = None):
  122. loaded_files = []
  123. if isinstance(filepath, str):
  124. if not os.path.exists(filepath):
  125. print("路径不存在")
  126. return None
  127. elif os.path.isfile(filepath):
  128. file = os.path.split(filepath)[-1]
  129. try:
  130. docs = load_file(filepath)
  131. print(f"{file} 已成功加载")
  132. loaded_files.append(filepath)
  133. except Exception as e:
  134. print(e)
  135. print(f"{file} 未能成功加载")
  136. return None
  137. elif os.path.isdir(filepath):
  138. docs = []
  139. for file in os.listdir(filepath):
  140. fullfilepath = os.path.join(filepath, file)
  141. try:
  142. docs += load_file(fullfilepath)
  143. print(f"{file} 已成功加载")
  144. loaded_files.append(fullfilepath)
  145. except Exception as e:
  146. print(e)
  147. print(f"{file} 未能成功加载")
  148. else:
  149. docs = []
  150. for file in filepath:
  151. try:
  152. docs += load_file(file)
  153. print(f"{file} 已成功加载")
  154. loaded_files.append(file)
  155. except Exception as e:
  156. print(e)
  157. print(f"{file} 未能成功加载")
  158. if len(docs) > 0:
  159. if vs_path and os.path.isdir(vs_path):
  160. vector_store = FAISS.load_local(vs_path, self.embeddings)
  161. vector_store.add_documents(docs)
  162. torch_gc(DEVICE)
  163. else:
  164. if not vs_path:
  165. vs_path = f"""{VS_ROOT_PATH}{os.path.splitext(file)[0]}_FAISS_{datetime.datetime.now().strftime("%Y%m%d_%H%M%S")}"""
  166. vector_store = FAISS.from_documents(docs, self.embeddings)
  167. torch_gc(DEVICE)
  168. vector_store.save_local(vs_path)
  169. return vs_path, loaded_files
  170. else:
  171. print("文件均未成功加载,请检查依赖包或替换为其他文件再次上传。")
  172. return None, loaded_files
  173. def get_knowledge_based_answer(self,
  174. query,
  175. vs_path,
  176. chat_history=[],
  177. streaming: bool = STREAMING):
  178. vector_store = FAISS.load_local(vs_path, self.embeddings)
  179. FAISS.similarity_search_with_score_by_vector = similarity_search_with_score_by_vector
  180. vector_store.chunk_size = self.chunk_size
  181. related_docs_with_score = vector_store.similarity_search_with_score(query,
  182. k=self.top_k)
  183. related_docs = get_docs_with_score(related_docs_with_score)
  184. prompt = generate_prompt(related_docs, query)
  185. # if streaming:
  186. # for result, history in self.llm._stream_call(prompt=prompt,
  187. # history=chat_history):
  188. # history[-1][0] = query
  189. # response = {"query": query,
  190. # "result": result,
  191. # "source_documents": related_docs}
  192. # yield response, history
  193. # else:
  194. for result, history in self.llm._call(prompt=prompt,
  195. history=chat_history,
  196. streaming=streaming):
  197. history[-1][0] = query
  198. response = {"query": query,
  199. "result": result,
  200. "source_documents": related_docs}
  201. yield response, history
  202. if __name__ == "__main__":
  203. local_doc_qa = LocalDocQA()
  204. local_doc_qa.init_cfg()
  205. query = "你好"
  206. vs_path = "/Users/liuqian/Downloads/glm-dev/vector_store/123"
  207. last_print_len = 0
  208. for resp, history in local_doc_qa.get_knowledge_based_answer(query=query,
  209. vs_path=vs_path,
  210. chat_history=[],
  211. streaming=True):
  212. print(resp["result"][last_print_len:], end="", flush=True)
  213. last_print_len = len(resp["result"])
  214. for resp, history in local_doc_qa.get_knowledge_based_answer(query=query,
  215. vs_path=vs_path,
  216. chat_history=[],
  217. streaming=False):
  218. print(resp["result"])
  219. pass