Luigi commited on
Commit
eb215ff
·
1 Parent(s): 35943b1

UI/UX Improvement

Browse files
Files changed (1) hide show
  1. app.py +161 -110
app.py CHANGED
@@ -6,7 +6,9 @@ from llama_cpp.llama_speculative import LlamaPromptLookupDecoding
6
  from huggingface_hub import hf_hub_download
7
  from duckduckgo_search import DDGS
8
 
9
- # ---- Initialize session state ----
 
 
10
  if "chat_history" not in st.session_state:
11
  st.session_state.chat_history = []
12
  if "pending_response" not in st.session_state:
@@ -16,34 +18,24 @@ if "model_name" not in st.session_state:
16
  if "llm" not in st.session_state:
17
  st.session_state.llm = None
18
 
19
- # ---- Custom CSS ----
 
 
20
  st.markdown("""
21
  <style>
22
- ul.think-list { margin: 0.5em 0 1em 1.5em; padding: 0; list-style-type: disc; }
23
- ul.think-list li { margin-bottom: 0.5em; }
24
- .chat-assistant { background-color: #f9f9f9; padding: 1em; border-radius: 5px; margin-bottom: 1em; }
 
 
25
  </style>
26
  """, unsafe_allow_html=True)
27
 
28
- # ---- Required storage space ----
 
 
29
  REQUIRED_SPACE_BYTES = 5 * 1024 ** 3 # 5 GB
30
 
