VectorV17 commited on
Commit
1d4a770
Β·
verified Β·
1 Parent(s): 4b79255

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -60
app.py CHANGED
@@ -1,11 +1,11 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
3
 
4
- # CHANGED: Replaced 'zephyr-7b-beta' with 'Qwen2.5-7B-Instruct' which is fully supported
5
- # on Hugging Face's serverless Inference infrastructure out-of-the-box.
6
  client = InferenceClient("Qwen/Qwen2.5-7B-Instruct")
7
 
8
- # Your AI FAQ Agent Knowledge Base context
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
- if "text" in content:
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
- history,
63
  system_message,
64
  max_tokens,
65
  temperature,
66
  top_p,
67
  ):
68
- # Inject your AI FAQ knowledge base directly into the active system message
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 parse conversation history safely (Fixes the ChatMessage .get() error)
78
- if history:
79
- for val in history:
80
- if hasattr(val, "role") and hasattr(val, "content"):
81
- role = val.role
82
- content_str = extract_text(val.content)
83
- if role and content_str:
84
- messages.append({"role": role, "content": content_str})
85
- elif isinstance(val, dict) and "role" in val:
86
- role = val.get("role")
87
- content_str = extract_text(val.get("content") or val.get("text"))
88
- if role and content_str:
89
- messages.append({"role": role, "content": content_str})
90
- elif isinstance(val, (list, tuple)) and len(val) >= 2:
91
- if val[0]:
92
- messages.append({"role": "user", "content": extract_text(val[0])})
93
- if val[1]:
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
- response = ""
 
 
 
 
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
- response += token
114
- yield response
115
  except Exception as e:
116
- yield f"An error occurred while connecting to the model API: {str(e)}"
117
-
118
- # Setup the customized ChatInterface layout
119
- demo = gr.ChatInterface(
120
- respond,
121
- additional_inputs=[
122
- gr.Textbox(
123
- value="You are an expert AI FAQ Agent assistant. Help users understand how websites use FAQ agents across various industries.",
124
- label="System message"
125
- ),
126
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
127
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
128
- gr.Slider(
129
- minimum=0.1,
130
- maximum=1.0,
131
- value=0.95,
132
- step=0.05,
133
- label="Top-p (nucleus sampling)",
134
- ),
135
- ],
136
- title="AI FAQ Agent",
137
- description="Ask queries about tailoring automated customer guidance bots to e-commerce, SaaS, healthcare, and event sites.",
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()