robiro commited on
Commit
f740c8a
·
verified ·
1 Parent(s): 02d4edd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -125
app.py CHANGED
@@ -6,16 +6,14 @@ import time
6
 
7
  # --- Configuration ---
8
  MODEL_REPO_ID = "unsloth/DeepSeek-R1-0528-Qwen3-8B-GGUF"
9
- # IMPORTANT: Verify this filename exists in the "Files and versions" tab of the repo
10
- MODEL_FILENAME = "DeepSeek-R1-0528-Qwen3-8B-Q4_K_M.gguf"
11
- LOCAL_MODEL_PATH = f"./{MODEL_FILENAME}" # Download to current directory
12
 
13
- # LLM Llama Parameters (adjust based on your Space's resources)
14
- N_CTX = 2048 # Context window size. Default 2048. Max for this model is very large, but needs RAM.
15
- N_THREADS = None # Number of CPU threads to use. None = Llama.cpp auto-detects.
16
- # On smaller CPU Spaces (e.g., 2-4 cores), explicitly setting N_THREADS=2 or N_THREADS=4 might be beneficial.
17
- N_GPU_LAYERS = 0 # Number of layers to offload to GPU. 0 for CPU-only. -1 for all possible.
18
- VERBOSE_LLAMA = True # Enable verbose logging from llama.cpp
19
 
20
  # Generation parameters
21
  DEFAULT_MAX_NEW_TOKENS = 512
@@ -24,6 +22,10 @@ DEFAULT_TOP_P = 0.95
24
  DEFAULT_TOP_K = 40
25
  DEFAULT_REPEAT_PENALTY = 1.1
26
 
 
 
 
 
27
  # --- Global variable for the model ---
28
  llm = None
29
 
@@ -37,7 +39,7 @@ def download_model_if_needed():
37
  repo_id=MODEL_REPO_ID,
38
  filename=MODEL_FILENAME,
39
  local_dir=".",
40
- local_dir_use_symlinks=False, # Good practice for GGUF
41
  resume_download=True
42
  )
43
  end_time = time.time()
@@ -45,18 +47,17 @@ def download_model_if_needed():
45
  return True
46
  except Exception as e:
47
  print(f"Error downloading model: {e}")
48
- print("Please ensure MODEL_FILENAME is correct and available in the repository.")
49
  print(f"Attempted to download: {MODEL_REPO_ID}/{MODEL_FILENAME}")
50
  return False
51
  else:
52
  print(f"Model file {MODEL_FILENAME} already exists.")
53
  return True
54
- return False
55
 
56
  # --- Model Loading ---
57
  def load_llm_model():
58
  global llm
59
- if llm is None: # Load only if not already loaded
60
  if not os.path.exists(LOCAL_MODEL_PATH):
61
  print("Model file not found. Cannot load.")
62
  return False
@@ -69,52 +70,56 @@ def load_llm_model():
69
  n_threads=N_THREADS,
70
  n_gpu_layers=N_GPU_LAYERS,
71
  verbose=VERBOSE_LLAMA,
72
- # logits_all=True, # Set to True if you need logits for all tokens (consumes more VRAM/RAM)
73
  )
74
  end_time = time.time()
75
  print(f"Model loaded successfully in {end_time - start_time:.2f} seconds.")
76
  return True
77
  except Exception as e:
78
  print(f"Error loading Llama model: {e}")
79
- print("Ensure llama-cpp-python is installed correctly and the model file is valid.")
80
- print(f"If you are on a resource-constrained environment (like free Hugging Face Spaces), "
81
- f"the model ({MODEL_FILENAME}, ~{os.path.getsize(LOCAL_MODEL_PATH)/(1024**3):.2f}GB) might be too large.")
82
- print("Try reducing N_CTX or using a smaller model variant if available.")
83
- llm = None # Ensure llm is None if loading failed
84
  return False
85
  else:
86
  print("Model already loaded.")
87
  return True
88
 
89
-
90
  # --- Chat Function ---
91
  def predict(message, history, system_prompt, max_new_tokens, temperature, top_p, top_k, repeat_penalty):
92
  if llm is None:
93
  return "Model not loaded. Please check the logs."
94
 
95
- # Qwen specific chat format elements
96
- im_start_token = "<|im_start|>"
97
- im_end_token = "<|im_end|>"
98
  # Common stop tokens for Qwen-like models
