Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -39,15 +39,15 @@ Travelers and event attendees are always looking for specific logistical details
|
|
| 39 |
- Examples: Hotels, Airbnb listings, music festivals, business conferences.
|
| 40 |
"""
|
| 41 |
|
| 42 |
-
# Helper function to generate structural ordinal date format matching the UI (e.g., "08th June 2026")
|
| 43 |
def get_thematic_datetime():
|
|
|
|
| 44 |
now = datetime.now()
|
| 45 |
day = now.strftime("%d")
|
| 46 |
if day.endswith("1") and day != "11": suffix = "st"
|
| 47 |
elif day.endswith("2") and day != "12": suffix = "nd"
|
| 48 |
elif day.endswith("3") and day != "13": suffix = "rd"
|
| 49 |
else: suffix = "th"
|
| 50 |
-
return f"{day}{suffix} {now.strftime('%B %Y')} | time: {now.strftime('%I:%M%p').lower()}"
|
| 51 |
|
| 52 |
def extract_text(content):
|
| 53 |
"""Safely extracts plain string text from any Gradio message structure."""
|
|
@@ -62,15 +62,26 @@ def extract_text(content):
|
|
| 62 |
return content.content
|
| 63 |
return str(content)
|
| 64 |
|
| 65 |
-
# Handle system prompts and streaming chat loops
|
| 66 |
def user_side(user_message, history):
|
|
|
|
| 67 |
if not user_message.strip():
|
| 68 |
return "", history
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
def bot_side(history, system_message, max_tokens, temperature, top_p):
|
|
|
|
| 72 |
if not history:
|
| 73 |
-
|
|
|
|
| 74 |
|
| 75 |
full_system_prompt = (
|
| 76 |
f"{system_message}\n\n"
|
|
@@ -79,14 +90,21 @@ def bot_side(history, system_message, max_tokens, temperature, top_p):
|
|
| 79 |
)
|
| 80 |
|
| 81 |
messages = [{"role": "system", "content": full_system_prompt}]
|
| 82 |
-
|
|
|
|
| 83 |
for msg in history:
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
-
|
| 90 |
|
| 91 |
try:
|
| 92 |
for message_chunk in client.chat_completion(
|
|
@@ -98,11 +116,11 @@ def bot_side(history, system_message, max_tokens, temperature, top_p):
|
|
| 98 |
):
|
| 99 |
token = message_chunk.choices[0].delta.content
|
| 100 |
if token is not None:
|
| 101 |
-
|
| 102 |
-
yield
|
| 103 |
except Exception as e:
|
| 104 |
-
|
| 105 |
-
yield
|
| 106 |
|
| 107 |
# Custom UI Theme Stylesheet
|
| 108 |
custom_css = """
|
|
@@ -170,12 +188,10 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
|
|
| 170 |
with gr.Column(scale=1):
|
| 171 |
gr.HTML(f"<div style='text-align: right; font-weight: 500; font-size: 14px;'>{get_thematic_datetime()}</div>")
|
| 172 |
toggle_btn = gr.Button("☀️/🌙 ➔ Change Mode (Day / Night)", elem_id="toggle-mode-btn")
|
| 173 |
-
# JavaScript layer injected out-of-the-box to shift between native light/dark frameworks
|
| 174 |
toggle_btn.click(None, None, None, js="() => document.body.classList.toggle('dark')")
|
| 175 |
|
| 176 |
# 2. Workspace Layout
|
| 177 |
with gr.Row():
|
| 178 |
-
# Left Panel (Chat interface & Prompt recommendations)
|
| 179 |
with gr.Column(scale=2):
|
| 180 |
chatbot = gr.Chatbot(
|
| 181 |
label="Lane AI Support Stream",
|
|
@@ -191,12 +207,10 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
|
|
| 191 |
)
|
| 192 |
send_btn = gr.Button("Send", variant="primary", scale=1, elem_id="send-btn")
|
| 193 |
|
| 194 |
-
# Interactive Suggestion Pill Buttons
|
| 195 |
with gr.Row():
|
| 196 |
suggest_btn1 = gr.Button("What is the course refund policy?")
|
| 197 |
suggest_btn2 = gr.Button("How do I unlock my completion certificate?")
|
| 198 |
|
| 199 |
-
# Right Panel (Thematic Avatar Identity Card)
|
| 200 |
with gr.Column(scale=1):
|
| 201 |
with gr.Card(elem_id="right-meta-card"):
|
| 202 |
gr.HTML(
|
|
@@ -217,7 +231,6 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
|
|
| 217 |
"""
|
| 218 |
)
|
| 219 |
|
| 220 |
-
# Collapse System Variables to Keep Layout Tidy
|
| 221 |
with gr.Accordion("Advanced Agent Parameter Configurations", open=False):
|
| 222 |
system_msg = gr.Textbox(
|
| 223 |
value="You are an expert AI FAQ Agent assistant. Help users understand how websites use FAQ agents across various industries.",
|
|
@@ -227,8 +240,8 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
|
|
| 227 |
temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
|
| 228 |
top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (Nucleus Sampling)")
|
| 229 |
|
| 230 |
-
# 3.
|
| 231 |
-
|
| 232 |
user_side, inputs=[msg_input, chatbot], outputs=[msg_input, chatbot], queue=False
|
| 233 |
).then(
|
| 234 |
bot_side, inputs=[chatbot, system_msg, max_tokens, temperature, top_p], outputs=[chatbot]
|
|
@@ -240,7 +253,6 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Default()) as demo:
|
|
| 240 |
bot_side, inputs=[chatbot, system_msg, max_tokens, temperature, top_p], outputs=[chatbot]
|
| 241 |
)
|
| 242 |
|
| 243 |
-
# Make suggestion buttons immediately clear text input and trigger model streaming responses
|
| 244 |
suggest_btn1.click(
|
| 245 |
user_side, inputs=[suggest_btn1, chatbot], outputs=[msg_input, chatbot], queue=False
|
| 246 |
).then(
|
|
|
|
| 39 |
- Examples: Hotels, Airbnb listings, music festivals, business conferences.
|
| 40 |
"""
|
| 41 |
|
|
|
|
| 42 |
def get_thematic_datetime():
|
| 43 |
+
"""Generates precise ordinal date strings matching the UI (e.g., '08th June 2026')"""
|
| 44 |
now = datetime.now()
|
| 45 |
day = now.strftime("%d")
|
| 46 |
if day.endswith("1") and day != "11": suffix = "st"
|
| 47 |
elif day.endswith("2") and day != "12": suffix = "nd"
|
| 48 |
elif day.endswith("3") and day != "13": suffix = "rd"
|
| 49 |
else: suffix = "th"
|
| 50 |
+
return f"{day}{suffix} {now.strftime('%B %Y').lower()} | time: {now.strftime('%I:%M%p').lower()}"
|
| 51 |
|
| 52 |
def extract_text(content):
|
| 53 |
"""Safely extracts plain string text from any Gradio message structure."""
|
|
|
|
| 62 |
return content.content
|
| 63 |
return str(content)
|
| 64 |
|
|
|
|
| 65 |
def user_side(user_message, history):
|
| 66 |
+
"""Handles incoming user messages and sanitizes state history format."""
|
| 67 |
if not user_message.strip():
|
| 68 |
return "", history
|
| 69 |
+
|
| 70 |
+
clean_history = []
|
| 71 |
+
for msg in history:
|
| 72 |
+
if isinstance(msg, dict):
|
| 73 |
+
clean_history.append({"role": msg["role"], "content": extract_text(msg["content"])})
|
| 74 |
+
elif hasattr(msg, "role") and hasattr(msg, "content"):
|
| 75 |
+
clean_history.append({"role": msg.role, "content": extract_text(msg.content)})
|
| 76 |
+
|
| 77 |
+
clean_history.append({"role": "user", "content": user_message})
|
| 78 |
+
return "", clean_history
|
| 79 |
|
| 80 |
def bot_side(history, system_message, max_tokens, temperature, top_p):
|
| 81 |
+
"""Streams responses out to the layout without throwing Object mutation errors."""
|
| 82 |
if not history:
|
| 83 |
+
yield history
|
| 84 |
+
return
|
| 85 |
|
| 86 |
full_system_prompt = (
|
| 87 |
f"{system_message}\n\n"
|
|
|
|
| 90 |
)
|
| 91 |
|
| 92 |
messages = [{"role": "system", "content": full_system_prompt}]
|
| 93 |
+
clean_history = []
|
| 94 |
+
|
| 95 |
for msg in history:
|
| 96 |
+
if isinstance(msg, dict):
|
| 97 |
+
role = msg.get("role")
|
| 98 |
+
content = extract_text(msg.get("content"))
|
| 99 |
+
else:
|
| 100 |
+
role = getattr(msg, "role", None)
|
| 101 |
+
content = extract_text(getattr(msg, "content", ""))
|
| 102 |
+
|
| 103 |
+
if role and content:
|
| 104 |
+
messages.append({"role": role, "content": content})
|
| 105 |
+
clean_history.append({"role": role, "content": content})
|
| 106 |
|
| 107 |
+
clean_history.append({"role": "assistant", "content": ""})
|
| 108 |
|
| 109 |
try:
|
| 110 |
for message_chunk in client.chat_completion(
|
|
|
|
| 116 |
):
|
| 117 |
token = message_chunk.choices[0].delta.content
|
| 118 |
if token is not None:
|
| 119 |
+
clean_history[-1]["content"] += token
|
| 120 |
+
yield clean_history
|
| 121 |
except Exception as e:
|
| 122 |
+
clean_history[-1]["content"] = f"An error occurred while connecting to the model API: {str(e)}"
|
| 123 |
+
yield clean_history
|
| 124 |
|
| 125 |
# Custom UI Theme Stylesheet
|
| 126 |
custom_css = """
|
|
|
|
| 188 |
with gr.Column(scale=1):
|
| 189 |
gr.HTML(f"<div style='text-align: right; font-weight: 500; font-size: 14px;'>{get_thematic_datetime()}</div>")
|
| 190 |
toggle_btn = gr.Button("☀️/🌙 ➔ Change Mode (Day / Night)", elem_id="toggle-mode-btn")
|
|
|
|
| 191 |
toggle_btn.click(None, None, None, js="() => document.body.classList.toggle('dark')")
|
| 192 |
|
| 193 |
# 2. Workspace Layout
|
| 194 |
with gr.Row():
|
|
|
|
| 195 |
with gr.Column(scale=2):
|
| 196 |
chatbot = gr.Chatbot(
|
| 197 |
label="Lane AI Support Stream",
|
|
|
|
| 207 |
)
|
| 208 |
send_btn = gr.Button("Send", variant="primary", scale=1, elem_id="send-btn")
|
| 209 |
|
|
|
|
| 210 |
with gr.Row():
|
| 211 |
suggest_btn1 = gr.Button("What is the course refund policy?")
|
| 212 |
suggest_btn2 = gr.Button("How do I unlock my completion certificate?")
|
| 213 |
|
|
|
|
| 214 |
with gr.Column(scale=1):
|
| 215 |
with gr.Card(elem_id="right-meta-card"):
|
| 216 |
gr.HTML(
|
|
|
|
| 231 |
"""
|
| 232 |
)
|
| 233 |
|
|
|
|
| 234 |
with gr.Accordion("Advanced Agent Parameter Configurations", open=False):
|
| 235 |
system_msg = gr.Textbox(
|
| 236 |
value="You are an expert AI FAQ Agent assistant. Help users understand how websites use FAQ agents across various industries.",
|
|
|
|
| 240 |
temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
|
| 241 |
top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (Nucleus Sampling)")
|
| 242 |
|
| 243 |
+
# 3. Components Event Wiring
|
| 244 |
+
send_btn.click(
|
| 245 |
user_side, inputs=[msg_input, chatbot], outputs=[msg_input, chatbot], queue=False
|
| 246 |
).then(
|
| 247 |
bot_side, inputs=[chatbot, system_msg, max_tokens, temperature, top_p], outputs=[chatbot]
|
|
|
|
| 253 |
bot_side, inputs=[chatbot, system_msg, max_tokens, temperature, top_p], outputs=[chatbot]
|
| 254 |
)
|
| 255 |
|
|
|
|
| 256 |
suggest_btn1.click(
|
| 257 |
user_side, inputs=[suggest_btn1, chatbot], outputs=[msg_input, chatbot], queue=False
|
| 258 |
).then(
|