ar12c commited on
Commit
4313838
·
verified ·
1 Parent(s): 11293da

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -19
app.py CHANGED
@@ -190,7 +190,7 @@ def perform_web_search(query):
190
  return ""
191
 
192
 
193
- def online_update(model, input_sentence, target_response, max_seq_len, search_context="", conversation_context=""):
194
  # Accept any language; just avoid corrupted or repetitive targets
195
  is_response_clean = not any(t in target_response for t in [voc.UNK, "i couldn't generate"])
196
  is_not_repetitive = not check_repetition(target_response, max_repeat=2)
@@ -199,10 +199,13 @@ def online_update(model, input_sentence, target_response, max_seq_len, search_co
199
  print("Skipping online update: Target response is corrupted or highly repetitive.")
200
  return
201
 
202
- prefix_text = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""
 
203
  context_prefix = f"{conversation_context} " if conversation_context else ""
204
 
205
- full_prompt_text = f"{SYSTEM_INSTRUCTION} {context_prefix}{prefix_text} {input_sentence}"
 
 
206
  full_prompt_text = to_ascii(full_prompt_text)
207
 
208
  prompt_tokens = indexes_from_sentence(voc, full_prompt_text)[:-1]
@@ -298,33 +301,59 @@ def process_feedback(history, rating):
298
  return history, "Cannot process feedback: No recent AI response found."
299
 
300
  last_user_message, last_ai_response = history[-1][0], history[-1][1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
301
  print(f"\n--- FEEDBACK RECEIVED ---")
302
  print(f"Rating: {rating}")
303
  print(f"User Prompt: '{last_user_message}'")
304
  print(f"AI Response: '{last_ai_response}'")
 
305
  print(f"-------------------------\n")
306
 
307
  if rating == "Good Response":
 
308
  conversation_context = ""
309
  if len(history) >= 2 and isinstance(history[-2], list) and len(history[-2]) == 2 and isinstance(history[-2][1], str):
310
  last_user, last_ai = history[-2][0], history[-2][1]
311
  conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
312
 
313
- # 1. Perform Online Update (Training)
314
  online_update(
315
  gpt_model,
316
- last_user_message,
317
  last_ai_response,
318
  max_length,
319
- search_context="",
 
320
  conversation_context=conversation_context
321
  )
322
 
323
- # 2. CRITICAL: Save the updated model state to disk
324
  save_checkpoint(gpt_model, optimizer, voc, CHECKPOINT_PATH)
325
 
326
  feedback_message = "Thanks for the **Good Response** rating! I just learned from that. Keep the good prompts coming! ✨"
327
  elif rating == "Bad Response":
 
328
  feedback_message = "Acknowledged **Bad Response** feedback. I will try to be better! 🛠️"
329
  else:
330
  feedback_message = "Unknown rating received."
@@ -336,6 +365,8 @@ def on_submit(user_message, history, uploaded_file, web_search_enabled):
336
  # Normalize history
337
  history = history or []
338
  if not history or history[-1][1] is not None:
 
 
339
  history.append([user_message, None])
340
 
341
  file_context = ""
@@ -348,14 +379,20 @@ def on_submit(user_message, history, uploaded_file, web_search_enabled):
348
  "please generate", "provide a much more detailed", "provide a different"
349
  ])
350
 
 
 
351
  match = re.search(r':\s*"(.+?)"$', user_message)
352
  if is_instruction and match:
353
  clean_user_message = match.group(1).strip()
354
  model_prompt = user_message
355
  else:
356
- clean_user_message = user_message
357
  model_prompt = user_message
358
 
 
 
 
 
 
359
  conversation_context = ""
360
  context_history = history[:-1] if not is_instruction else history
361
  if context_history and isinstance(context_history[-1], list) and len(context_history[-1]) == 2 and isinstance(context_history[-1][1], str):
@@ -363,8 +400,6 @@ def on_submit(user_message, history, uploaded_file, web_search_enabled):
363
  conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
364
  print(f"Context included: {conversation_context}")
365
 
366
- # No language rejection; proceed
367
-
368
  search_context_text = ""