99
- stop_tokens = [im_end_token, im_start_token + "user", im_start_token + "system", llm.token_eos()]
100
-
101
 
102
- # Format messages for llama_cpp
103
- messages = []
104
  if system_prompt and system_prompt.strip():
105
- messages.append({"role": "system", "content": system_prompt.strip()})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
- for human_msg, ai_msg in history:
108
- messages.append({"role": "user", "content": human_msg})
109
- if ai_msg is not None: # ai_msg could be None if it's the first turn and history is just the user prompt
110
- messages.append({"role": "assistant", "content": ai_msg})
111
- messages.append({"role": "user", "content": message})
112
 
113
  print("\n--- Input to Model ---")
114
  print(f"System Prompt: {system_prompt if system_prompt and system_prompt.strip() else 'None'}")
115
- print(f"History: {history}")
116
  print(f"Current Message: {message}")
117
- print(f"Formatted messages for create_chat_completion: {messages}")
118
  print("--- End Input to Model ---\n")
119
 
120
  assistant_response_text = ""
@@ -123,14 +128,13 @@ def predict(message, history, system_prompt, max_new_tokens, temperature, top_p,
123
  try:
124
  print("Attempting generation with llm.create_chat_completion()...")
125
  response = llm.create_chat_completion(
126
- messages=messages,
127
  temperature=temperature,
128
  top_p=top_p,
129
  top_k=top_k,
130
  repeat_penalty=repeat_penalty,
131
  max_tokens=max_new_tokens,
132
  stop=stop_tokens,
133
- # stream=True # For streaming output, Gradio handles this differently
134
  )
135
  assistant_response_text = response['choices'][0]['message']['content'].strip()
136
  print(f"create_chat_completion successful. Raw response: {response['choices'][0]['message']}")
@@ -139,16 +143,15 @@ def predict(message, history, system_prompt, max_new_tokens, temperature, top_p,
139
  print(f"Error during create_chat_completion: {e_chat_completion}")
140
  print("Falling back to manual prompt construction and llm()...")
141
 
142
- # Construct prompt manually as a fallback (simplified Qwen format)
143
  prompt = ""
144
  if system_prompt and system_prompt.strip():
145
- prompt += f"{im_start_token}system\n{system_prompt.strip()}{im_end_token}\n"
146
 
147
- for human_msg, ai_msg in history:
148
- prompt += f"{im_start_token}user\n{human_msg}{im_end_token}\n"
149
  if ai_msg is not None:
150
- prompt += f"{im_start_token}assistant\n{ai_msg}{im_end_token}\n"
151
- prompt += f"{im_start_token}user\n{message}{im_end_token}\n{im_start_token}assistant\n" # Model should continue from here
152
 
153
  print(f"Fallback prompt: {prompt}")
154
 
@@ -161,7 +164,7 @@ def predict(message, history, system_prompt, max_new_tokens, temperature, top_p,
161
  top_k=top_k,
162
  repeat_penalty=repeat_penalty,
163
  stop=stop_tokens,
164
- echo=False # Don't echo the input prompt
165
  )
166
  assistant_response_text = output['choices'][0]['text'].strip()
167
  print(f"Fallback llm() successful. Raw output: {output['choices'][0]['text']}")
@@ -190,8 +193,9 @@ def create_gradio_interface():
190
  [],
191
  elem_id="chatbot",
192
  label="Chat Window",
193
- bubble_full_width=False,
194
  height=500,
 
195
  )
196
  user_input = gr.Textbox(
197
  show_label=False,
@@ -208,7 +212,7 @@ def create_gradio_interface():
208
  lines=3
209
  )
210
  max_new_tokens_slider = gr.Slider(
211
- minimum=32, maximum=N_CTX, value=DEFAULT_MAX_NEW_TOKENS, step=32, # Max tokens cannot exceed context
212
  label="Max New Tokens"
213
  )
214
  temperature_slider = gr.Slider(
@@ -227,88 +231,66 @@ def create_gradio_interface():
227
  minimum=1.0, maximum=2.0, value=DEFAULT_REPEAT_PENALTY, step=0.05,
228
  label="Repeat Penalty"
229
  )
230
- # Hidden status textbox for errors
231
  status_display = gr.Textbox(label="Status", interactive=False, visible=False)
232
 
233
 
234
- # Chat submission logic
235
- def handle_submit(message, chat_history, sys_prompt, max_tokens, temp, top_p_val, top_k_val, rep_penalty):
236
- if llm is None:
237
- # Update status display if model not loaded
238
- # This part is tricky as Gradio submit doesn't easily update arbitrary components outside its output
239
- # For now, errors from predict will be returned in the chat.
240
- # A more robust way would be a global status or specific UI element.
241
- print("Attempted to chat but LLM is not loaded.")
242
- # A simple way to indicate an issue if llm is None
243
- chat_history.append((message, "ERROR: Model not loaded. Please check server logs."))
244
- return "", chat_history, "ERROR: Model not loaded."
245
-
246
- # Append user message
247
- chat_history.append((message, None))
248
- # We pass the full system prompt and params to predict
249
- return "", chat_history, sys_prompt, max_tokens, temp, top_p_val, top_k_val, rep_penalty
250
-
251
-
252
- # Connect user input to the generation
253
- submit_args = {
254
- "fn": predict,
255
- "inputs": [user_input, chatbot, system_prompt_input, max_new_tokens_slider, temperature_slider, top_p_slider, top_k_slider, repeat_penalty_slider],
256
- "outputs": [chatbot], # Predict will update the last AI message in chatbot
257
- }
258
-
259
- # Gradio's ChatInterface simplifies history management, but for custom layouts, we manage it manually.
260
- # Here, we'll use a more direct approach like gr.Interface or manual updates.
261
- # Since we use gr.Chatbot and manage history, we need to ensure `predict` gets the right state.
262
- # `predict` directly takes history and returns the new AI response.
263
- # Gradio's `gr.Chatbot` will automatically append the (user, ai_response) pair.
264
 
265
- user_input.submit(
266
- predict,
267
- [user_input, chatbot, system_prompt_input, max_new_tokens_slider, temperature_slider, top_p_slider, top_k_slider, repeat_penalty_slider],
268
- [user_input, chatbot], # Clear user_input, update chatbot
269
- # The `predict` function returns only the assistant's response string.
270
- # Gradio Chatbot expects the new AI message to be the output to update the last turn.
271
- # So, we need a wrapper if we want to clear user_input and update chatbot
272
- )
273
-
274
- # A slightly cleaner way to handle chatbot updates with custom parameters
275
- # and clearing input box:
276
- def user_chat_fn(user_message, chat_history, sys_prompt, max_tok, temp, top_p_val, top_k_val, rep_pen):
277
  if llm is None:
278
- chat_history.append((user_message, "ERROR: Model not loaded. Check logs."))
279
- return "", chat_history # Clear input, update history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
 
281
- # Append user message, AI response will be None initially
282
- chat_history.append((user_message, None))
283
- return "", chat_history, sys_prompt, max_tok, temp, top_p_val, top_k_val, rep_pen
 
284
 
285
- def bot_response_fn(chat_history, sys_prompt, max_tok, temp, top_p_val, top_k_val, rep_pen):
286
- if llm is None: # Should be caught by user_chat_fn, but double check
287
- return chat_history # No change
 
 
 
 
288
 
289
- # The last message in history is the user's current message
290
- user_message = chat_history[-1][0]
291
- # The history to pass to `predict` should not include the current user turn's empty AI response
292
- history_for_predict = chat_history[:-1]
293
 
294
- bot_msg = predict(user_message, history_for_predict, sys_prompt, max_tok, temp, top_p_val, top_k_val, rep_pen)
295
- chat_history[-1] = (user_message, bot_msg) # Update the last turn with AI's response
296
- return chat_history
297
 
298
- # Chain the actions: user input -> update chatbot (user msg) -> bot generates -> update chatbot (bot msg)
299
  user_input.submit(
300
  user_chat_fn,
301
  [user_input, chatbot, system_prompt_input, max_new_tokens_slider, temperature_slider, top_p_slider, top_k_slider, repeat_penalty_slider],
302
- [user_input, chatbot, system_prompt_input, max_new_tokens_slider, temperature_slider, top_p_slider, top_k_slider, repeat_penalty_slider], # Outputs for user_chat_fn
303
- queue=False # User input should be fast
304
  ).then(
305
  bot_response_fn,
306
  [chatbot, system_prompt_input, max_new_tokens_slider, temperature_slider, top_p_slider, top_k_slider, repeat_penalty_slider],
307
- [chatbot], # Output for bot_response_fn
308
- queue=True # Generation can take time
309
  )
310
 
311
-
312
  gr.Examples(
313
  examples=[
314
  ["Hello, how are you today?", "You are a friendly and helpful AI assistant specializing in concise answers."],
@@ -317,21 +299,18 @@ def create_gradio_interface():
317
  ["Explain the concept of black holes to a 5-year-old.", "Keep it simple and use an analogy."]
318
  ],
319
  inputs=[user_input, system_prompt_input],
320
- # outputs=[chatbot], # Examples don't directly feed to chatbot output here with this setup
321
- # fn=lambda q, s: (None, [(q, predict(q, [], s, ...default_params...))]) # Complex to run predict for examples
322
- # For simplicity, examples just populate the input fields.
323
  )
324
 
325
  with gr.Accordion("Advanced/Debug Info", open=False):
 
326
  gr.Markdown(f"""
327
  - **Model File:** `{LOCAL_MODEL_PATH}`
328
  - **N_CTX:** `{N_CTX}`
329
  - **N_THREADS:** `{N_THREADS if N_THREADS is not None else 'Auto'}`
330
  - **N_GPU_LAYERS:** `{N_GPU_LAYERS}`
331
  - **Log Verbosity (llama.cpp):** `{VERBOSE_LLAMA}`
332
- - **Stop Tokens Used:** `{im_start_token}system`, `{im_start_token}user`, `{im_end_token}`, `EOS_TOKEN`
333
  """)
334
- # Add a button to attempt model reload if it failed initially
335
  reload_button = gr.Button("Attempt to Reload Model")
336
  reload_status = gr.Label(value="Model Status: Unknown")
337
 
@@ -343,7 +322,17 @@ def create_gradio_interface():
343
 
344
  def attempt_reload():
345
  global llm
346
- llm = None # Force re-evaluation of loading
 
 
 
 
 
 
 
 
 
 
347
  if load_llm_model():
348
  return "Model reloaded successfully!"
349
  else:
@@ -351,8 +340,6 @@ def create_gradio_interface():
351
 
352
  reload_button.click(attempt_reload, outputs=[reload_status])
353
  iface.load(update_reload_status, outputs=[reload_status]) # Update status on interface load
354
-
355
-
356
  return iface
357
 
358
  # --- Main Execution ---
@@ -362,19 +349,15 @@ if __name__ == "__main__":
362
 
363
  if model_available:
364
  if not load_llm_model():
365
- print("Model loading failed. The Gradio interface will start, but chat functionality will be impaired.")
366
- print("You can try to reload the model via the 'Advanced/Debug Info' section in the UI.")
367
  else:
368
  print("Model ready.")
369
  else:
370
- print("Model download failed. Cannot proceed to load model or start chat functionality.")
371
- print("The Gradio interface will start, but it will not be functional.")
372
 
373
  print("Creating Gradio interface...")
374
  app_interface = create_gradio_interface()
375
 
376
  print("Launching Gradio interface...")
377
- # Share=True is useful for public links if running locally, but HF Spaces handles public URL.
378
- # In_browser=True to open in browser locally.
379
  app_interface.launch()
380
- print("Gradio interface launched. Check your terminal or logs for the URL.")
 
6
 
7
  # --- Configuration ---
8
  MODEL_REPO_ID = "unsloth/DeepSeek-R1-0528-Qwen3-8B-GGUF"
9
+ MODEL_FILENAME = "DeepSeek-R1-0528-Qwen3-8B-Q4_K_M.gguf" # IMPORTANT: Verify this filename
10
+ LOCAL_MODEL_PATH = f"./{MODEL_FILENAME}"
 
11
 
12
+ # LLM Llama Parameters
13
+ N_CTX = 2048
14
+ N_THREADS = None
15
+ N_GPU_LAYERS = 0
16
+ VERBOSE_LLAMA = True
 
17
 
18
  # Generation parameters
19
  DEFAULT_MAX_NEW_TOKENS = 512
 
22
  DEFAULT_TOP_K = 40
23
  DEFAULT_REPEAT_PENALTY = 1.1
24
 
25
+ # Qwen specific chat format elements (defined globally)
26
+ IM_START_TOKEN = "<|im_start|>"
27
+ IM_END_TOKEN = "<|im_end|>"
28
+
29
  # --- Global variable for the model ---
30
  llm = None
31
 
 
39
  repo_id=MODEL_REPO_ID,
40
  filename=MODEL_FILENAME,
41
  local_dir=".",
42
+ local_dir_use_symlinks=False,
43
  resume_download=True
44
  )
