gnvnsk / app.py
KaiShin1885's picture
Update app.py
da6fa3c verified
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()