Ruurd commited on
Commit
2db3bb3
·
1 Parent(s): 0115682

Change chatbot

Browse files
Files changed (1) hide show
  1. app.py +38 -33
app.py CHANGED
@@ -1,14 +1,14 @@
1
  import os
2
  import torch
 
3
  import gradio as gr
4
  import spaces
5
  from transformers import AutoTokenizer, AutoModelForCausalLM
6
 
7
- # Global model/tokenizer
8
  current_model = None
9
  current_tokenizer = None
10
 
11
- # Load model when selected
12
  def load_model_on_selection(model_name, progress=gr.Progress(track_tqdm=False)):
13
  global current_model, current_tokenizer
14
  token = os.getenv("HF_TOKEN")
@@ -20,34 +20,40 @@ def load_model_on_selection(model_name, progress=gr.Progress(track_tqdm=False)):
20
  current_model = AutoModelForCausalLM.from_pretrained(
21
  model_name,
22
  torch_dtype=torch.float16,
23
- device_map="cpu",
24
  use_auth_token=token
25
  )
26
 
27
  progress(1, desc="Model ready.")
28
  return f"{model_name} loaded and ready!"
29
 
30
- # Inference - yields response token-by-token
 
 
 
 
 
 
 
 
 
 
 
31
  @spaces.GPU
32
- def chat_with_model(history):
33
  global current_model, current_tokenizer
34
  if current_model is None or current_tokenizer is None:
35
- yield history + [("⚠️ No model loaded.", "")]
 
36
 
37
  current_model.to("cuda")
38
 
39
- # Combine conversation history into prompt
40
- prompt = ""
41
- for user_msg, bot_msg in history:
42
- prompt += f"[INST] {user_msg.strip()} [/INST] {bot_msg.strip()} "
43
- prompt += f"[INST] {history[-1][0]} [/INST]"
44
-
45
  inputs = current_tokenizer(prompt, return_tensors="pt").to(current_model.device)
46
- output_ids = []
47
 
48
- # Clone history to avoid mutating during yield
49
- updated_history = history.copy()
50
- updated_history[-1] = (history[-1][0], "")
51
 
52
  for token_id in current_model.generate(
53
  **inputs,
@@ -55,26 +61,25 @@ def chat_with_model(history):
55
  do_sample=False,
56
  return_dict_in_generate=True,
57
  output_scores=False
58
- ).sequences[0]:
59
  output_ids.append(token_id.item())
60
  decoded = current_tokenizer.decode(output_ids, skip_special_tokens=True)
61
- updated_history[-1] = (history[-1][0], decoded)
62
- yield updated_history
63
 
64
- # When user submits a message
65
- def add_user_message(message, history):
66
- return "", history + [(message, "")]
67
 
68
- # Model choices
69
  model_choices = [
70
  "meta-llama/Llama-3.2-3B-Instruct",
71
  "deepseek-ai/DeepSeek-R1-Distill-Llama-8B",
72
  "google/gemma-7b"
73
  ]
74
 
75
- # Gradio UI
76
  with gr.Blocks() as demo:
77
- gr.Markdown("## Clinical Chatbot — LLaMA, DeepSeek, Gemma")
78
 
79
  default_model = gr.State("meta-llama/Llama-3.2-3B-Instruct")
80
 
@@ -82,22 +87,22 @@ with gr.Blocks() as demo:
82
  model_selector = gr.Dropdown(choices=model_choices, label="Select Model")
83
  model_status = gr.Textbox(label="Model Status", interactive=False)
84
 
85
- chatbot = gr.Chatbot(label="Chat")
86
- msg = gr.Textbox(label="Your Message", placeholder="Enter your clinical query...", show_label=False)
87
- clear_btn = gr.Button("Clear Chat")
88
 
89
- # Load model on launch
90
  demo.load(fn=load_model_on_selection, inputs=default_model, outputs=model_status)
91
 
92
- # Load model on dropdown selection
93
  model_selector.change(fn=load_model_on_selection, inputs=model_selector, outputs=model_status)
94
 
95
- # On message submit: update history, then stream bot reply
96
  msg.submit(add_user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
97
- fn=chat_with_model, inputs=chatbot, outputs=chatbot
98
  )
99
 