45
  end_time = time.time()
 
47
  return True
48
  except Exception as e:
49
  print(f"Error downloading model: {e}")
 
50
  print(f"Attempted to download: {MODEL_REPO_ID}/{MODEL_FILENAME}")
51
  return False
52
  else:
53
  print(f"Model file {MODEL_FILENAME} already exists.")
54
  return True
55
+ return False # Should not be reached if logic is correct, but good for completeness
56
 
57
  # --- Model Loading ---
58
  def load_llm_model():
59
  global llm
60
+ if llm is None:
61
  if not os.path.exists(LOCAL_MODEL_PATH):
62
  print("Model file not found. Cannot load.")
63
  return False
 
70
  n_threads=N_THREADS,
71
  n_gpu_layers=N_GPU_LAYERS,
72
  verbose=VERBOSE_LLAMA,
 
73
  )
74
  end_time = time.time()
75
  print(f"Model loaded successfully in {end_time - start_time:.2f} seconds.")
76
  return True
77
  except Exception as e:
78
  print(f"Error loading Llama model: {e}")
79
+ print(f"If on resource-constrained environment, model ({MODEL_FILENAME}, ~{os.path.getsize(LOCAL_MODEL_PATH)/(1024**3):.2f}GB if exists) might be too large.")
80
+ llm = None
 
 
 
