Spaces:
Sleeping
Sleeping
File size: 5,922 Bytes
b3f28b2 ca5b1bc b3f28b2 da6fa3c b3f28b2 da6fa3c b3f28b2 da6fa3c b3f28b2 da6fa3c b3f28b2 |
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 |
import gradio as gr
import time
import random
# Default prompt to guide users
DEFAULT_PROMPT = """You are a helpful assistant named [NAME].
Your personality is [PERSONALITY].
You have the following knowledge: [KNOWLEDGE].
You always respond with a [TONE] tone.
"""
# Bot class to maintain state and handle conversations
class ChatBot:
def __init__(self):
self.prompt = DEFAULT_PROMPT
self.messages = []
def update_prompt(self, new_prompt):
self.prompt = new_prompt
self.messages = []
return "System prompt updated! Start a new conversation."
def chat(self, message):
if not message:
return "Please enter a message."
# Add user message to history
self.messages.append({"role": "user", "content": message})
# Generate response based on prompt and previous messages
response = self.generate_response(message)
# Add bot response to history
self.messages.append({"role": "assistant", "content": response})
return response
def generate_response(self, message):
# Simulate thinking
time.sleep(0.5 + random.random())
# Parse prompt to extract personality traits
name = ""
personality = ""
knowledge = ""
tone = ""
if "[NAME]" in self.prompt:
try:
name = self.prompt.split("[NAME]")[1].split(".")[0].strip()
except:
pass
if "[PERSONALITY]" in self.prompt:
try:
personality = self.prompt.split("[PERSONALITY]")[1].split(".")[0].strip()
except:
pass
if "[KNOWLEDGE]" in self.prompt:
try:
knowledge = self.prompt.split("[KNOWLEDGE]")[1].split(".")[0].strip()
except:
pass
if "[TONE]" in self.prompt:
try:
tone = self.prompt.split("[TONE]")[1].split(".")[0].strip()
except:
pass
# Simple response generation logic
greetings = ["hi", "hello", "hey", "greetings", "howdy"]
if any(greeting in message.lower() for greeting in greetings):
return f"Hello! I'm {name}. How can I help you today?"
if "your name" in message.lower():
return f"I'm {name}! Nice to meet you."
if "who are you" in message.lower():
return f"I'm {name}, a {personality} assistant with knowledge about {knowledge}."
if "what do you know" in message.lower():
return f"I have knowledge about {knowledge}."
if "personality" in message.lower():
return f"My personality is {personality}."
# Default response
responses = [
f"As a {personality} assistant named {name}, I'd say that's an interesting point about {message}.",
f"From my knowledge of {knowledge}, I can tell you that your question is thought-provoking.",
f"Let me think about '{message}' from my {personality} perspective.",
f"Based on what I know about {knowledge}, I'd respond to '{message}' with careful consideration.",
f"That's an interesting question! As {name}, I find this topic fascinating."
]
return random.choice(responses)
def get_chat_history(self):
return self.messages
# Initialize bot
bot = ChatBot()
# Define UI components
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("# 🤖 Customizable ChatBot")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("## System Prompt")
prompt_input = gr.Textbox(
value=DEFAULT_PROMPT,
lines=10,
label="Edit the prompt to change the bot's personality",
info="Use [NAME], [PERSONALITY], [KNOWLEDGE], and [TONE] placeholders"
)
update_button = gr.Button("Update Bot Personality")
system_message = gr.Textbox(label="System Message", interactive=False)
gr.Markdown("### Example Prompts")
example_prompts = gr.Examples(
[
["""You are a helpful assistant named Alex.
Your personality is friendly and enthusiastic.
You have the following knowledge: science and technology.
You always respond with a cheerful tone."""],
["""You are a helpful assistant named Professor Oak.
Your personality is scholarly and detail-oriented.
You have the following knowledge: Pokémon research and biology.
You always respond with a professional tone."""],
["""You are a helpful assistant named Chef Remy.
Your personality is passionate and creative.
You have the following knowledge: cooking and fine cuisine.
You always respond with an encouraging tone."""]
],
inputs=[prompt_input]
)
with gr.Column(scale=1):
gr.Markdown("## Chat Interface")
chatbot = gr.Chatbot(height=400, label="Conversation")
msg = gr.Textbox(label="Your Message", placeholder="Type your message here...")
send_button = gr.Button("Send")
clear_button = gr.Button("Clear Conversation")
# Set up event handlers
update_button.click(
bot.update_prompt,
inputs=[prompt_input],
outputs=[system_message]
)
def respond(message, history):
bot_response = bot.chat(message)
history.append((message, bot_response))
return "", history
send_button.click(
respond,
inputs=[msg, chatbot],
outputs=[msg, chatbot]
)
msg.submit(
respond,
inputs=[msg, chatbot],
outputs=[msg, chatbot]
)
clear_button.click(
lambda: ([], "Conversation cleared."),
outputs=[chatbot, system_message]
)
# Launch the app
if __name__ == '__main__':
demo.launch() |