Sales_Chat.py 5.13 KB
import os

import streamlit as st
from streamlit_chat import message
from utilities.helper import LLMHelper
from dotenv import load_dotenv

load_dotenv()
import threading
import time
import datetime


def clear_text_input():
    st.session_state['question'] = st.session_state['input']
    st.session_state['input'] = ""


def clear_chat_data():
    st.session_state['input'] = ""
    st.session_state['chat_history'] = []
    st.session_state['source_documents'] = []


def worker(question_place):
    print("当前的Pid:"+str(os.getpid()))
    if question_place:
        if len(str(question_place).strip()) != 0:
            # 获取当前日期和时间
            start = datetime.datetime.now()
            # 记录程序开始时间
            start_time = time.perf_counter()
            question, result, _, sources = llm_helper.get_semantic_answer_lang_chain(question_place, [])
            end_time = time.perf_counter()
            end = datetime.datetime.now()
            # 计算程序运行时间
            run_time = end_time - start_time
            print(str(result))
            # print(start.strftime("%Y-%m-%d %H:%M:%S"))
            # print(end.strftime("%Y-%m-%d %H:%M:%S"))
            # print(f"Program start in {start_time:.6f} seconds.")
            # print(f"Program end in {end_time:.6f} seconds.")
            print(f"Program finished in {run_time:.6f} seconds.")

            # st.session_state['chat_history'].append((question, result))
            # st.session_state['chat_history_show'].append((question, result))
            # st.session_state['source_documents'].append(sources)
        # else:
        # st.markdown("系统回复:输入问题有误,请重新输入")

    # if st.session_state['chat_history_show']:
    # for i in range(len(st.session_state['chat_history_show']) - 1, -1, -1):
    # message(st.session_state['chat_history_show'][i][1], key=str(i))
    # st.markdown(f'\n\nSources: {st.session_state["source_documents"][i]}')
    # st.markdown(f'\n\nSources: 广联知识库')
    # message(st.session_state['chat_history_show'][i][0], is_user=True, key=str(i) + '_user')


# Initialize chat history
if 'question' not in st.session_state:
    st.session_state['question'] = None
if 'chat_history' not in st.session_state:
    st.session_state['chat_history'] = []
if 'source_documents' not in st.session_state:
    st.session_state['source_documents'] = []
if 'chat_history_show' not in st.session_state:
    st.session_state['chat_history_show'] = []

llm_helper = LLMHelper()

st.markdown('## 嘀加知识库')
st.text("")
# Chat
st.text_input("你: ", placeholder="输入您的问题", key="input", on_change=clear_text_input)
clear_chat = st.button("清除聊天内容", key="clear_chat", on_click=clear_chat_data)

# threads = []
# questions = [
#              "艾利盾甲太阳膜的颜色太单调了,只有黑的、灰的,有绿色吗?",
#              "太阳光的组成",
#              "玻璃膜基础知识",
#              "为什么要预约?",
#              "没有谁会说⾃⼰家东西是差的,哪有你说的那么好?",
#              "有没有便宜点的膜,我不贴你们这么贵的?",
#              "别家膜也很好啊,⽽且跟你们⼀样也会做隔热测试,效果也差不多,主要是还⽐你家便宜? ",
#              "现在天气不热,等到天热时再贴膜吧?",
#              "我怎么没有听过艾利盾甲太阳膜?",
#              "太阳膜贴完后我们应该注意哪些问题?"
#              ]
# questions = [
#              "太阳光的组成是什么?"
#              ]

# for i in range(5):
#     for j in range(len(questions)):
#         t = threading.Thread(target=worker, args=(questions[j],))
#         threads.append(t)
#
# # 启动线程
# for t in threads:
#     t.start()
#TODO 知识库新增 产品说明书之类知识点

if st.session_state['question']:
    if len(str(st.session_state['question']).strip())!=0:
        question, result, _, sources = llm_helper.get_semantic_answer_lang_chain(st.session_state['question'], st.session_state['chat_history'])
        if result == "网络超时,请重试":
            question, result, _, sources = llm_helper.get_semantic_answer_lang_chain(st.session_state['question'],
                                                                                     st.session_state['chat_history'])
        st.session_state['chat_history'].append((question, result))
        now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        print(now,result)
        st.session_state['chat_history_show'].append((question, result))
        st.session_state['source_documents'].append(sources)
        st.session_state['question'] = ""
    else:
        st.markdown("系统回复:输入问题有误,请重新输入")

if st.session_state['chat_history_show']:
    for i in range(len(st.session_state['chat_history_show'])-1, -1, -1):
        message(st.session_state['chat_history_show'][i][1], key=str(i))
        # st.markdown(f'\n\nSources: {st.session_state["source_documents"][i]}')
        st.markdown(f'\n\nSources: 嘀加知识库')
        message(st.session_state['chat_history_show'][i][0], is_user=True, key=str(i) + '_user')