81
  return False
82
  else:
83
  print("Model already loaded.")
84
  return True
85
 
 
86
  # --- Chat Function ---
87
  def predict(message, history, system_prompt, max_new_tokens, temperature, top_p, top_k, repeat_penalty):
88
  if llm is None:
89
  return "Model not loaded. Please check the logs."
90
 
 
 
 
91
  # Common stop tokens for Qwen-like models
92
+ # Accessing global IM_START_TOKEN and IM_END_TOKEN
93
+ stop_tokens = [IM_END_TOKEN, IM_START_TOKEN + "user", IM_START_TOKEN + "system", llm.token_eos_str()] # Use string representation of EOS
94
 
95
+ messages_for_api = [] # Renamed to avoid conflict with Gradio's 'messages' type
 
96
  if system_prompt and system_prompt.strip():
97
+ messages_for_api.append({"role": "system", "content": system_prompt.strip()})
98
+
99
+ # History for Gradio Chatbot with type="messages" is already in the correct format
100
+ # history will be a list of lists, where each inner list is [user_msg, ai_msg]
101
+ # or if type="messages", it's a list of dicts.
102
+ # Let's assume for now the input `history` from chatbot (when type="tuples")
103
+ # needs conversion if predict is called directly with such history.
104
+ # If chatbot type="messages", history is already List[Dict[str, str]]
105
+ # The `user_chat_fn` and `bot_response_fn` handle history in `messages` format for the chatbot.
106
+ # So, when `predict` is called by `bot_response_fn`, `history` is actually `history_for_predict`
107
+ # which is `chat_history[:-1]`. `chat_history` is a list of tuples.
108
+ # We need to convert this tuple-style history to OpenAI dict style for create_chat_completion.
109
+
110
+ # The history passed from `bot_response_fn` (history_for_predict) is list of [user, assistant] tuples
111
+ for human_msg, ai_msg in history: # history here is history_for_predict from bot_response_fn
112
+ messages_for_api.append({"role": "user", "content": human_msg})
113
+ if ai_msg is not None:
114
+ messages_for_api.append({"role": "assistant", "content": ai_msg})
115
+ messages_for_api.append({"role": "user", "content": message})
116
 
 
 
 
 
 
117
 
