Splashdude commited on
Commit
e9c6c9e
·
verified ·
1 Parent(s): 9b08ee0

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +74 -61
app.py CHANGED
@@ -7,8 +7,7 @@ MODEL_ID = "Splashdude/smollm-chatbot"
7
  SYSTEM_PROMPT = (
8
  "You are a helpful, friendly AI assistant. "
9
  "You give clear, accurate, and conversational answers. "
10
- "Keep responses concise unless the user asks for detail. "
11
- "Remember what the user tells you and refer back to it when asked."
12
  )
13
 
14
  model = None
@@ -27,58 +26,31 @@ def load_model():
27
  print("Model loaded!")
28
 
29
 
30
- def extract_text(content):
31
- """Extract plain text from Gradio content (handles str, list, dict)."""
32
- if isinstance(content, str):
33
- return content
34
- if isinstance(content, list):
35
- parts = []
36
- for item in content:
37
- if isinstance(item, str):
38
- parts.append(item)
39
- elif isinstance(item, dict):
40
- parts.append(item.get("text", item.get("content", str(item))))
41
- else:
42
- parts.append(str(item))
43
- return " ".join(parts)
44
- if isinstance(content, dict):
45
- return content.get("text", content.get("content", str(content)))
46
- return str(content)
47
-
48
-
49
- def build_messages(history, new_message):
50
- """Convert Gradio history to chat messages list."""
51
- messages = [{"role": "system", "content": SYSTEM_PROMPT}]
52
- for msg in history:
53
- role = msg.get("role", "")
54
- content = extract_text(msg.get("content", ""))
55
- if role in ("user", "assistant") and content:
56
- messages.append({"role": role, "content": content})
57
- messages.append({"role": "user", "content": new_message})
58
- return messages
59
-
60
-
61
- def generate_response(message, history):
62
  if model is None:
63
  try:
64
  load_model()
65
  except Exception as e:
66
- yield f"Error loading model: {e}"
 
 
67
  return
68
 
69
  if not message or not message.strip():
70
- yield "Please type a message."
71
  return
72
 
73
- try:
74
- messages = build_messages(history, message)
75
- text = tokenizer.apply_chat_template(
76
- messages, tokenize=False, add_generation_prompt=True
77
- )
78
- inputs = tokenizer(text, return_tensors="pt")
79
- except Exception as e:
80
- yield f"Error building prompt: {e}"
81
- return
 
 
82
 
83
  streamer = TextIteratorStreamer(
84
  tokenizer, skip_prompt=True, skip_special_tokens=True
@@ -101,26 +73,67 @@ def generate_response(message, history):
101
  partial = ""
102
  for token in streamer:
103
  partial += token
104
- yield partial
 
105
 
106
  thread.join()
107
 
108
 
109
- demo = gr.ChatInterface(
110
- fn=generate_response,
111
- title="AI Chatbot",
112
- description="A fast conversational AI chatbot powered by SmolLM2-360M.",
113
- examples=[
114
- "Hello! How are you?",
115
- "Tell me a joke.",
116
- "What is the capital of France?",
117
- "Explain gravity in simple terms.",
118
- "Write a short poem about the ocean.",
119
- "What are some tips for staying productive?",
120
- ],
121
- save_history=True,
122
- editable=True,
123
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
  if __name__ == "__main__":
 
126
  demo.launch()
 
7
  SYSTEM_PROMPT = (
8
  "You are a helpful, friendly AI assistant. "
9
  "You give clear, accurate, and conversational answers. "
10
+ "Remember what the user tells you in this conversation."
 
11
  )
12
 
13
  model = None
 
26
  print("Model loaded!")
27
 
28
 
29
+ def generate_response(message, chat_history):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  if model is None:
31
  try:
32
  load_model()
33
  except Exception as e:
34
+ chat_history.append({"role": "user", "content": message})
35
+ chat_history.append({"role": "assistant", "content": f"Error: {e}"})
36
+ yield chat_history, ""
37
  return
38
 
39
  if not message or not message.strip():
40
+ yield chat_history, ""
41
  return
42
 
43
+ chat_history.append({"role": "user", "content": message})
44
+ chat_history.append({"role": "assistant", "content": ""})
45
+
46
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}]
47
+ for msg in chat_history[:-1]:
48
+ messages.append({"role": msg["role"], "content": msg["content"]})
49
+
50
+ text = tokenizer.apply_chat_template(
51
+ messages, tokenize=False, add_generation_prompt=True
52
+ )
53
+ inputs = tokenizer(text, return_tensors="pt")
54
 
55
  streamer = TextIteratorStreamer(
56
  tokenizer, skip_prompt=True, skip_special_tokens=True
 
73
  partial = ""
74
  for token in streamer:
75
  partial += token
76
+ chat_history[-1]["content"] = partial
77
+ yield chat_history, ""
78
 
79
  thread.join()
80
 
81
 
82
+ def clear_chat():
83
+ return [], ""
84
+
85
+
86
+ with gr.Blocks(title="AI Chatbot", theme=gr.themes.Soft()) as demo:
87
+ gr.Markdown("# AI Chatbot\nFast conversational AI powered by SmolLM2-360M.")
88
+
89
+ chatbot = gr.Chatbot(type="messages", height=500, show_copy_button=True, label="Chat")
90
+ chat_state = gr.State([])
91
+
92
+ with gr.Row():
93
+ msg = gr.Textbox(
94
+ placeholder="Type your message...",
95
+ show_label=False,
96
+ container=False,
97
+ scale=8,
98
+ )
99
+ submit = gr.Button("Send", variant="primary", scale=1)
100
+ clear = gr.Button("New Chat", scale=1)
101
+
102
+ gr.Examples(
103
+ examples=[
104
+ "Hello! How are you?",
105
+ "Tell me a joke.",
106
+ "What is the capital of France?",
107
+ "Explain gravity in simple terms.",
108
+ ],
109
+ inputs=msg,
110
+ label="Examples",
111
+ )
112
+
113
+ def user_submit(message, history):
114
+ for updated_history, _ in generate_response(message, history):
115
+ yield updated_history, "", updated_history
116
+
117
+ def bot_response(message, history):
118
+ for updated_history, _ in generate_response(message, history):
119
+ yield updated_history, updated_history
120
+
121
+ msg.submit(
122
+ user_submit,
123
+ [msg, chat_state],
124
+ [chatbot, msg, chat_state],
125
+ queue=True,
126
+ )
127
+
128
+ submit.click(
129
+ user_submit,
130
+ [msg, chat_state],
131
+ [chatbot, msg, chat_state],
132
+ queue=True,
133
+ )
134
+
135
+ clear.click(clear_chat, None, [chatbot, chat_state])
136
 
137
  if __name__ == "__main__":
138
+ demo.queue()
139
  demo.launch()