Spaces:
Build error
Build error
File size: 14,159 Bytes
5bf177b | 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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 | 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})
|