369
  search_needed = bool(web_search_enabled) or "?" in clean_user_message or any(
370
  clean_user_message.lower().startswith(q) for q in ["what is", "who is", "how to"]
@@ -372,6 +407,7 @@ def on_submit(user_message, history, uploaded_file, web_search_enabled):
372
  if search_needed:
373
  search_context_text = perform_web_search(clean_user_message)
374
 
 
375
  final_model_prompt = f"{file_context} {model_prompt}" if file_context else model_prompt
376
  reply = generate_response(
377
  final_model_prompt,
@@ -399,11 +435,8 @@ with gr.Blocks(title="OkemoLLM") as demo:
399
 
400
  def add_user_message_to_history(message, history, file_ref, web_enabled):
401
  history = history or []
402
- if file_ref:
403
- # NOTE: This only adds a non-image file attachment marker for Gradio's internal history.
404
- # Client-side logic handles image object URLs.
405
- file_name = file_ref.name.split("/")[-1]
406
- message = f"{message} (Attached: {file_name})"
407
  updated_history = history + [[message, None]]
408
  return updated_history, ""
409
 
@@ -435,7 +468,6 @@ with gr.Blocks(title="OkemoLLM") as demo:
435
  clear.click(lambda: [], None, chat, queue=False)
436
 
437
  def feedback_good_wrapper(history_state):
438
- # The API client (JS) sends the full history state here.
439
  return process_feedback(history_state, "Good Response")
440
 
441
  def feedback_bad_wrapper(history_state):
@@ -461,10 +493,12 @@ with gr.Blocks(title="OkemoLLM") as demo:
461
 
462
  # Public API: /on_submit (renamed for consistency with JS client)
463
  def chat_submit_api(msg_value, chat_value, uploaded_file_value, web_enabled_value):
464
- # NOTE: The JS client sends the final user message (with markers) in msg_value.
465
- # We process it directly through on_submit since the client handles the history update.
 
 
466
  final_history, status_msg = on_submit(
467
- msg_value, chat_value or [], uploaded_file_value, web_enabled_value
468
  )
469
  return final_history, status_msg
470
 
 
190
  return ""
191
 
192
 
193
+ def online_update(model, input_sentence, target_response, max_seq_len, search_context="", file_context="", conversation_context=""):
194
  # Accept any language; just avoid corrupted or repetitive targets
195
  is_response_clean = not any(t in target_response for t in [voc.UNK, "i couldn't generate"])
196
  is_not_repetitive = not check_repetition(target_response, max_repeat=2)
 
199
  print("Skipping online update: Target response is corrupted or highly repetitive.")
200
  return
201
 
202
+ prefix_search = f"According to a search result: {to_ascii(search_context)}. " if search_context else ""
203
+ prefix_file = f"Based on the attached file: {to_ascii(file_context)}. " if file_context else ""
204
  context_prefix = f"{conversation_context} " if conversation_context else ""
205
 
206
+ # This is the CRITICAL STEP for learning from user input:
207
+ # Combine all contextual elements with the user's input sentence at the end.
208
+ full_prompt_text = f"{SYSTEM_INSTRUCTION} {context_prefix}{prefix_search}{prefix_file}{input_sentence}"
209
  full_prompt_text = to_ascii(full_prompt_text)
210
 
211
  prompt_tokens = indexes_from_sentence(voc, full_prompt_text)[:-1]
 
301
  return history, "Cannot process feedback: No recent AI response found."
302
 
303
  last_user_message, last_ai_response = history[-1][0], history[-1][1]
304
+
305
+ # 1. EXTRACT CONTEXTS (File/Search) for Training
306
+ file_context_text = ""
307
+ # Look for the server-side file marker (Attached: filename)
308
+ file_match = re.search(r"\(Attached: (.*?)\)", last_user_message)
309
+ if file_match:
310
+ file_name = file_match.group(1)
311
+ # Assuming we can retrieve or generate a summary of the file content here.
312
+ file_context_text = f"The user provided a file named '{file_name}'."
313
+
314
+ # Clean the user message for re-running search and training prompt
315
+ clean_user_message = last_user_message
316
+ clean_user_message = re.sub(r'\(Attached:.*?\)', '', clean_user_message).strip()
317
+ clean_user_message = re.sub(r'\[IMAGE_PREVIEW_URL:.*?]', '', clean_user_message).strip()
318
+
319
+ search_context_text = ""
320
+ if "?" in clean_user_message or any(
321
+ clean_user_message.lower().startswith(q) for q in ["what is", "who is", "how to"]
322
+ ):
323
+ # Re-run the web search to get the context text used by the model
324
+ search_context_text = perform_web_search(clean_user_message)
325
+
326
  print(f"\n--- FEEDBACK RECEIVED ---")
327
  print(f"Rating: {rating}")
328
  print(f"User Prompt: '{last_user_message}'")
329
  print(f"AI Response: '{last_ai_response}'")
330
+ print(f"Contexts for Learning - Search: '{search_context_text[:30]}...', File: '{file_context_text}'")
331
  print(f"-------------------------\n")
332
 
333
  if rating == "Good Response":
334
+ # 1. Gather conversation context (previous turn)
335
  conversation_context = ""
336
  if len(history) >= 2 and isinstance(history[-2], list) and len(history[-2]) == 2 and isinstance(history[-2][1], str):
337
  last_user, last_ai = history[-2][0], history[-2][1]
338
  conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
339
 
340
+ # 2. Perform Online Update (Training) - Trains on the clean prompt + all contexts
341
  online_update(
342
  gpt_model,
343
+ clean_user_message,
344
  last_ai_response,
345
  max_length,
346
+ search_context=search_context_text,
347
+ file_context=file_context_text,
348
  conversation_context=conversation_context
349
  )
350
 
351
+ # 3. Save the updated model state to disk
352
  save_checkpoint(gpt_model, optimizer, voc, CHECKPOINT_PATH)
353
 
354
  feedback_message = "Thanks for the **Good Response** rating! I just learned from that. Keep the good prompts coming! ✨"
355
  elif rating == "Bad Response":
356
+ # Log the bad response but DO NOT train (to avoid training on poor examples)
357
  feedback_message = "Acknowledged **Bad Response** feedback. I will try to be better! 🛠️"
358
  else:
359
  feedback_message = "Unknown rating received."
 
365
  # Normalize history
366
  history = history or []
367
  if not history or history[-1][1] is not None:
368
+ # NOTE: history[-1][0] is the user message received from the client.
369
+ # It already includes the file/image markers placed by the JS client.
370
  history.append([user_message, None])
371
 
372
  file_context = ""
 
379
  "please generate", "provide a much more detailed", "provide a different"
380
  ])
