Spaces:
Runtime error
Runtime error
File size: 13,044 Bytes
8a0db6c ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 32d5c15 ff50e88 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 |
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
import torch
from threading import Thread
import re
# Model configuration - using a smaller model that works well on CPU
MODEL_NAME = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
# Global variables for model and tokenizer
model = None
tokenizer = None
def load_model():
"""Load the model and tokenizer"""
global model, tokenizer
if model is None:
print("Loading model... This may take a moment on CPU.")
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
model = AutoModelForCausalLM.from_pretrained(
MODEL_NAME,
torch_dtype=torch.float32,
device_map="cpu",
low_cpu_mem_usage=True
)
print("Model loaded successfully!")
return model, tokenizer
# Default system prompts
SYSTEM_PROMPTS = {
"Default Assistant": "You are a helpful, harmless, and honest AI assistant. Provide clear, accurate, and thoughtful responses.",
"Creative Writer": "You are a creative writing assistant. Help users with storytelling, poetry, and imaginative content. Be expressive and artistic.",
"Code Helper": "You are an expert programmer. Help users write, debug, and understand code. Provide clear explanations and best practices.",
"Socratic Teacher": "You are a Socratic teacher. Instead of giving direct answers, guide users to discover answers through thoughtful questions.",
"Friendly Chat": "You are a friendly conversational partner. Be warm, engaging, and personable. Use casual language and show genuine interest.",
"Custom": ""
}
def format_chat_prompt(messages, system_prompt):
"""Format messages for TinyLlama chat format"""
formatted = f"<|system|>\n{system_prompt}</s>\n"
for msg in messages:
if msg["role"] == "user":
formatted += f"<|user|>\n{msg['content']}</s>\n"
elif msg["role"] == "assistant":
formatted += f"<|assistant|>\n{msg['content']}</s>\n"
formatted += "<|assistant|>\n"
return formatted
def chat(message, history, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p):
"""Main chat function with streaming support"""
global model, tokenizer
# Load model if not loaded
if model is None:
yield "⏳ Loading model for the first time... Please wait (this may take 1-2 minutes on CPU)..."
load_model()
# Determine system prompt
if system_prompt_choice == "Custom":
system_content = custom_system_prompt if custom_system_prompt.strip() else SYSTEM_PROMPTS["Default Assistant"]
else:
system_content = SYSTEM_PROMPTS.get(system_prompt_choice, SYSTEM_PROMPTS["Default Assistant"])
# Build messages list
messages = []
for msg in history:
if msg["role"] in ["user", "assistant"]:
messages.append({"role": msg["role"], "content": msg["content"]})
messages.append({"role": "user", "content": message})
try:
# Format the prompt
prompt = format_chat_prompt(messages, system_content)
# Tokenize
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048)
# Set up streamer
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
# Generation parameters
generation_kwargs = {
"input_ids": inputs["input_ids"],
"attention_mask": inputs["attention_mask"],
"max_new_tokens": max_tokens,
"temperature": temperature if temperature > 0 else 0.1,
"top_p": top_p,
"do_sample": temperature > 0,
"streamer": streamer,
"pad_token_id": tokenizer.eos_token_id,
"eos_token_id": tokenizer.eos_token_id,
}
# Run generation in a separate thread
thread = Thread(target=model.generate, kwargs=generation_kwargs)
thread.start()
# Stream the response
response = ""
for new_text in streamer:
response += new_text
# Clean up any remaining special tokens
clean_response = response.replace("</s>", "").strip()
yield clean_response
thread.join()
except Exception as e:
yield f"❌ Error: {str(e)}\n\nPlease try again with a shorter message or lower max tokens."
def clear_chat():
"""Clear the chat history"""
return [], ""
def export_chat(history):
"""Export chat history as text"""
if not history:
return "No chat history to export."
export_text = "# Chat Export\n\n"
for msg in history:
role = "👤 User" if msg["role"] == "user" else "🤖 Assistant"
export_text += f"## {role}\n{msg['content']}\n\n---\n\n"
return export_text
# Custom CSS
css = """
.header-container {
text-align: center;
padding: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 12px;
margin-bottom: 20px;
}
.header-container h1 {
color: white;
margin: 0;
font-size: 2em;
}
.header-container p {
color: rgba(255,255,255,0.9);
margin: 10px 0 0 0;
}
.header-container a {
color: #ffd700;
text-decoration: none;
font-weight: bold;
}
.header-container a:hover {
text-decoration: underline;
}
.info-box {
background: var(--background-fill-secondary);
padding: 10px 15px;
border-radius: 8px;
margin: 10px 0;
border-left: 4px solid #667eea;
}
.chatbot-container {
min-height: 500px;
}
"""
# Build the interface
with gr.Blocks(
title="TinyLlama Chatbot (CPU)",
theme=gr.themes.Soft(),
css=css,
fill_height=True,
footer_links=[
{"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"},
{"label": "Model", "url": "https://huggingface.co/TinyLlama/TinyLlama-1.1B-Chat-v1.0"}
]
) as demo:
# Header
gr.HTML("""
<div class="header-container">
<h1>🦙 TinyLlama Chatbot</h1>
<p>Powered by TinyLlama-1.1B-Chat - Running locally on CPU</p>
<p><a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank">Built with anycoder</a></p>
</div>
""")
gr.HTML("""
<div class="info-box">
ℹ️ <strong>CPU Mode:</strong> This chatbot runs entirely on CPU without any API calls.
First response may take longer as the model loads. Responses are generated locally.
</div>
""")
with gr.Row():
# Main chat column
with gr.Column(scale=3):
chatbot = gr.Chatbot(
label="Chat",
height=500,
type="messages",
show_copy_button=True,
render_markdown=True,
elem_classes=["chatbot-container"]
)
with gr.Row():
msg = gr.Textbox(
placeholder="Type your message here... (Press Enter to send)",
label="Message",
scale=4,
lines=2,
max_lines=5,
autofocus=True
)
send_btn = gr.Button("Send 📤", variant="primary", scale=1)
with gr.Row():
clear_btn = gr.Button("🗑️ Clear Chat", variant="secondary")
regenerate_btn = gr.Button("🔄 Regenerate", variant="secondary")
export_btn = gr.Button("📥 Export", variant="secondary")
# Settings sidebar
with gr.Column(scale=1):
gr.Markdown("### ⚙️ Settings")
with gr.Accordion("System Prompt", open=True):
system_prompt_choice = gr.Dropdown(
choices=list(SYSTEM_PROMPTS.keys()),
value="Default Assistant",
label="Preset Prompts",
interactive=True
)
custom_system_prompt = gr.Textbox(
label="Custom System Prompt",
placeholder="Enter your custom system prompt here...",
lines=4,
visible=False
)
with gr.Accordion("Generation Parameters", open=False):
temperature = gr.Slider(
minimum=0.0,
maximum=2.0,
value=0.7,
step=0.1,
label="Temperature",
info="Higher = more creative, Lower = more focused"
)
max_tokens = gr.Slider(
minimum=32,
maximum=512,
value=256,
step=32,
label="Max Tokens",
info="Maximum response length (lower = faster on CPU)"
)
top_p = gr.Slider(
minimum=0.0,
maximum=1.0,
value=0.9,
step=0.05,
label="Top P",
info="Nucleus sampling parameter"
)
# Export output
export_output = gr.Textbox(
label="Exported Chat",
lines=10,
visible=False,
show_copy_button=True
)
# Examples
gr.Markdown("### 💡 Example Prompts")
gr.Examples(
examples=[
["Explain what machine learning is in simple terms"],
["Write a short poem about the ocean"],
["What are three tips for staying productive?"],
["Tell me a fun fact about space"],
["How do I make a simple pasta dish?"],
],
inputs=msg,
label=""
)
# Event handlers
def toggle_custom_prompt(choice):
return gr.Textbox(visible=(choice == "Custom"))
system_prompt_choice.change(
toggle_custom_prompt,
inputs=[system_prompt_choice],
outputs=[custom_system_prompt]
)
def user_message(message, history):
if message.strip():
history.append({"role": "user", "content": message})
return "", history
def bot_response(history, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p):
if not history:
yield history
return
user_msg = history[-1]["content"]
history_for_api = history[:-1]
history.append({"role": "assistant", "content": ""})
for response in chat(user_msg, history_for_api, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p):
history[-1]["content"] = response
yield history
def regenerate(history, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p):
if len(history) >= 2:
# Remove last assistant message
history = history[:-1]
# Get last user message
user_msg = history[-1]["content"]
history_for_api = history[:-1]
history.append({"role": "assistant", "content": ""})
for response in chat(user_msg, history_for_api, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p):
history[-1]["content"] = response
yield history
else:
yield history
def show_export(history):
export_text = export_chat(history)
return gr.Textbox(visible=True, value=export_text)
# Wire up events
msg.submit(
user_message,
inputs=[msg, chatbot],
outputs=[msg, chatbot],
queue=False
).then(
bot_response,
inputs=[chatbot, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p],
outputs=[chatbot]
)
send_btn.click(
user_message,
inputs=[msg, chatbot],
outputs=[msg, chatbot],
queue=False
).then(
bot_response,
inputs=[chatbot, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p],
outputs=[chatbot]
)
clear_btn.click(
clear_chat,
outputs=[chatbot, msg]
)
regenerate_btn.click(
regenerate,
inputs=[chatbot, system_prompt_choice, custom_system_prompt, temperature, max_tokens, top_p],
outputs=[chatbot]
)
export_btn.click(
show_export,
inputs=[chatbot],
outputs=[export_output]
)
if __name__ == "__main__":
# Pre-load model on startup (optional - can be commented out for faster startup)
print("Starting TinyLlama Chatbot...")
demo.launch() |