118
  print("\n--- Input to Model ---")
119
  print(f"System Prompt: {system_prompt if system_prompt and system_prompt.strip() else 'None'}")
120
+ print(f"History (tuples format for predict): {history}")
121
  print(f"Current Message: {message}")
122
+ print(f"Formatted messages for create_chat_completion: {messages_for_api}")
123
  print("--- End Input to Model ---\n")
124
 
125
  assistant_response_text = ""
 
128
  try:
129
  print("Attempting generation with llm.create_chat_completion()...")
130
  response = llm.create_chat_completion(
131
+ messages=messages_for_api,
132
  temperature=temperature,
133
  top_p=top_p,
134
  top_k=top_k,
135
  repeat_penalty=repeat_penalty,
136
  max_tokens=max_new_tokens,
137
  stop=stop_tokens,
 
138
  )
139
  assistant_response_text = response['choices'][0]['message']['content'].strip()
140
  print(f"create_chat_completion successful. Raw response: {response['choices'][0]['message']}")
 
143
  print(f"Error during create_chat_completion: {e_chat_completion}")
144
  print("Falling back to manual prompt construction and llm()...")
145
 
 
146
  prompt = ""
147
  if system_prompt and system_prompt.strip():
148
+ prompt += f"{IM_START_TOKEN}system\n{system_prompt.strip()}{IM_END_TOKEN}\n"
149
 
