local_doc_qa.py 5.3 KB

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