cli_demo.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from configs.model_config import *
  2. from chains.local_doc_qa import LocalDocQA
  3. import os
  4. import nltk
  5. nltk.data.path = [NLTK_DATA_PATH] + nltk.data.path
  6. # Show reply with source text from input document
  7. REPLY_WITH_SOURCE = True
  8. if __name__ == "__main__":
  9. local_doc_qa = LocalDocQA()
  10. local_doc_qa.init_cfg(llm_model=LLM_MODEL,
  11. embedding_model=EMBEDDING_MODEL,
  12. embedding_device=EMBEDDING_DEVICE,
  13. llm_history_len=LLM_HISTORY_LEN,
  14. top_k=VECTOR_SEARCH_TOP_K)
  15. vs_path = None
  16. while not vs_path:
  17. filepath = input("Input your local knowledge file path 请输入本地知识文件路径:")
  18. # 判断 filepath 是否为空,如果为空的话,重新让用户输入,防止用户误触回车
  19. if not filepath:
  20. continue
  21. vs_path, _ = local_doc_qa.init_knowledge_vector_store(filepath)
  22. history = []
  23. while True:
  24. query = input("Input your question 请输入问题:")
  25. last_print_len = 0
  26. for resp, history in local_doc_qa.get_knowledge_based_answer(query=query,
  27. vs_path=vs_path,
  28. chat_history=history,
  29. streaming=STREAMING):
  30. if STREAMING:
  31. print(resp["result"][last_print_len:], end="", flush=True)
  32. last_print_len = len(resp["result"])
  33. else:
  34. print(resp["result"])
  35. if REPLY_WITH_SOURCE:
  36. source_text = [f"""出处 [{inum + 1}] {os.path.split(doc.metadata['source'])[-1]}:\n\n{doc.page_content}\n\n"""
  37. # f"""相关度:{doc.metadata['score']}\n\n"""
  38. for inum, doc in
  39. enumerate(resp["source_documents"])]
  40. print("\n\n" + "\n\n".join(source_text))