import gradio as gr import random import time from typing import List, Dict, Any # Sample responses for the chatbot RESPONSES = [ "That's an interesting question! Let me think about it...", "I understand what you're saying. Here's my perspective...", "Great point! Have you considered this as well?", "I'm here to help! What would you like to know more about?", "That reminds me of something important I'd like to share...", "Thanks for sharing that with me. Let me provide some insights...", "I appreciate your question. Here's what I think...", "Absolutely! Let me elaborate on that topic...", ] def generate_response(message: str, history: List[Dict[str, str]]) -> str: """Generate a response based on the user message and chat history.""" # Simple logic - in a real app, this would call an AI model time.sleep(0.5) # Simulate thinking time # Check for specific keywords to provide more relevant responses message_lower = message.lower() if "hello" in message_lower or "hi" in message_lower: return "Hello! It's great to chat with you today. How can I assist you?" elif "how are you" in message_lower: return "I'm doing wonderfully, thank you for asking! I'm here and ready to help you with anything you need." elif "bye" in message_lower or "goodbye" in message_lower: return "Goodbye! It was a pleasure chatting with you. Feel free to come back anytime!" elif "help" in message_lower: return "I'm here to help! You can ask me questions, share your thoughts, or just have a friendly conversation. What's on your mind?" elif "thank" in message_lower: return "You're very welcome! I'm always happy to assist. Is there anything else I can help you with?" else: # Return a random response return random.choice(RESPONSES) def user_input(user_message: str, history: List[Dict[str, str]]) -> tuple[str, List[Dict[str, str]]]: """Process user input and add it to the chat history.""" if not user_message.strip(): return "", history # Add user message to history history.append({"role": "user", "content": user_message}) return "", history def bot_response(history: List[Dict[str, str]]) -> List[Dict[str, str]]: """Generate and add bot response to the chat history.""" if not history: return history last_message = history[-1]["content"] bot_message = generate_response(last_message, history) # Add bot message to history history.append({"role": "assistant", "content": bot_message}) return history def stream_response(message: str, history: List[Dict[str, str]]): """Stream the bot response character by character.""" if not history: return last_message = history[-1]["content"] full_response = generate_response(last_message, history) # Add empty bot message to history history.append({"role": "assistant", "content": ""}) # Stream the response for i in range(len(full_response)): history[-1]["content"] = full_response[:i+1] yield history time.sleep(0.02) # Small delay for streaming effect # Example conversations EXAMPLE_CONVERSATIONS = [ ["Hello! How are you today?"], ["Can you help me with something?"], ["What's the weather like?"], ["Tell me an interesting fact"], ["Thank you for your help!"] ] # Custom CSS for better styling CUSTOM_CSS = """ .chat-container { height: 500px; overflow-y: auto; } .message { padding: 10px; margin: 5px; border-radius: 10px; max-width: 80%; } .user-message { background-color: #e3f2fd; margin-left: auto; text-align: right; } .bot-message { background-color: #f3e5f5; } """ with gr.Blocks( title="AI Chatbot Assistant", theme=gr.themes.Soft(), css=CUSTOM_CSS ) as demo: # Header with branding gr.HTML("""

🤖 AI Chatbot Assistant

Your friendly AI companion for engaging conversations

Built with anycoder

""") # Chat interface with gr.Row(): with gr.Column(scale=4): chatbot = gr.Chatbot( label="Conversation", height=500, show_copy_button=True, placeholder="Start a conversation by typing a message below...", avatar_images=( None, # User avatar (default) "https://picsum.photos/seed/ai-avatar/100/100.jpg" # Bot avatar ), type="messages" ) with gr.Row(): msg = gr.Textbox( label="Your Message", placeholder="Type your message here and press Enter...", lines=1, max_lines=5, container=False, scale=4 ) submit_btn = gr.Button( "Send", variant="primary", scale=1, size="sm" ) with gr.Row(): clear_btn = gr.Button( "Clear Conversation", variant="secondary", scale=1, size="sm" ) example_btn = gr.Button( "Random Example", variant="secondary", scale=1, size="sm" ) with gr.Column(scale=1): gr.Markdown("### 💡 Tips") gr.Markdown(""" - Type your message and press Enter or click Send - Use the Clear button to start fresh - Try the Random Example button for conversation starters - Click on messages to copy them """) gr.Markdown("### 📊 Stats") message_count = gr.Number( label="Messages", value=0, interactive=False ) gr.Markdown("### 🎯 Quick Actions") gr.Examples( examples=EXAMPLE_CONVERSATIONS, inputs=msg, label="Example Messages", examples_per_page=5 ) # Event handlers def update_message_count(history: List[Dict[str, str]]) -> int: """Update the message count display.""" return len(history) if history else 0 # Handle user input and generate streaming response msg.submit( user_input, [msg, chatbot], [msg, chatbot], queue=False ).then( stream_response, [msg, chatbot], chatbot ).then( update_message_count, chatbot, message_count ) submit_btn.click( user_input, [msg, chatbot], [msg, chatbot], queue=False ).then( stream_response, [msg, chatbot], chatbot ).then( update_message_count, chatbot, message_count ) # Clear conversation def clear_conversation(): """Clear the chat history and reset message count.""" return [], 0 clear_btn.click( clear_conversation, outputs=[chatbot, message_count] ) # Random example def get_random_example(): """Get a random example message.""" return random.choice(EXAMPLE_CONVERSATIONS)[0] example_btn.click( get_random_example, outputs=msg ) # Welcome message on load demo.load( lambda: [{"role": "assistant", "content": "Hello! I'm your AI chatbot assistant. How can I help you today? 😊"}], outputs=chatbot ).then( update_message_count, chatbot, message_count ) if __name__ == "__main__": demo.launch( share=False, show_error=True, quiet=False, show_tips=True )