Langchain-Chatchat/cli_demo.py

44 lines
2.0 KiB
Python
Raw Normal View History

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