31
- # ---- Function to retrieve web search context ----
32
- def retrieve_context(query, max_results=6, max_chars_per_result=600):
33
- try:
34
- with DDGS() as ddgs:
35
- results = list(islice(ddgs.text(query, region="wt-wt", safesearch="off", timelimit="y"), max_results))
36
- context = ""
37
- for i, result in enumerate(results, start=1):
38
- title = result.get("title", "No Title")
39
- snippet = result.get("body", "")[:max_chars_per_result]
40
- context += f"Result {i}:\nTitle: {title}\nSnippet: {snippet}\n\n"
41
- return context.strip()
42
- except Exception as e:
43
- st.error(f"Error during retrieval: {e}")
44
- return ""
45
-
46
- # ---- Model definitions ----
47
  MODELS = {
48
  "Qwen2.5-0.5B-Instruct (Q4_K_M)": {
49
  "repo_id": "Qwen/Qwen2.5-0.5B-Instruct-GGUF",
@@ -102,33 +94,30 @@ MODELS = {
102
  },
103
  }
104
 
105
- # ----- Sidebar settings -----
106
- # ----- Sidebar settings -----
107
- with st.sidebar:
108
- st.header("⚙️ Settings")
109
- selected_model_name = st.selectbox("Select Model", list(MODELS.keys()))
110
- system_prompt_base = st.text_area("System Prompt", value="You are a helpful assistant.", height=80)
111
- max_tokens = st.slider("Max tokens", 64, 1024, 256, step=32)
112
- temperature = st.slider("Temperature", 0.1, 2.0, 0.7)
113
- top_k = st.slider("Top-K", 1, 100, 40)
114
- top_p = st.slider("Top-P", 0.1, 1.0, 0.95)
115
- repeat_penalty = st.slider("Repetition Penalty", 1.0, 2.0, 1.1)
116
- enable_search = st.checkbox("Enable Web Search", value=False)
117
-
118
- # NEW SETTINGS: Expose search configuration
119
- max_results = st.number_input("Max Results for Context", min_value=1, max_value=20, value=6, step=1)
120
- max_chars_per_result = st.number_input("Max Chars Per Result", min_value=100, max_value=2000, value=600, step=50)
121
-
122
- # ---- Define selected model and manage its download/load ----
123
- selected_model = MODELS[selected_model_name]
124
- model_path = os.path.join("models", selected_model["filename"])
125
- os.makedirs("models", exist_ok=True)
126
 
127
- def try_load_model(path):
 
128
  try:
129
  return Llama(
130
- model_path=path,
131
- n_ctx=4096, # Reduced context window
132
  n_threads=2,
133
  n_threads_batch=1,
134
  n_batch=256,
@@ -142,7 +131,8 @@ def try_load_model(path):
142
  except Exception as e:
143
  return str(e)
144
 
145
- def download_model():
 
146
  with st.spinner(f"Downloading {selected_model['filename']}..."):
147
  hf_hub_download(
148
  repo_id=selected_model["repo_id"],
@@ -151,63 +141,142 @@ def download_model():
151
  local_dir_use_symlinks=False,
152
  )
153
 
154
- def validate_or_download_model():
 
 
 
155
  if not os.path.exists(model_path):
156
  if shutil.disk_usage(".").free < REQUIRED_SPACE_BYTES:
157
- st.info("Insufficient storage. Consider cleaning up old models.")
158
- download_model()
159
  result = try_load_model(model_path)
160
  if isinstance(result, str):
161
- st.warning(f"Initial load failed: {result}\nRe-downloading...")
162
  try:
163
  os.remove(model_path)
164
  except Exception:
165
  pass
166
- download_model()
167
  result = try_load_model(model_path)
168
  if isinstance(result, str):
169
- st.error(f"Model still failed after re-download: {result}")
170
  st.stop()
171
  return result
172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  if st.session_state.model_name != selected_model_name:
174
- if st.session_state.llm is not None:
175
- del st.session_state.llm
176
- gc.collect()
177
- st.session_state.llm = validate_or_download_model()
178
- st.session_state.model_name = selected_model_name
 
179
 
180
  llm = st.session_state.llm
181
 
182
- # ---- Display title and existing chat history ----
 
 
183
  st.title(f"🧠 {selected_model['description']} (Streamlit + GGUF)")
184
  st.caption(f"Powered by `llama.cpp` | Model: {selected_model['filename']}")
185
 
 
186
  for chat in st.session_state.chat_history:
187
- with st.chat_message(chat["role"]):
188
- st.markdown(chat["content"])
 
 
 
 
189
 
190
- # ---- Chat input and processing ----
191
- user_input = st.chat_input("Ask something...")
 
 
192
  if user_input:
193
  if st.session_state.pending_response:
194
- st.warning("Please wait for the assistant to finish responding.")
195
  else:
196
- # Display user input and update chat history
 
 
197
  with st.chat_message("user"):
198
- st.markdown(user_input)
199
- st.session_state.chat_history.append({"role": "user", "content": user_input})
200
  st.session_state.pending_response = True
 
 
 
 
 
 
 
 
201
 
202
- # Use the new settings when retrieving web search context
203
- retrieved_context = (
204
- retrieve_context(user_input, max_results=max_results, max_chars_per_result=max_chars_per_result)
205
- if enable_search else ""
206
- )
207
- st.sidebar.markdown("### Retrieved Context" if enable_search else "Web Search Disabled")
208
- st.sidebar.text(retrieved_context or "No context found.")
209
-
210
- # Build augmented query as before...
211
  if enable_search and retrieved_context:
212
  augmented_user_input = (
213
  f"{system_prompt_base.strip()}\n\n"
@@ -217,8 +286,8 @@ if user_input:
217
  )
218
  else:
219
  augmented_user_input = f"{system_prompt_base.strip()}\n\nUser Query: {user_input}"
220
-
221
- # Limit conversation history (last 2 pairs)
222
  MAX_TURNS = 2
223
  trimmed_history = st.session_state.chat_history[-(MAX_TURNS * 2):]
224
  if trimmed_history and trimmed_history[-1]["role"] == "user":
@@ -226,62 +295,44 @@ if user_input:
226
  else:
227
  messages = trimmed_history + [{"role": "user", "content": augmented_user_input}]
228
 
229
- # ---- Set up a placeholder for the response and queue for streaming tokens ----
230
  visible_placeholder = st.empty()
 
231
  response_queue = queue.Queue()
232
 
233
- # Function to stream LLM response and push incremental updates into the queue
234
- def stream_response(msgs, max_tokens, temp, topk, topp, repeat_penalty):
235
- final_text = ""
236
- try:
237
- stream = llm.create_chat_completion(
238
- messages=msgs,
239
- max_tokens=max_tokens,
240
- temperature=temp,
241
- top_k=topk,
242
- top_p=topp,
243
- repeat_penalty=repeat_penalty,
244
- stream=True,
245
- )
246
- for chunk in stream:
247
- if "choices" in chunk:
248
- delta = chunk["choices"][0]["delta"].get("content", "")
249
- final_text += delta
250
- response_queue.put(delta)
251
- if chunk["choices"][0].get("finish_reason", ""):
252
- break
253
- except Exception as e:
254
- response_queue.put(f"\nError: {e}")
255
- response_queue.put(None) # Signal completion
256
-
257
- # Start streaming in a separate thread
258
  stream_thread = threading.Thread(
259
  target=stream_response,
260
- args=(messages, max_tokens, temperature, top_k, top_p, repeat_penalty),
261
  daemon=True
262
  )
263
  stream_thread.start()
264
 
265
- # Poll the queue in the main thread for up to 5 seconds
266
  final_response = ""
267
  timeout = 300 # seconds
268
  start_time = time.time()
 
269
  while True:
270
  try:
271
  update = response_queue.get(timeout=0.1)
272
  if update is None:
273
  break
274
  final_response += update
 
275
  visible_response = re.sub(r"<think>.*?</think>", "", final_response, flags=re.DOTALL)
276
- visible_response = re.sub(r"<think>.*$", "", visible_response, flags=re.DOTALL)
277
- visible_placeholder.markdown(visible_response)
278
- # Reset the timer after each token is generated
279
  start_time = time.time()
280
  except queue.Empty:
281
  if time.time() - start_time > timeout:
282
  st.error("Response generation timed out.")
283
  break
284
 
285
- st.session_state.chat_history.append({"role": "assistant", "content": final_response})
 
 
286
  st.session_state.pending_response = False
 
287
  gc.collect()
 
6
  from huggingface_hub import hf_hub_download
7
  from duckduckgo_search import DDGS
8
 
9
+ # ------------------------------
10
+ # Initialize Session State
11
+ # ------------------------------
12
  if "chat_history" not in st.session_state:
13
  st.session_state.chat_history = []
14
  if "pending_response" not in st.session_state:
 
18
  if "llm" not in st.session_state:
19
  st.session_state.llm = None
20
 
21
+ # ------------------------------
22
+ # Custom CSS for Improved Look & Feel
23
+ # ------------------------------
24
  st.markdown("""
25
  <style>
26
+ .chat-container { margin: 1em 0; }
27
+ .chat-assistant { background-color: #eef7ff; padding: 1em; border-radius: 10px; margin-bottom: 1em; }
28
+ .chat-user { background-color: #e6ffe6; padding: 1em; border-radius: 10px; margin-bottom: 1em; }
29
+ .message-time { font-size: 0.8em; color: #555; text-align: right; }
30
+ .loading-spinner { font-size: 1.1em; color: #ff6600; }
31
  </style>
32
  """, unsafe_allow_html=True)
33
 
34
+ # ------------------------------
35
+ # Required Storage and Model Definitions
36
+ # ------------------------------
37
  REQUIRED_SPACE_BYTES = 5 * 1024 ** 3 # 5 GB
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  MODELS = {
40
  "Qwen2.5-0.5B-Instruct (Q4_K_M)": {
41
  "repo_id": "Qwen/Qwen2.5-0.5B-Instruct-GGUF",
 
94
  },
95
  }
96
 
97
+ # ------------------------------
98
+ # Helper Functions
99
+ # ------------------------------
100
+ def retrieve_context(query, max_results=6, max_chars_per_result=600):
101
+ """Retrieve web search context using DuckDuckGo."""
102
+ try:
103
+ with DDGS() as ddgs:
104
+ results = list(islice(ddgs.text(query, region="wt-wt", safesearch="off", timelimit="y"), max_results))
105
+ context = ""
106
+ for i, result in enumerate(results, start=1):
107
+ title = result.get("title", "No Title")
108
+ snippet = result.get("body", "")[:max_chars_per_result]
109
+ context += f"Result {i}:\nTitle: {title}\nSnippet: {snippet}\n\n"
110
+ return context.strip()
111
+ except Exception as e:
112
+ st.error(f"Error during web retrieval: {e}")
113
+ return ""
 
 
 
 
114
 
115
+ def try_load_model(model_path):
116
+ """Attempt to initialize the model from a specified path."""
117
  try:
118
  return Llama(
119
+ model_path=model_path,
120
+ n_ctx=4096,
121
  n_threads=2,
122
  n_threads_batch=1,
123
  n_batch=256,
 
131
  except Exception as e:
132
  return str(e)
133
 
134
+ def download_model(selected_model):
135
+ """Download the model using Hugging Face Hub."""
136
  with st.spinner(f"Downloading {selected_model['filename']}..."):
137
  hf_hub_download(
138
  repo_id=selected_model["repo_id"],
 
141
  local_dir_use_symlinks=False,
142
  )
143
 
144
+ def validate_or_download_model(selected_model):
145
+ """Ensure the model is available and loaded properly; download if necessary."""
146
+ model_path = os.path.join("models", selected_model["filename"])
147
+ os.makedirs("models", exist_ok=True)
148
  if not os.path.exists(model_path):
149
  if shutil.disk_usage(".").free < REQUIRED_SPACE_BYTES:
150
+ st.info("Insufficient storage space. Consider cleaning up old models.")
151
+ download_model(selected_model)
152
  result = try_load_model(model_path)
153
  if isinstance(result, str):
154
+ st.warning(f"Initial model load failed: {result}\nAttempting re-download...")
155
  try:
156
  os.remove(model_path)
157
  except Exception:
158
  pass
159
+ download_model(selected_model)
160
  result = try_load_model(model_path)
161
  if isinstance(result, str):
162
+ st.error(f"Model failed to load after re-download: {result}")
163
  st.stop()
164
  return result
165
 
166
+ def stream_response(llm, messages, max_tokens, temperature, top_k, top_p, repeat_penalty, response_queue):
167
+ """Stream the model response token-by-token."""
168
+ final_text = ""
169
+ try:
170
+ stream = llm.create_chat_completion(
171
+ messages=messages,
172
+ max_tokens=max_tokens,
173
+ temperature=temperature,
174
+ top_k=top_k,
175
+ top_p=top_p,
176
+ repeat_penalty=repeat_penalty,
177
+ stream=True,
178
+ )
179
+ for chunk in stream:
180
+ if "choices" in chunk:
181
+ delta = chunk["choices"][0]["delta"].get("content", "")
182
+ final_text += delta
183
+ response_queue.put(delta)
184
+ if chunk["choices"][0].get("finish_reason", ""):
185
+ break
186
+ except Exception as e:
187
+ response_queue.put(f"\nError: {e}")
188
+ response_queue.put(None) # Signal the end of streaming
189
+
190
+ # ------------------------------
191
+ # Sidebar: Settings and Advanced Options
192
+ # ------------------------------
193
+ with st.sidebar:
194
+ st.header("⚙️ Settings")
195
+
196
+ # Basic Settings
197
+ selected_model_name = st.selectbox("Select Model", list(MODELS.keys()),
198
+ help="Choose from the available model configurations.")
199
+ system_prompt_base = st.text_area("System Prompt",
200
+ value="You are a helpful assistant.",
201
+ height=80,
202
+ help="Define the base context for the AI's responses.")
203
+
204
+ # Generation Parameters
205
+ st.subheader("Generation Parameters")
206
+ max_tokens = st.slider("Max Tokens", 64, 1024, 256, step=32,
207
+ help="The maximum number of tokens the assistant can generate.")
208
+ temperature = st.slider("Temperature", 0.1, 2.0, 0.7,
209
+ help="Controls randomness. Lower values are more deterministic.")
210
+ top_k = st.slider("Top-K", 1, 100, 40,
211
+ help="Limits the token candidates to the top-k tokens.")
212
+ top_p = st.slider("Top-P", 0.1, 1.0, 0.95,
213
+ help="Nucleus sampling parameter; restricts to a cumulative probability.")
214
+ repeat_penalty = st.slider("Repetition Penalty", 1.0, 2.0, 1.1,
215
+ help="Penalizes token repetition to improve output variety.")
216
+
217
+ # Advanced Settings using expandable sections
218
+ with st.expander("Web Search Settings"):
219
+ enable_search = st.checkbox("Enable Web Search", value=False,
220
+ help="Include recent web search context to augment the prompt.")
221
+ max_results = st.number_input("Max Results for Context", min_value=1, max_value=20, value=6, step=1,
222
+ help="How many search results to use.")
223
+ max_chars_per_result = st.number_input("Max Chars per Result", min_value=100, max_value=2000, value=600, step=50,
224
+ help="Max characters to extract from each search result.")
225
+
226
+ # ------------------------------
227
+ # Model Loading/Reloading if Needed
228
+ # ------------------------------
229
+ selected_model = MODELS[selected_model_name]
230
  if st.session_state.model_name != selected_model_name:
231
+ with st.spinner("Loading selected model..."):
232
+ if st.session_state.llm is not None:
233
+ del st.session_state.llm
234
+ gc.collect()
235
+ st.session_state.llm = validate_or_download_model(selected_model)
236
+ st.session_state.model_name = selected_model_name
237
 
238
  llm = st.session_state.llm
239
 
240
+ # ------------------------------
241
+ # Main Title and Chat History Display
242
+ # ------------------------------
243
  st.title(f"🧠 {selected_model['description']} (Streamlit + GGUF)")
244
  st.caption(f"Powered by `llama.cpp` | Model: {selected_model['filename']}")
245
 
246
+ # Render chat history with improved styling
247
  for chat in st.session_state.chat_history:
248
+ role = chat["role"]
249
+ content = chat["content"]
250
+ if role == "assistant":
251
+ st.markdown(f"<div class='chat-assistant'>{content}</div>", unsafe_allow_html=True)
252
+ else:
253
+ st.markdown(f"<div class='chat-user'>{content}</div>", unsafe_allow_html=True)
254
 
255
+ # ------------------------------
256
+ # Chat Input and Processing
257
+ # ------------------------------
258
+ user_input = st.chat_input("Your message...")
259
  if user_input:
260
  if st.session_state.pending_response:
261
+ st.warning("Please wait until the current response is finished.")
262
  else:
263
+ # Append user message with timestamp (if desired)
264
+ timestamp = time.strftime("%H:%M")
265
+ st.session_state.chat_history.append({"role": "user", "content": f"{user_input}\n\n<span class='message-time'>{timestamp}</span>"})
266
  with st.chat_message("user"):
267
+ st.markdown(f"<div class='chat-user'>{user_input}</div>", unsafe_allow_html=True)
268
+
269
  st.session_state.pending_response = True
270
+
271
+ # Retrieve web search context if enabled
272
+ retrieved_context = ""
273
+ if enable_search:
274
+ retrieved_context = retrieve_context(user_input, max_results=max_results, max_chars_per_result=max_chars_per_result)
275
+ with st.sidebar:
276
+ st.markdown("### Retrieved Context")
277
+ st.text_area("", value=retrieved_context or "No context found.", height=150)
278
 
279
+ # Augment the user prompt with the system prompt and optional web context
 
 
 
 
 
 
 
 
280
  if enable_search and retrieved_context:
281
  augmented_user_input = (
282
  f"{system_prompt_base.strip()}\n\n"
 
286
  )
287
  else:
288
  augmented_user_input = f"{system_prompt_base.strip()}\n\nUser Query: {user_input}"
289
+
290
+ # Limit conversation history to the last few turns (for context)
291
  MAX_TURNS = 2
292
  trimmed_history = st.session_state.chat_history[-(MAX_TURNS * 2):]
293
  if trimmed_history and trimmed_history[-1]["role"] == "user":
 
295
  else:
296
  messages = trimmed_history + [{"role": "user", "content": augmented_user_input}]
297
 
298
+ # Set up a placeholder for displaying the streaming response and a queue for tokens
299
  visible_placeholder = st.empty()
300
+ progress_bar = st.progress(0)
301
  response_queue = queue.Queue()
302
 
303
+ # Start streaming response in a separate thread
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  stream_thread = threading.Thread(
305
  target=stream_response,
306
+ args=(llm, messages, max_tokens, temperature, top_k, top_p, repeat_penalty, response_queue),
307
  daemon=True
308
  )
309
  stream_thread.start()
310
 
311
+ # Poll the queue to update the UI with incremental tokens and update progress
312
  final_response = ""
313
  timeout = 300 # seconds
314
  start_time = time.time()
315
+ progress = 0
316
  while True:
317
  try:
318
  update = response_queue.get(timeout=0.1)
319
  if update is None:
320
  break
321
  final_response += update
322
+ # Remove any special tags from the output (for cleaner UI)
323
  visible_response = re.sub(r"<think>.*?</think>", "", final_response, flags=re.DOTALL)
324
+ visible_placeholder.markdown(f"<div class='chat-assistant'>{visible_response}</div>", unsafe_allow_html=True)
325
+ progress = min(progress + 1, 100)
326
+ progress_bar.progress(progress)
327
  start_time = time.time()
328
  except queue.Empty:
329
  if time.time() - start_time > timeout:
330
  st.error("Response generation timed out.")
331
  break
332
 
333
+ # Append assistant response with timestamp
334
+ timestamp = time.strftime("%H:%M")
335
+ st.session_state.chat_history.append({"role": "assistant", "content": f"{final_response}\n\n<span class='message-time'>{timestamp}</span>"})
336
  st.session_state.pending_response = False
337
+ progress_bar.empty() # Clear progress bar
338
  gc.collect()