100
  # Clear chat
101
- clear_btn.click(lambda: [], None, chatbot, queue=False)
102
 
103
  demo.launch()
 
1
  import os
2
  import torch
3
+ import time
4
  import gradio as gr
5
  import spaces
6
  from transformers import AutoTokenizer, AutoModelForCausalLM
7
 
8
+ # Globals
9
  current_model = None
10
  current_tokenizer = None
11
 
 
12
  def load_model_on_selection(model_name, progress=gr.Progress(track_tqdm=False)):
13
  global current_model, current_tokenizer
14
  token = os.getenv("HF_TOKEN")
 
20
  current_model = AutoModelForCausalLM.from_pretrained(
21
  model_name,
22
  torch_dtype=torch.float16,
23
+ device_map="cpu", # loaded to CPU initially
24
  use_auth_token=token
25
  )
26
 
27
  progress(1, desc="Model ready.")
28
  return f"{model_name} loaded and ready!"
29
 
30
+ # Format conversation as plain text
31
+ def format_prompt(messages):
32
+ prompt = ""
33
+ for msg in messages:
34
+ role = msg["role"]
35
+ if role == "user":
36
+ prompt += f"User: {msg['content'].strip()}\n"
37
+ elif role == "assistant":
38
+ prompt += f"Assistant: {msg['content'].strip()}\n"
39
+ prompt += "Assistant:"
40
+ return prompt
41
+
42
  @spaces.GPU
43
+ def chat_with_model(messages):
44
  global current_model, current_tokenizer
45
  if current_model is None or current_tokenizer is None:
46
+ yield messages + [{"role": "assistant", "content": "⚠️ No model loaded."}]
47
+ return
48
 
49
  current_model.to("cuda")
50
 
51
+ prompt = format_prompt(messages)
 
 
 
 
 
52
  inputs = current_tokenizer(prompt, return_tensors="pt").to(current_model.device)
 
53
 
54
+ output_ids = []
55
+ messages = messages.copy()
56
+ messages.append({"role": "assistant", "content": ""})
57
 
58
  for token_id in current_model.generate(
59
  **inputs,
 
61
  do_sample=False,
62
  return_dict_in_generate=True,
63
  output_scores=False
64
+ ).sequences[0][inputs['input_ids'].shape[-1]:]: # skip input tokens
65
  output_ids.append(token_id.item())
66
  decoded = current_tokenizer.decode(output_ids, skip_special_tokens=True)
67
+ messages[-1]["content"] = decoded
68
+ yield messages
69
 
70
+ def add_user_message(user_input, history):
71
+ return "", history + [{"role": "user", "content": user_input}]
 
72
 
73
+ # Available models
74
  model_choices = [
75
  "meta-llama/Llama-3.2-3B-Instruct",
76
  "deepseek-ai/DeepSeek-R1-Distill-Llama-8B",
77
  "google/gemma-7b"
78
  ]
79
 
80
+ # UI
81
  with gr.Blocks() as demo:
82
+ gr.Markdown("## Clinical Chatbot (Streaming) — LLaMA, DeepSeek, Gemma")
83
 
84
  default_model = gr.State("meta-llama/Llama-3.2-3B-Instruct")
85
 
 
87
  model_selector = gr.Dropdown(choices=model_choices, label="Select Model")
88
  model_status = gr.Textbox(label="Model Status", interactive=False)
89
 
90
+ chatbot = gr.Chatbot(label="Chat", type="messages")
91
+ msg = gr.Textbox(label="Your message", placeholder="Enter clinical input...", show_label=False)
92
+ clear = gr.Button("Clear")
93
 
94
+ # Load default model on startup
95
  demo.load(fn=load_model_on_selection, inputs=default_model, outputs=model_status)
96
 
97
+ # Load selected model manually
98
  model_selector.change(fn=load_model_on_selection, inputs=model_selector, outputs=model_status)
99
 
100
+ # Submit message + stream model response
101
  msg.submit(add_user_message, [msg, chatbot], [msg, chatbot], queue=False).then(
102
+ chat_with_model, chatbot, chatbot
103
  )
104
 
105
  # Clear chat
106
+ clear.click(lambda: [], None, chatbot, queue=False)
107
 
108
  demo.launch()