150
+ for human_msg, ai_msg in history: # history here is history_for_predict
151
+ prompt += f"{IM_START_TOKEN}user\n{human_msg}{IM_END_TOKEN}\n"
152
  if ai_msg is not None:
153
+ prompt += f"{IM_START_TOKEN}assistant\n{ai_msg}{IM_END_TOKEN}\n"
154
+ prompt += f"{IM_START_TOKEN}user\n{message}{IM_END_TOKEN}\n{IM_START_TOKEN}assistant\n"
155
 
156
  print(f"Fallback prompt: {prompt}")
157
 
 
164
  top_k=top_k,
165
  repeat_penalty=repeat_penalty,
166
  stop=stop_tokens,
167
+ echo=False
168
  )
169
  assistant_response_text = output['choices'][0]['text'].strip()
170
  print(f"Fallback llm() successful. Raw output: {output['choices'][0]['text']}")
 
193
  [],
194
  elem_id="chatbot",
195
  label="Chat Window",
196
+ # bubble_full_width=False, # Deprecated
197
  height=500,
198
+ type="messages" # Use OpenAI-style messages format
199
  )
200
  user_input = gr.Textbox(
201
  show_label=False,
 
212
  lines=3
213
  )
214
  max_new_tokens_slider = gr.Slider(
215
+ minimum=32, maximum=N_CTX, value=DEFAULT_MAX_NEW_TOKENS, step=32,
216
  label="Max New Tokens"
217
  )
218
  temperature_slider = gr.Slider(
 
231
  minimum=1.0, maximum=2.0, value=DEFAULT_REPEAT_PENALTY, step=0.05,
232
  label="Repeat Penalty"
233
  )
 
234
  status_display = gr.Textbox(label="Status", interactive=False, visible=False)
235
 
236
 
237
+ def user_chat_fn(user_message, chat_history_messages, sys_prompt, max_tok, temp, top_p_val, top_k_val, rep_pen):
238
+ if not user_message.strip(): # Do nothing if user message is empty
239
+ return "", chat_history_messages, sys_prompt, max_tok, temp, top_p_val, top_k_val, rep_pen
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  if llm is None:
242
+ chat_history_messages.append({"role": "user", "content": user_message})
243
+ chat_history_messages.append({"role": "assistant", "content": "ERROR: Model not loaded. Check server logs."})
244
+ return "", chat_history_messages, sys_prompt, max_tok, temp, top_p_val, top_k_val, rep_pen
245
+
246
+ chat_history_messages.append({"role": "user", "content": user_message})
247
+ # Add a placeholder for assistant message that bot_response_fn will fill
248
+ chat_history_messages.append({"role": "assistant", "content": None})
249
+ return "", chat_history_messages, sys_prompt, max_tok, temp, top_p_val, top_k_val, rep_pen
250
+
251
+ def bot_response_fn(chat_history_messages, sys_prompt, max_tok, temp, top_p_val, top_k_val, rep_pen):
252
+ if llm is None or chat_history_messages[-1]["content"] is not None : # If model not loaded or already processed
253
+ return chat_history_messages
254
+
255
+ user_message = chat_history_messages[-2]["content"] # Get the last user message
256
+
257
+ # Convert OpenAI-style message history (List[Dict]) to tuple-style for predict's current internal logic
258
+ history_for_predict_tuples = []
259
+ # Iterate up to the second to last message (the current user's message)
260
+ # Each pair of (user, assistant) forms one turn for the tuple history
261
+ i = 0
262
+ temp_history = chat_history_messages[:-2] # Exclude current user and assistant placeholder
263
 
264
+ # Skip system prompt if present at the beginning for tuple conversion
265
+ start_index = 0
266
+ if temp_history and temp_history[0]["role"] == "system":
267
+ start_index = 1 # System prompt handled separately in predict
268
 
