custom-assistant7 / faq_interface.py
Imtaiz's picture
Upload faq_interface.py with huggingface_hub
7bb7d1d verified
Raw History Blame Contribute Delete
14.2 kB
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
Args:
config (dict): Configuration dictionary containing all UI settings and parameters
"""
# 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
# Page configuration
st.set_page_config(page_icon=config.get('PAGE_ICON', '🤖'))
# Custom CSS from original app.py
st.markdown("""
<style>
/* Hide default elements */
header {visibility: hidden;}
footer {visibility: hidden;}
#MainMenu {visibility: hidden;}
/* Basic resets and container setup */
.reportview-container .main .block-container {
padding-top: 0;
max-width: 700px;
padding-right: 1rem;
padding-left: 1rem;
}
/* Animations */
@keyframes fadeIn {
0% {opacity: 0;}
100% {opacity: 1;}
}
@keyframes slideInDown {
0% {
opacity: 0;
transform: translateY(-10px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
@keyframes pulse {
25% {
box-shadow: 0 0 10px rgba(128, 128, 128, 0.5), 0 0 10px rgba(105, 105, 105, 0.3);
}
20% {
box-shadow: 0 0 15px rgba(105, 105, 105, 0.7), 0 0 30px rgba(80, 80, 80, 0.5);
}
200% {
box-shadow: 0 0 10px rgba(128, 128, 128, 0.5), 0 0 20px rgba(105, 105, 105, 0.3);
}
}
@media screen and (max-width: 768px) {
.chat-container,
.stChatInput,
div.stChatInputContainer {
padding-left: 0rem !important;
padding-right: 0rem !important;
}
}
/* Logo and header styling */
.logo-container {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 0;
padding-top: 0.5rem;
}
.round-logo {
width: 120px;
height: 120px;
border-radius: 50%;
margin-top: 0.5rem;
padding: 2px;
opacity: 0;
animation: fadeIn 1.5s ease-out forwards;
object-fit: cover;
aspect-ratio: 1 / 1;
overflow: hidden;
}
.concierge-header {
font-size: 1.25rem;
text-align: center;
margin-top: 0.5rem;
margin-bottom: 0;
font-weight: 500;
}
.concierge-subtitle {
text-align: center;
font-size: 0.9rem;
margin-top: 0.25rem;
margin-bottom: 0.5rem;
padding: 4px 12px;
border-radius: 4px;
animation: highlightText 7s ease-in-out infinite;
display: inline-block;
}
@keyframes highlightText {
0% {
color: rgba(0, 0, 0, 0.6);
background-color: transparent;
}
50% {
color: white;
background-color: #FF7F50;
}
100% {
color: rgba(0, 0, 0, 0.6);
background-color: transparent;
}
}
/* Chat container styling */
.chat-container {
display: flex;
flex-direction: column;
overflow-y: scroll;
padding-bottom: 70px;
margin-top: 0;
gap: 1rem;
width: 100% !important;
max-width: 750px !important;
margin-left: auto !important;
margin-right: auto !important;
padding-left: 1rem !important;
padding-right: 1rem !important;
box-sizing: border-box !important;
}
.stChatMessage {
background-color: #ffffff;
border-radius: 15px;
padding: 1.5rem !important;
margin-bottom: 1rem;
box-shadow: 0 1px 2px rgba(0,0,0,0.1);
word-wrap: break-word !important;
overflow-wrap: break-word !important;
width: 100% !important;
max-width: 100% !important;
}
.stChatMessage p {
word-wrap: break-word !important;
overflow-wrap: break-word !important;
white-space: pre-wrap !important;
margin-bottom: 1rem !important;
}
/* Chat input styling */
.stChatInput {
position: fixed;
bottom: 0;
background: white;
padding: 1rem;
border-top: none !important;
box-shadow: none !important;
width: 100% !important;
max-width: 750px !important;
left: 51% !important;
transform: translateX(-50%) !important;
box-sizing: border-box !important;
}
div.stChatInputContainer {
box-shadow: none !important;
border: none !important;
background: transparent !important;
width: 100% !important;
max-width: 750px !important;
margin: 0 auto !important;
box-sizing: border-box !important;
}
.stChatInput textarea {
border: 1px solid #E3E3E3 !important;
border-radius: 8px !important;
padding: 10px 15px !important;
font-size: 0.9rem !important;
box-shadow: none !important;
background: white !important;
transition: border-color 0.2s ease;
outline: none !important;
-webkit-appearance: none !important;
width: 100% !important;
box-sizing: border-box !important;
}
.stChatInput textarea:focus {
outline: 0 !important;
outline-offset: 0 !important;
border: 1px solid #E3E3E3 !important;
box-shadow: none !important;
-webkit-appearance: none !important;
}
.stButton > button {
background-color: #ffffff !important;
color: #1E88E5 !important;
border: 1px solid #E3E3E3 !important;
border-radius: 8px !important;
padding: 10px 20px !important;
font-size: 0.9rem !important;
font-weight: normal !important;
width: 90% !important;
margin: 0 auto !important;
box-shadow: none !important;
transition: all 0.2s ease;
}
.stButton > button:hover {
background-color: #FF7F50 !important;
color: white !important;
border-color: #FF7F50 !important;
transform: translateY(-1px);
}
/* Utility classes */
.fade-in {
opacity: 0;
animation: fadeIn 1s ease-in forwards;
}
div[data-testid="stVerticalBlock"] > div {
padding: 0;
margin: 0;
}
.typing-indicator {
background-color: #E3E3E3;
padding: 0.5rem 1rem;
border-radius: 20px;
display: inline-block;
animation: pulse 1s infinite;
}
</style>
""", unsafe_allow_html=True)
# Load JavaScript for handling scrolling
st.markdown("""
<script>
function scrollToStarters() {
setTimeout(() => {
const container = document.querySelector('.chat-container');
if (container) {
container.scrollTop = container.scrollHeight / 2;
}
}, 1000);
}
window.addEventListener('load', scrollToStarters);
</script>
""", unsafe_allow_html=True)
# Logo and header
st.markdown(f"""
<div class="logo-container">
<img src="{config['LOGO_URL']}" alt="Logo" class="round-logo">
<div class="concierge-header">{config['AGENT_NAME']}</div>
<div class="concierge-subtitle">{config.get('AGENT_SUBTITLE', 'Your AI Assistant')}</div>
</div>
""", unsafe_allow_html=True)
# Initialize session state
if "messages" not in st.session_state:
st.session_state.messages = []
if "conversation_starter_selected" not in st.session_state:
st.session_state.conversation_starter_selected = False
if "conversation_starter" not in st.session_state:
st.session_state.conversation_starter = ""
# Add initial welcome message
if 'welcome_message_displayed' not in st.session_state:
st.session_state.messages.append({"role": "assistant", "content": config.get('WELCOME_MESSAGE', 'Hi! How can I help you today?')})
st.session_state.welcome_message_displayed = True
# Chat container
st.markdown('<div class="chat-container">', unsafe_allow_html=True)
# Display chat messages
for idx, message in enumerate(st.session_state.messages):
with st.chat_message(message["role"], avatar=get_avatar(message["role"])):
if idx == 0 and message["role"] == "assistant":
st.markdown(f'<div class="fade-in">{message["content"]}</div>', unsafe_allow_html=True)
# Conversation starter buttons
if 'CONVERSATION_STARTERS' in config:
col1, col2, col3 = st.columns([1,1,1])
with col2:
for starter in config['CONVERSATION_STARTERS']:
if st.button(starter["text"]):
st.session_state.conversation_starter = starter["text"]
st.session_state.conversation_starter_selected = True
else:
st.markdown(message["content"], unsafe_allow_html=True)
st.markdown('</div>', unsafe_allow_html=True)
# Chat input
thread_id = ensure_single_thread_id()
prompt = st.chat_input(config.get('CHAT_INPUT_PLACEHOLDER', 'Type your message here...'))
if st.session_state.conversation_starter_selected and not prompt:
prompt = st.session_state.conversation_starter
st.session_state.conversation_starter_selected = False
if prompt:
with st.chat_message("user", avatar=get_avatar("user")):
st.markdown(prompt, unsafe_allow_html=True)
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("assistant", avatar=get_avatar("assistant")):
assistant_response = get_assistant_response(prompt, thread_id)
st.session_state.messages.append({"role": "assistant", "content": assistant_response})