Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,11 +1,11 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
|
|
|
| 3 |
|
| 4 |
-
#
|
| 5 |
-
# on Hugging Face's serverless Inference infrastructure out-of-the-box.
|
| 6 |
client = InferenceClient("Qwen/Qwen2.5-7B-Instruct")
|
| 7 |
|
| 8 |
-
#
|
| 9 |
FAQ_CONTEXT = """
|
| 10 |
An AI FAQ Agent can be adapted for almost any website where users have questions, need guidance, or require support. If people visit your site and need to find information, an FAQ agent can help. Here is a breakdown of the most common types of websites that benefit from an FAQ Agent, categorized by industry:
|
| 11 |
|
|
@@ -39,33 +39,58 @@ Travelers and event attendees are always looking for specific logistical details
|
|
| 39 |
- Examples: Hotels, Airbnb listings, music festivals, business conferences.
|
| 40 |
"""
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
def extract_text(content):
|
| 43 |
-
"""
|
| 44 |
-
Safely extracts plain string text from any Gradio message structure,
|
| 45 |
-
handling strings, dictionaries, or custom Gradio ChatMessage objects.
|
| 46 |
-
"""
|
| 47 |
if isinstance(content, str):
|
| 48 |
return content
|
| 49 |
if isinstance(content, dict):
|
| 50 |
-
|
| 51 |
-
return content["text"]
|
| 52 |
-
if "content" in content:
|
| 53 |
-
return content["content"]
|
| 54 |
if hasattr(content, "text") and isinstance(content.text, str):
|
| 55 |
return content.text
|
| 56 |
if hasattr(content, "content") and isinstance(content.content, str):
|
| 57 |
return content.content
|
| 58 |
return str(content)
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
def respond(
|
| 61 |
message,
|
| 62 |
-
|
| 63 |
system_message,
|
| 64 |
max_tokens,
|
| 65 |
temperature,
|
| 66 |
top_p,
|
| 67 |
):
|
| 68 |
-
#
|
| 69 |
full_system_prompt = (
|
| 70 |
f"{system_message}\n\n"
|
| 71 |
f"Use the following FAQ reference context to answer questions accurately:\n"
|
|
@@ -74,33 +99,34 @@ def respond(
|
|
| 74 |
|
| 75 |
messages = [{"role": "system", "content": full_system_prompt}]
|
| 76 |
|
| 77 |
-
# Cleanse and
|
| 78 |
-
if
|
| 79 |
-
for
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
if
|
| 89 |
-
messages.append({"role":
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
messages.append({"role": "assistant", "content": extract_text(val[1])})
|
| 95 |
-
|
| 96 |
-
# Cleanse and parse current incoming user message
|
| 97 |
user_content_str = extract_text(message)
|
| 98 |
messages.append({"role": "user", "content": user_content_str})
|
| 99 |
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
-
# Stream responses back reliably from the new model API
|
| 103 |
try:
|
|
|
|
| 104 |
for message_chunk in client.chat_completion(
|
| 105 |
messages,
|
| 106 |
max_tokens=max_tokens,
|
|
@@ -110,32 +136,93 @@ def respond(
|
|
| 110 |
):
|
| 111 |
token = message_chunk.choices[0].delta.content
|
| 112 |
if token is not None:
|
| 113 |
-
|
| 114 |
-
yield
|
| 115 |
except Exception as e:
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
gr.
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
if __name__ == "__main__":
|
| 141 |
demo.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
+
from datetime import datetime
|
| 4 |
|
| 5 |
+
# Powered by an active provider endpoint on HF serverless framework
|
|
|
|
| 6 |
client = InferenceClient("Qwen/Qwen2.5-7B-Instruct")
|
| 7 |
|
| 8 |
+
# Static grounding data asset for the Agentic Architecture
|
| 9 |
FAQ_CONTEXT = """
|
| 10 |
An AI FAQ Agent can be adapted for almost any website where users have questions, need guidance, or require support. If people visit your site and need to find information, an FAQ agent can help. Here is a breakdown of the most common types of websites that benefit from an FAQ Agent, categorized by industry:
|
| 11 |
|
|
|
|
| 39 |
- Examples: Hotels, Airbnb listings, music festivals, business conferences.
|
| 40 |
"""
|
| 41 |
|
| 42 |
+
# Custom thematic CSS to styling cards, status panels, and the toggle buttons
|
| 43 |
+
CUSTOM_CSS = """
|
| 44 |
+
.agent-header {
|
| 45 |
+
background: linear-gradient(135deg, #2b5876 0%, #4e4376 100%);
|
| 46 |
+
color: white;
|
| 47 |
+
padding: 24px;
|
| 48 |
+
border-radius: 12px;
|
| 49 |
+
margin-bottom: 15px;
|
| 50 |
+
box-shadow: 0 4px 15px rgba(0,0,0,0.15);
|
| 51 |
+
}
|
| 52 |
+
.dark .agent-header {
|
| 53 |
+
background: linear-gradient(135deg, #141e30 0%, #243b55 100%);
|
| 54 |
+
}
|
| 55 |
+
.meta-panel {
|
| 56 |
+
background: rgba(255, 255, 255, 0.1);
|
| 57 |
+
padding: 8px 15px;
|
| 58 |
+
border-radius: 8px;
|
| 59 |
+
font-size: 0.95em;
|
| 60 |
+
font-family: monospace;
|
| 61 |
+
display: inline-block;
|
| 62 |
+
}
|
| 63 |
+
.toggle-btn {
|
| 64 |
+
max-width: 150px !important;
|
| 65 |
+
}
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
def extract_text(content):
|
| 69 |
+
"""Safely extracts plain string data from Gradio Chat history structures."""
|
|
|
|
|
|
|
|
|
|
| 70 |
if isinstance(content, str):
|
| 71 |
return content
|
| 72 |
if isinstance(content, dict):
|
| 73 |
+
return content.get("text", content.get("content", str(content)))
|
|
|
|
|
|
|
|
|
|
| 74 |
if hasattr(content, "text") and isinstance(content.text, str):
|
| 75 |
return content.text
|
| 76 |
if hasattr(content, "content") and isinstance(content.content, str):
|
| 77 |
return content.content
|
| 78 |
return str(content)
|
| 79 |
|
| 80 |
+
def update_timestamp():
|
| 81 |
+
"""Generates a dynamic real-time clock panel string."""
|
| 82 |
+
now = datetime.now()
|
| 83 |
+
return f"π {now.strftime('%A, %B %d, %Y | %I:%M:%S %p')}"
|
| 84 |
+
|
| 85 |
def respond(
|
| 86 |
message,
|
| 87 |
+
chat_history,
|
| 88 |
system_message,
|
| 89 |
max_tokens,
|
| 90 |
temperature,
|
| 91 |
top_p,
|
| 92 |
):
|
| 93 |
+
# Anchor system parameters and context data inside root payload
|
| 94 |
full_system_prompt = (
|
| 95 |
f"{system_message}\n\n"
|
| 96 |
f"Use the following FAQ reference context to answer questions accurately:\n"
|
|
|
|
| 99 |
|
| 100 |
messages = [{"role": "system", "content": full_system_prompt}]
|
| 101 |
|
| 102 |
+
# Cleanse and build conversation history state sequentially
|
| 103 |
+
if chat_history:
|
| 104 |
+
for turn in chat_history:
|
| 105 |
+
# Handles dictionary structure standard in modern Gradio
|
| 106 |
+
if isinstance(turn, dict):
|
| 107 |
+
role = turn.get("role")
|
| 108 |
+
content = extract_text(turn.get("content") or turn.get("text"))
|
| 109 |
+
if role and content:
|
| 110 |
+
messages.append({"role": role, "content": content})
|
| 111 |
+
# Handles tuple/list structures from historical versions
|
| 112 |
+
elif isinstance(turn, (list, tuple)) and len(turn) >= 2:
|
| 113 |
+
if turn[0]:
|
| 114 |
+
messages.append({"role": "user", "content": extract_text(turn[0])})
|
| 115 |
+
if turn[1]:
|
| 116 |
+
messages.append({"role": "assistant", "content": extract_text(turn[1])})
|
| 117 |
+
|
| 118 |
+
# Append current message text
|
|
|
|
|
|
|
|
|
|
| 119 |
user_content_str = extract_text(message)
|
| 120 |
messages.append({"role": "user", "content": user_content_str})
|
| 121 |
|
| 122 |
+
# Initialize message list updates for modern stateful block tracking
|
| 123 |
+
updated_history = chat_history + [
|
| 124 |
+
{"role": "user", "content": user_content_str},
|
| 125 |
+
{"role": "assistant", "content": ""}
|
| 126 |
+
]
|
| 127 |
|
|
|
|
| 128 |
try:
|
| 129 |
+
# Request stream from backend serverless cluster
|
| 130 |
for message_chunk in client.chat_completion(
|
| 131 |
messages,
|
| 132 |
max_tokens=max_tokens,
|
|
|
|
| 136 |
):
|
| 137 |
token = message_chunk.choices[0].delta.content
|
| 138 |
if token is not None:
|
| 139 |
+
updated_history[-1]["content"] += token
|
| 140 |
+
yield "", updated_history
|
| 141 |
except Exception as e:
|
| 142 |
+
updated_history[-1]["content"] = f"An error occurred while connecting to the model API: {str(e)}"
|
| 143 |
+
yield "", updated_history
|
| 144 |
+
|
| 145 |
+
# Initialize customizable custom-themed layout frame
|
| 146 |
+
with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft()) as demo:
|
| 147 |
+
|
| 148 |
+
# Top Control and Info Strip
|
| 149 |
+
with gr.Row():
|
| 150 |
+
with gr.Column(scale=8):
|
| 151 |
+
# Dynamic Live Date & Time Tracker Panel updated automatically
|
| 152 |
+
timestamp_box = gr.Markdown(value=update_timestamp(), elem_classes=["meta-panel"])
|
| 153 |
+
with gr.Column(scale=2, min_width=150):
|
| 154 |
+
# Day/Night Mode Switch Trigger via Gradio JavaScript Engine
|
| 155 |
+
theme_toggle = gr.Button("π Dark Mode", elem_classes=["toggle-btn"])
|
| 156 |
+
|
| 157 |
+
# Automatically refresh time indicator string every 1 second
|
| 158 |
+
demo.load(fn=update_timestamp, outputs=timestamp_box, every=1.0)
|
| 159 |
+
|
| 160 |
+
# JavaScript logic binding for the Theme Toggle Switch
|
| 161 |
+
theme_toggle.click(
|
| 162 |
+
fn=None,
|
| 163 |
+
js="""
|
| 164 |
+
() => {
|
| 165 |
+
document.body.classList.toggle('dark');
|
| 166 |
+
const isDark = document.body.classList.contains('dark');
|
| 167 |
+
return isDark ? "βοΈ Light Mode" : "π Dark Mode";
|
| 168 |
+
}
|
| 169 |
+
""",
|
| 170 |
+
outputs=theme_toggle
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# Master Headers and System Details Box
|
| 174 |
+
with gr.Div(elem_classes=["agent-header"]):
|
| 175 |
+
gr.Markdown("# π§ System Context-Based AI FAQ Agent")
|
| 176 |
+
gr.Markdown(
|
| 177 |
+
"### *Agentic Architecture Grounding Demonstration*\n"
|
| 178 |
+
"This workspace operates using a **System Context-Based (Agentic) Approach**. "
|
| 179 |
+
"Unlike raw LLM queries, this agent is explicitly grounded via immutable system context instructions. "
|
| 180 |
+
"It maps incoming user data safely against isolated domain intelligence vectors in real time, preventing context drift."
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
# Core Application Workspace Split
|
| 184 |
+
with gr.Row():
|
| 185 |
+
with gr.Column(scale=7):
|
| 186 |
+
# Interactive Stream Chat Window Interface
|
| 187 |
+
chatbot = gr.Chatbot(type="messages", height=500, show_label=False)
|
| 188 |
+
|
| 189 |
+
with gr.Row():
|
| 190 |
+
user_input = gr.Textbox(
|
| 191 |
+
show_label=False,
|
| 192 |
+
placeholder="Ask questions about tailoring automated customer guidance bots...",
|
| 193 |
+
container=False,
|
| 194 |
+
scale=8
|
| 195 |
+
)
|
| 196 |
+
submit_btn = gr.Button("Send", variant="primary", scale=2)
|
| 197 |
+
|
| 198 |
+
clear_btn = gr.Button("ποΈ Clear Conversation History")
|
| 199 |
+
|
| 200 |
+
# Configurations Panel Sidebar
|
| 201 |
+
with gr.Column(scale=3):
|
| 202 |
+
with gr.Accordion("System Settings & Grounding Metrics", open=True):
|
| 203 |
+
system_msg = gr.Textbox(
|
| 204 |
+
value="You are an expert AI FAQ Agent assistant. Help users understand how websites use FAQ agents across various industries.",
|
| 205 |
+
label="Active Persona Rule",
|
| 206 |
+
lines=3
|
| 207 |
+
)
|
| 208 |
+
max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max Generated Tokens")
|
| 209 |
+
temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Sampling Temperature")
|
| 210 |
+
top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p Sampling Window")
|
| 211 |
+
|
| 212 |
+
# Binding input pipelines safely across the context state configurations
|
| 213 |
+
submit_event = submit_btn.click(
|
| 214 |
+
fn=respond,
|
| 215 |
+
inputs=[user_input, chatbot, system_msg, max_tokens, temperature, top_p],
|
| 216 |
+
outputs=[user_input, chatbot]
|
| 217 |
+
)
|
| 218 |
+
user_input.submit(
|
| 219 |
+
fn=respond,
|
| 220 |
+
inputs=[user_input, chatbot, system_msg, max_tokens, temperature, top_p],
|
| 221 |
+
outputs=[user_input, chatbot]
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
# Session memory wiping logic tracking
|
| 225 |
+
clear_btn.click(fn=lambda: [], outputs=chatbot)
|
| 226 |
|
| 227 |
if __name__ == "__main__":
|
| 228 |
demo.launch()
|