ar12c commited on
Commit
641b2bd
·
verified ·
1 Parent(s): 4a88d4e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -7
app.py CHANGED
@@ -16,7 +16,7 @@ SYSTEM_INSTRUCTION = "You are a friendly and concise general-purpose AI assistan
16
  # --- END NEW SYSTEM PROMPT ---
17
 
18
  # --- NEW: Online Learning Hyperparameter ---
19
- ONLINE_LEARNING_EPOCHS = 5
20
  # --- END NEW HYPERPARAMETER ---
21
 
22
 
@@ -233,7 +233,7 @@ def online_update(model, input_sentence, target_response, max_seq_len, search_co
233
  model.train()
234
  causal = make_bool_causal_mask(L, device)
235
 
236
- # Loop 5 times for a fixed number of learning epochs
237
  last_loss = 0.0
238
  for epoch in range(ONLINE_LEARNING_EPOCHS):
239
  optimizer.zero_grad()
@@ -330,6 +330,56 @@ def generate_response(prompt, search_context="", conversation_context=""):
330
  return "I couldn't generate a stable English response. Please try a shorter or clearer prompt in English."
331
  return text
332
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333
  with gr.Blocks(title="OkemoLLM") as demo:
334
  gr.Markdown("# OkemoLLM (English-only, Online Learning & Web Search Enabled with 1-Turn Context)")
335
  chat = gr.Chatbot(height=500)
@@ -386,10 +436,9 @@ with gr.Blocks(title="OkemoLLM") as demo:
386
  # MODIFICATION: Pass conversation_context to generator
387
  reply = generate_response(model_prompt, search_context=search_context_text, conversation_context=conversation_context)
388
 
389
- # 6. Online fine-tuning only on genuine user messages (not instructions)
390
- if not is_instruction:
391
- # MODIFICATION: Pass conversation_context to online_update
392
- online_update(gpt_model, clean_user_message, reply, max_length, search_context=search_context_text, conversation_context=conversation_context)
393
 
394
  # 7. Update the history: Use the clean user message, regardless of the prompt sent to the model.
395
  history[-1] = (clean_user_message, reply)
@@ -397,6 +446,44 @@ with gr.Blocks(title="OkemoLLM") as demo:
397
 
398
  msg.submit(on_submit, inputs=[msg, chat], outputs=[chat, msg])
399
  clear.click(lambda: [], None, chat)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
400
 
401
  if __name__ == "__main__":
402
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  # --- END NEW SYSTEM PROMPT ---
17
 
18
  # --- NEW: Online Learning Hyperparameter ---
19
+ ONLINE_LEARNING_EPOCHS = 1 # Changed from 5 to 1
20
  # --- END NEW HYPERPARAMETER ---
21
 
22
 
 
233
  model.train()
234
  causal = make_bool_causal_mask(L, device)
235
 
236
+ # Loop 1 time for a fixed number of learning epochs
237
  last_loss = 0.0
238
  for epoch in range(ONLINE_LEARNING_EPOCHS):
239
  optimizer.zero_grad()
 
330
  return "I couldn't generate a stable English response. Please try a shorter or clearer prompt in English."
331
  return text
332
 
333
+
334
+ # --- NEW GRADIO FUNCTION TO HANDLE FEEDBACK ---
335
+ def process_feedback(history, rating):
336
+ """
337
+ Handles feedback from the client. Only triggers online_update (training) for "Good Response".
338
+ For "Bad Response", it logs the event but skips training.
339
+ """
340
+ if not history or not history[-1][1]:
341
+ return history, "Cannot process feedback: No recent AI response found."
342
+
343
+ last_user_message, last_ai_response = history[-1]
344
+
345
+ # 1. Log the event (always)
346
+ print(f"\n--- FEEDBACK RECEIVED ---")
347
+ print(f"Rating: {rating}")
348
+ print(f"User Prompt: '{last_user_message}'")
349
+ print(f"AI Response: '{last_ai_response}'")
350
+ print(f"-------------------------\n")
351
+
352
+ if rating == "Good Response":
353
+ # 2. Extract conversation context from previous turn (if available)
354
+ conversation_context = ""
355
+ if len(history) >= 2 and history[-2][1]:
356
+ last_user, last_ai = history[-2]
357
+ conversation_context = f"User: {to_ascii(last_user)} Response: {to_ascii(last_ai)}"
358
+
359
+ # 3. Trigger online update (training) only for good responses
360
+ # NOTE: We skip searching again, assuming the previous generation step included search if needed.
361
+ # This keeps the training focused on the interaction itself.
362
+ online_update(
363
+ gpt_model,
364
+ last_user_message,
365
+ last_ai_response,
366
+ max_length,
367
+ search_context="", # Search context needs to be cached/passed if required for learning
368
+ conversation_context=conversation_context
369
+ )
370
+ feedback_message = f"Thanks for the **Good Response** rating! I just learned from that. Keep the good prompts coming! ✨"
371
+
372
+ elif rating == "Bad Response":
373
+ # 4. Skip training for bad responses to avoid confusing the model with unstable/undesired data.
374
+ feedback_message = f"Acknowledged **Bad Response** feedback. I will try to be better! 🛠️"
375
+
376
+ else:
377
+ feedback_message = "Unknown rating received."
378
+
379
+ return history, feedback_message
380
+ # --- END NEW GRADIO FUNCTION ---
381
+
382
+
383
  with gr.Blocks(title="OkemoLLM") as demo:
384
  gr.Markdown("# OkemoLLM (English-only, Online Learning & Web Search Enabled with 1-Turn Context)")
385
  chat = gr.Chatbot(height=500)
 
436
  # MODIFICATION: Pass conversation_context to generator
437
  reply = generate_response(model_prompt, search_context=search_context_text, conversation_context=conversation_context)
438
 
439
+ # 6. Skip automatic training on submit. Training now only occurs via the 'Good Response' button.
440
+ # if not is_instruction:
441
+ # online_update(...)
 
442
 
443
  # 7. Update the history: Use the clean user message, regardless of the prompt sent to the model.
444
  history[-1] = (clean_user_message, reply)
 
446
 
447
  msg.submit(on_submit, inputs=[msg, chat], outputs=[chat, msg])
448
  clear.click(lambda: [], None, chat)
449
+
450
+ # --- NEW: Gradio Endpoint for Feedback ---
451
+ # This single endpoint handles both good and bad responses
452
+ demo.queue().custom_component(
453
+ process_feedback,
454
+ inputs=[chat, gr.State("Good Response")], # Initial value for State is ignored, but structure needed
455
+ outputs=[chat, gr.Textbox(visible=False)] # outputs updated history and a message to the status textbox
456
+ ).as_custom_function(
457
+ # NOTE: The client-side JS needs to be updated to call '/process_feedback' and pass the rating.
458
+ # However, for stability within Gradio, we define two specific API endpoints the client can use.
459
+ # Since Gradio doesn't easily allow passing a fixed parameter value in the endpoint mapping,
460
+ # we will define two distinct functions mapping to the same core logic for the client.
461
+ # The client will call /feedback_good or /feedback_bad, which will run this function.
462
+ # Since we cannot easily pass 'Good Response' or 'Bad Response' as a fixed argument in the custom component structure in Gradio Blocks, we will implement this via two separate, simple Gradio interface calls outside of the Blocks structure, or rely on the client to call /predict with the rating.
463
+ # For simplicity and to match the client's original intent, we'll use simple Gradio interfaces.
464
+ name="feedback_endpoint"
465
+ )
466
 
467
  if __name__ == "__main__":
468
+ # Define separate, simple Gradio interfaces that the client can hit to simulate the fixed feedback payload
469
+ with gr.Blocks() as feedback_interface:
470
+ gr.Interface(
471
+ fn=lambda h: process_feedback(h, "Good Response"),
472
+ inputs=gr.State([]),
473
+ outputs=[gr.State([]), gr.Textbox()],
474
+ api_name="feedback_good", # Client calls /run/feedback_good
475
+ live=False,
476
+ allow_flagging="never",
477
+
478
+ )
479
+ gr.Interface(
480
+ fn=lambda h: process_feedback(h, "Bad Response"),
481
+ inputs=gr.State([]),
482
+ outputs=[gr.State([]), gr.Textbox()],
483
+ api_name="feedback_bad", # Client calls /run/feedback_bad
484
+ live=False,
485
+ allow_flagging="never",
486
+ )
487
+
488
+ # We launch the main app demo, but the feedback endpoints are registered via their interfaces.
489
+ demo.launch()