File size: 3,923 Bytes
21723c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import streamlit as st
import time
from openai import OpenAI
import os
from dotenv import load_dotenv

def run_interface(config=None):
    '''Run the FAQ interface with dynamic configuration'''
    # Load environment variables
    load_dotenv()

    # Setup OpenAI client
    openai_api_key = os.environ.get('OPENAI_API_KEY')
    if not openai_api_key:
        st.error('OpenAI API key not found. Please add it to your environment variables.')
        st.stop()

    client = OpenAI(api_key=openai_api_key)

    def ensure_single_thread_id():
        if "thread_id" not in st.session_state:
            thread = client.beta.threads.create()
            st.session_state.thread_id = thread.id
        return st.session_state.thread_id

    def get_avatar(role):
        return config.get('AVATAR_CONFIG', {}).get(role)

    def get_assistant_response(prompt, thread_id):
        message_placeholder = st.empty()
        i = 0

        client.beta.threads.messages.create(
            thread_id=thread_id,
            role="user",
            content=prompt
        )

        stream = client.beta.threads.runs.create(
            thread_id=thread_id,
            assistant_id=config['ASSISTANT_ID'],
            stream=True
        )

        full_response = ""

        for event in stream:
            if not full_response:
                message_placeholder.markdown(f"*Thinking{config['THINKING_DOTS'][i % len(config['THINKING_DOTS'])]}*", unsafe_allow_html=True)
                i += 1
                time.sleep(config['THINKING_INTERVAL'])

            if event.data.object == "thread.message.delta":
                for content in event.data.delta.content:
                    if content.type == 'text':
                        chunk = content.text.value
                        full_response += chunk

                        lines = full_response.split('\n')
                        cleaned_lines = []
                        for line in lines:
                            cleaned_line = ' '.join([part.strip() for part in line.split('【') if '】' not in part])
                            cleaned_line = cleaned_line.strip()
                            if cleaned_line:
                                if cleaned_line[0].isdigit() and '. ' in cleaned_line:
                                    cleaned_lines.append(cleaned_line + '\n')
                                else:
                                    cleaned_lines.append(cleaned_line)

                        formatted_response = '\n'.join(cleaned_lines)
                        message_placeholder.markdown(formatted_response)
                        time.sleep(0.01)

        return full_response

    # Load CSS and initialize interface
    st.markdown('''<style>
        /* Add your custom CSS here */
        .stApp {
            max-width: 1200px;
            margin: 0 auto;
        }
    </style>''', unsafe_allow_html=True)

    # Initialize chat interface
    thread_id = ensure_single_thread_id()

    # Display chat messages
    if "messages" not in st.session_state:
        st.session_state.messages = []
        st.session_state.messages.append({
            "role": "assistant",
            "content": config.get('WELCOME_MESSAGE', 'Hi! How can I help you today?')
        })

    for message in st.session_state.messages:
        with st.chat_message(message["role"], avatar=get_avatar(message["role"])):
            st.markdown(message["content"])

    # Chat input
    if prompt := st.chat_input("Type your message here..."):
        st.session_state.messages.append({"role": "user", "content": prompt})
        with st.chat_message("user", avatar=get_avatar("user")):
            st.markdown(prompt)

        with st.chat_message("assistant", avatar=get_avatar("assistant")):
            response = get_assistant_response(prompt, thread_id)
            st.session_state.messages.append({"role": "assistant", "content": response})