381
 
382
+ # Clean the user message for search, if needed
383
+ clean_user_message = user_message
384
  match = re.search(r':\s*"(.+?)"$', user_message)
385
  if is_instruction and match:
386
  clean_user_message = match.group(1).strip()
387
  model_prompt = user_message
388
  else:
 
389
  model_prompt = user_message
390
 
391
+ # Clean file/image markers from search prompt
392
+ clean_user_message = re.sub(r'\(Attached:.*?\)', '', clean_user_message).strip()
393
+ clean_user_message = re.sub(r'\[IMAGE_PREVIEW_URL:.*?]', '', clean_user_message).strip()
394
+
395
+
396
  conversation_context = ""
397
  context_history = history[:-1] if not is_instruction else history
398
  if context_history and isinstance(context_history[-1], list) and len(context_history[-1]) == 2 and isinstance(context_history[-1][1], str):
 
400
  conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
401
  print(f"Context included: {conversation_context}")
402
 
 
 
403
  search_context_text = ""
404
  search_needed = bool(web_search_enabled) or "?" in clean_user_message or any(
405
  clean_user_message.lower().startswith(q) for q in ["what is", "who is", "how to"]
 
407
  if search_needed:
408
  search_context_text = perform_web_search(clean_user_message)
409
 
410
+ # final_model_prompt includes the file context description for generation
411
  final_model_prompt = f"{file_context} {model_prompt}" if file_context else model_prompt
412
  reply = generate_response(
413
  final_model_prompt,
 
435
 
436
  def add_user_message_to_history(message, history, file_ref, web_enabled):
437
  history = history or []
438
+ # NOTE: File attachment markers are added on the client-side, so we rely on the JS message
439
+ # when called from the submit chain. This is a redundant function for Gradio native events.
 
 
 
440
  updated_history = history + [[message, None]]
441
  return updated_history, ""
442
 
 
468
  clear.click(lambda: [], None, chat, queue=False)
469
 
470
  def feedback_good_wrapper(history_state):
 
471
  return process_feedback(history_state, "Good Response")
472
 
473
  def feedback_bad_wrapper(history_state):
 
493
 
494
  # Public API: /on_submit (renamed for consistency with JS client)
495
  def chat_submit_api(msg_value, chat_value, uploaded_file_value, web_enabled_value):
496
+ # The client handles optimistic history update; we must replicate the history flow here.
497
+ updated_history = chat_value or []
498
+ updated_history.append([msg_value, None])
499
+
500
  final_history, status_msg = on_submit(
501
+ msg_value, updated_history, uploaded_file_value, web_enabled_value
502
  )
503
  return final_history, status_msg
504