Spaces:
Runtime error
Runtime error
File size: 12,255 Bytes
2d5c442 | 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 | """
AI Chatbot powered by HuggingFace Model
A modern conversational AI built with Gradio 6 and transformers
"""
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
import warnings
warnings.filterwarnings("ignore")
# Model configuration
MODEL_NAME = "microsoft/DialoGPT-medium"
def load_chatbot():
"""
Load the conversational model and tokenizer from HuggingFace.
Returns a conversational pipeline for generating responses.
"""
try:
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, padding_side="left")
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME)
conversation_pipeline = pipeline(
"text-generation",
model=model,
tokenizer=tokenizer,
max_new_tokens=150,
do_sample=True,
temperature=0.7,
top_p=0.95,
pad_token_id=tokenizer.eos_token_id
)
return conversation_pipeline
except Exception as e:
raise RuntimeError(f"Failed to load model: {str(e)}")
# Global pipeline variable
chat_pipeline = None
def get_chat_pipeline():
"""Get or initialize the chat pipeline."""
global chat_pipeline
if chat_pipeline is None:
chat_pipeline = load_chatbot()
return chat_pipeline
def format_prompt(message, history):
"""Format the conversation history and current message into a prompt."""
prompt = ""
# Add conversation history
for user_msg, bot_msg in history:
prompt += f"<|user|>{user_msg}<|endoftext|>"
prompt += f"<|assistant|>{bot_msg}<|endoftext|>"
# Add current message
prompt += f"<|user|>{message}<|endoftext|>"
prompt += "<|assistant|>"
return prompt
def chatbot_fn(message, history, system_prompt, max_length, temperature, top_p):
"""
Generate a response from the chatbot based on user input.
Args:
message: User's input message
history: List of previous (user, bot) message tuples
system_prompt: System prompt to set the bot's behavior
max_length: Maximum length of generated response
temperature: Randomness of generation (0.0-2.0)
top_p: Top-p sampling parameter (0.0-1.0)
Returns:
Updated conversation history with the new response
"""
# Validate input
if not message or not message.strip():
return history + [("Empty message", "Please enter a message to chat!")]
# Update pipeline parameters
pipeline = get_chat_pipeline()
pipeline.task_kwargs = {
"max_new_tokens": max_length,
"do_sample": temperature > 0,
"temperature": temperature if temperature > 0 else None,
"top_p": top_p if top_p < 1.0 else None,
}
try:
# Format the prompt with history
full_prompt = format_prompt(message, history)
# Add system prompt context
if system_prompt:
full_prompt = f"<|system|>{system_prompt}<|endoftext|>\n{full_prompt}"
# Generate response
response = pipeline(
full_prompt,
max_new_tokens=max_length,
do_sample=temperature > 0,
temperature=temperature if temperature > 0 else 0.7,
top_p=top_p if top_p < 1.0 else 0.95,
pad_token_id=50256, # EOS token for DialoGPT
truncation=True
)
# Extract the generated text
generated_text = response[0]["generated_text"]
# Remove the prompt from the response
response_text = generated_text[len(full_prompt):].strip()
# Clean up the response - remove special tokens
for token in ["<|endoftext|>", "<|user|>", "<|assistant|>", "<|system|>"]:
response_text = response_text.split(token)[0].strip()
# If response is empty or too short, provide a fallback
if not response_text or len(response_text) < 2:
response_text = "I'm not sure how to respond to that. Could you try again?"
# Add the new exchange to history
new_history = history + [(message, response_text)]
return new_history
except Exception as e:
error_msg = f"Sorry, I encountered an error: {str(e)}"
return history + [(message, error_msg)]
def clear_chat():
"""Clear the chat history."""
return []
# Create custom theme for the chatbot
chatbot_theme = gr.themes.Soft(
primary_hue="indigo",
secondary_hue="purple",
neutral_hue="slate",
font=gr.themes.GoogleFont("Inter"),
text_size="lg",
spacing_size="md",
radius_size="lg"
).set(
button_primary_background_fill="*primary_600",
button_primary_background_fill_hover="*primary_700",
button_secondary_background_fill="*secondary_300",
button_secondary_background_fill_hover="*secondary_400",
block_title_text_weight="600",
block_background_fill_dark="*neutral_800",
)
# Custom CSS for enhanced styling
custom_css = """
.gradio-container {
max-width: 1200px !important;
}
.chatbot-container {
background: linear-gradient(135deg, #f5f7fa 0%, #e4e8ec 100%);
border-radius: 16px;
padding: 20px;
}
.chat-header {
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.user-message {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 18px 18px 4px 18px;
padding: 12px 16px;
margin: 8px 0;
}
.bot-message {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
color: white;
border-radius: 18px 18px 18px 4px;
padding: 12px 16px;
margin: 8px 0;
}
.settings-panel {
background: rgba(255, 255, 255, 0.9);
border-radius: 12px;
padding: 16px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
.loading-indicator {
animation: pulse 1.5s infinite;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
"""
# Build the Gradio application
with gr.Blocks(
title="AI Chatbot - Powered by HuggingFace",
fill_height=True,
fill_width=True
) as demo:
# Header with branding
with gr.Row():
gr.HTML("""
<div style="text-align: center; padding: 20px 0;">
<h1 style="font-size: 2.5em; margin-bottom: 10px; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;">
π€ AI Chatbot
</h1>
<p style="color: #666; font-size: 1.1em;">
Powered by Microsoft DialoGPT β’ Built with <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #667eea;">anycoder</a>
</p>
</div>
""")
# Main content area
with gr.Row(equal_height=True):
# Settings sidebar
with gr.Column(scale=1, min_width=280):
with gr.Group(elem_classes=["settings-panel"]):
gr.Markdown("### βοΈ Chat Settings")
system_prompt = gr.Textbox(
label="System Prompt",
placeholder="You are a helpful and friendly assistant...",
value="You are a helpful, friendly AI assistant. You provide clear, concise, and accurate responses.",
lines=3,
max_lines=5
)
with gr.Accordion("Advanced Settings", open=False):
max_length = gr.Slider(
label="Max Response Length",
minimum=50,
maximum=300,
value=150,
step=10
)
temperature = gr.Slider(
label="Temperature (Creativity)",
minimum=0.0,
maximum=2.0,
value=0.7,
step=0.1,
info="Higher = more creative, Lower = more focused"
)
top_p = gr.Slider(
label="Top-p Sampling",
minimum=0.1,
maximum=1.0,
value=0.95,
step=0.05,
info="Controls vocabulary diversity"
)
clear_btn = gr.Button(
"ποΈ Clear Chat",
variant="secondary",
size="lg"
)
gr.Markdown("""
### π‘ Tips
- Be specific in your questions
- Try different prompts
- Adjust temperature for creativity
- Clear chat to start fresh
""")
# Chat interface
with gr.Column(scale=3):
with gr.Group(elem_classes=["chatbot-container"]):
chatbot = gr.Chatbot(
label="π¬ Conversation",
placeholder="Start chatting with the AI!",
height=450,
bubble_full_width=False,
avatar_images=("π€", "π€"),
latex_delimiters=[],
show_copy_button=True,
render_markdown=True
)
# Input area
with gr.Row():
message_input = gr.Textbox(
placeholder="Type your message here...",
label=None,
show_label=False,
scale=5,
lines=2,
max_lines=4,
submit_btn=True
)
submit_btn = gr.Button(
"Send",
variant="primary",
scale=1,
size="lg"
)
# Example prompts
with gr.Row():
gr.Markdown("### β¨ Try these prompts:")
with gr.Row():
examples = gr.Examples(
examples=[
["Tell me about artificial intelligence"],
["What are some tips for productivity?"],
["Explain quantum computing simply"],
["Write a short poem about nature"]
],
inputs=message_input,
label=None
)
# Event handlers
submit_btn.click(
fn=chatbot_fn,
inputs=[
message_input,
chatbot,
system_prompt,
max_length,
temperature,
top_p
],
outputs=chatbot,
api_visibility="public",
show_progress="minimal"
)
message_input.submit(
fn=chatbot_fn,
inputs=[
message_input,
chatbot,
system_prompt,
max_length,
temperature,
top_p
],
outputs=chatbot,
api_visibility="public",
show_progress="minimal"
)
clear_btn.click(
fn=clear_chat,
inputs=None,
outputs=chatbot,
api_visibility="public"
)
# Launch the application with Gradio 6 parameters
demo.launch(
theme=chatbot_theme,
css=custom_css,
server_name="0.0.0.0",
server_port=7860,
show_error=True,
quiet=False,
footer_links=[
{"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"},
{"label": "Model: DialoGPT-medium", "url": "https://huggingface.co/microsoft/DialoGPT-medium"},
{"label": "Gradio", "url": "https://gradio.app"},
{"label": "HuggingFace", "url": "https://huggingface.co"}
]
) |