269
+ for i in range(start_index, len(temp_history), 2):
270
+ if i + 1 < len(temp_history) and temp_history[i]["role"] == "user" and temp_history[i+1]["role"] == "assistant":
271
+ history_for_predict_tuples.append(
272
+ (temp_history[i]["content"], temp_history[i+1]["content"])
273
+ )
274
+ elif temp_history[i]["role"] == "user": # Handle case where last turn was only a user message (shouldn't happen if paired)
275
+ history_for_predict_tuples.append((temp_history[i]["content"], None))
276
 
 
 
 
 
277
 
278
+ bot_msg_content = predict(user_message, history_for_predict_tuples, sys_prompt, max_tok, temp, top_p_val, top_k_val, rep_pen)
279
+ chat_history_messages[-1]["content"] = bot_msg_content # Update the assistant's placeholder message
280
+ return chat_history_messages
281
 
 
282
  user_input.submit(
283
  user_chat_fn,
284
  [user_input, chatbot, system_prompt_input, max_new_tokens_slider, temperature_slider, top_p_slider, top_k_slider, repeat_penalty_slider],
285
+ [user_input, chatbot, system_prompt_input, max_new_tokens_slider, temperature_slider, top_p_slider, top_k_slider, repeat_penalty_slider],
286
+ queue=False
287
  ).then(
288
  bot_response_fn,
289
  [chatbot, system_prompt_input, max_new_tokens_slider, temperature_slider, top_p_slider, top_k_slider, repeat_penalty_slider],
290
+ [chatbot],
291
+ queue=True
292
  )
293
 
 
294
  gr.Examples(
295
  examples=[
296
  ["Hello, how are you today?", "You are a friendly and helpful AI assistant specializing in concise answers."],
 
299
  ["Explain the concept of black holes to a 5-year-old.", "Keep it simple and use an analogy."]
300
  ],
301
  inputs=[user_input, system_prompt_input],
 
 
 
302
  )
303
 
304
  with gr.Accordion("Advanced/Debug Info", open=False):
305
+ # Accessing global IM_START_TOKEN and IM_END_TOKEN
306
  gr.Markdown(f"""
307
  - **Model File:** `{LOCAL_MODEL_PATH}`
308
  - **N_CTX:** `{N_CTX}`
309
  - **N_THREADS:** `{N_THREADS if N_THREADS is not None else 'Auto'}`
310
  - **N_GPU_LAYERS:** `{N_GPU_LAYERS}`
311
  - **Log Verbosity (llama.cpp):** `{VERBOSE_LLAMA}`
312
+ - **Stop Tokens Used (Conceptual):** `{IM_START_TOKEN}system`, `{IM_START_TOKEN}user`, `{IM_END_TOKEN}`, `EOS_TOKEN`
313
  """)
 
314
  reload_button = gr.Button("Attempt to Reload Model")
315
  reload_status = gr.Label(value="Model Status: Unknown")
316
 
 
322
 
323
  def attempt_reload():
324
  global llm
325
+ if llm is not None:
326
+ try:
327
+ # Attempt to free existing model if Llama.cpp supports it or by reassigning
328
+ print("Freeing existing model instance (if any)...")
329
+ del llm # Explicitly delete to trigger __del__ if possible
330
+ llm = None
331
+ import gc
332
+ gc.collect() # Suggest garbage collection
333
+ except Exception as e_del:
334
+ print(f"Error during manual deletion of llm: {e_del}")
335
+
336
  if load_llm_model():
337
  return "Model reloaded successfully!"
338
  else:
 
340
 
341
  reload_button.click(attempt_reload, outputs=[reload_status])
342
  iface.load(update_reload_status, outputs=[reload_status]) # Update status on interface load
 
 
343
  return iface
344
 
345
  # --- Main Execution ---
 
349
 
350
  if model_available:
351
  if not load_llm_model():
352
+ print("Initial model loading failed. Gradio will start; use UI to attempt reload.")
 
353
  else:
354
  print("Model ready.")
355
  else:
356
+ print("Model download failed. Cannot load model. Gradio will start; chat will be non-functional.")
 
357
 
358
  print("Creating Gradio interface...")
359
  app_interface = create_gradio_interface()
360
 
361
  print("Launching Gradio interface...")
 
 
362
  app_interface.launch()
363
+ print("Gradio interface launched.")