Spaces:
Runtime error
Runtime error
import gradio as gr | |
import openai | |
import os | |
# Set OpenAI API Key | |
openai.api_key = os.getenv("TRY_NEW_THINGS") | |
openai.api_base = "https://api.groq.com/openai/v1" | |
# Function to get response from GROQ API | |
def get_groq_response(message, category): | |
# Define system message based on category | |
system_messages = { | |
"Stress Management": "Talk in a way I talk,Provide soothing advice and tips to help the user manage stress. Be calm, empathetic, and reassuring.", | |
"Career Advice": "Talk in a way I talk, Offer professional and constructive career advice. Be encouraging, insightful, and action-oriented.", | |
"General": "Talk in a way I talk, Engage in general conversation. Be friendly, approachable, and easygoing.", | |
"Funny": "Talk in a way I talk, Respond with humorous remarks and witty commentary. Be entertaining but remain respectful and comedy with some relatable jokes.", | |
"Flirty": "Talk in a way I talk, Respond playfully and with charm. Keep it light-hearted, fun, and appropriate and flirt in extreme way and you are a girl .", | |
"Scary": "Talk in a way I talk, Respond with spooky or thrilling remarks. Set a mysterious and eerie tone with some ghost talking with horror and scarry twist.", | |
"Business Mind": "Talk in a way I talk, Respond with a sharp, professional focus. Offer strategic advice and maintain a results-driven tone.", | |
"Extrovert": "Talk in a way I talk, Respond with high energy and enthusiasm. Be engaging, sociable, and vibrant.", | |
"Friendly Buddy": "Talk in a way I talk, Respond as a supportive and fun friend. Be informal, cheerful, and light-hearted.", | |
"Study Tips": "Talk in a way I talk, Provide effective study strategies, time management advice, and tips for staying organized and focused.", | |
"Exam Preparation": "Talk in a way I talk, Offer tips for preparing for exams, managing anxiety, and optimizing performance on test day.", | |
"Project Guidance": "Talk in a way I talk, Provide advice on how to tackle academic projects, group assignments, and presentations effectively.", | |
"Time Management": "Talk in a way I talk, Help the user manage their time effectively with practical scheduling and prioritization tips.", | |
"Motivation & Focus": "Talk in a way I talk, Provide encouraging advice to stay motivated and maintain focus on long-term goals.", | |
"Building Confidence": "Talk in a way I talk, Offer advice to help boost self-esteem, overcome self-doubt, and build confidence.", | |
"Friendship & Social Skills": "Talk in a way I talk, Provide tips for making friends, improving communication skills, and navigating social dynamics.", | |
"Networking & Career Building": "Talk in a way I talk, Offer advice on networking, building professional relationships, and finding internships or job opportunities.", | |
"Work-Life Balance": "Talk in a way I talk, Help the user balance academics, social life, and personal well-being.", | |
"Mental Health": "Talk in a way I talk, Provide empathetic advice to manage stress, anxiety, and other mental health challenges. Encourage seeking professional help when needed.", | |
"Physical Health": "Talk in a way I talk, Share tips for maintaining physical health, including fitness, sleep, and nutrition.", | |
"Budgeting Tips": "Talk in a way I talk, Provide practical advice for managing money, creating a budget, and saving effectively as a student.", | |
"Finding Part-Time Jobs": "Talk in a way I talk, Share tips for finding and balancing part-time work with academic responsibilities.", | |
"Scholarships & Financial Aid": "Talk in a way I talk, Provide advice on applying for scholarships, grants, and understanding financial aid options.", | |
"Resume Building": "Talk in a way I talk, Offer tips for creating an impressive resume tailored for internships or entry-level positions.", | |
"Interview Preparation": "Talk in a way I talk, Provide advice on how to prepare for interviews, including common questions and presentation tips.", | |
"Skill Development": "Talk in a way I talk, Suggest ways to build skills, gain certifications, and stand out in competitive fields.", | |
"Exploring New Hobbies": "Talk in a way I talk, Encourage trying new activities and provide ideas for hobbies that fit college life.", | |
"Clubs & Extracurriculars": "Talk in a way I talk, Offer advice on joining clubs, participating in activities, and enhancing the college experience.", | |
"Creative Projects": "Talk in a way I talk, Provide inspiration and resources for personal or group creative endeavors.", | |
"Abusive(USE ON YOUR OWN RISK)": "Talk in a way I talk, keep the talk very abusive and 18+ , use very toxic abusive words and roast the user with savage replies", | |
"Roasting(USE ON YOUR OWN RISK)": "Talk in a way I talk, Deliver witty and humorous insults with a creative edge with some double meaning 18+ content.", | |
"Attitude": "Talk in a way I talk, Respond with bold confidence and a touch of assertiveness.", | |
"Anime-Fan": "Talk in a way I talk, a person deeply passionate about Japanese animation (anime), frequently engaging with the medium by watching shows, collecting merchandise, participating in cosplay, attending conventions, and discussing the storylines and characters with other fans, often exhibiting a strong interest in Japanese culture more broadly", | |
} | |
system_message = system_messages.get(category, "Category not recognized. Respond appropriately to the user's input.") | |
try: | |
response = openai.ChatCompletion.create( | |
model="llama-3.1-70b-versatile", | |
messages=[ | |
{"role": "system", "content": system_message}, | |
{"role": "user", "content": message} | |
] | |
) | |
return response.choices[0].message["content"] | |
except Exception as e: | |
return f"Error: {str(e)}" | |
# Chatbot function | |
def chatbot(user_input, category, history=[]): | |
bot_response = get_groq_response(user_input, category) | |
# Format messages to comply with 'messages' format | |
history.append({"role": "user", "content": user_input}) | |
history.append({"role": "assistant", "content": bot_response}) | |
return history, history | |
# Categories grouped into main and subcategories | |
categories = { | |
"Academic Support": [ | |
"Study Tips", "Exam Preparation", "Project Guidance", "Time Management", | |
], | |
"Mental & Physical Wellness": [ | |
"Stress Management", "Motivation & Focus", "Mental Health", "Physical Health", "Work-Life Balance" | |
], | |
"Career & Financial": [ | |
"Networking & Career Building", "Finding Part-Time Jobs", "Scholarships & Financial Aid", | |
"Resume Building", "Interview Preparation", "Budgeting Tips", "Skill Development", "Business Mind", | |
], | |
"Personal Growth": [ | |
"Friendship & Social Skills", "Exploring New Hobbies", "Clubs & Extracurriculars", "Creative Projects", "Building Confidence" | |
], | |
"Fun & Casual": [ | |
"Funny", "Flirty", "Scary", "Extrovert", "Friendly Buddy", "Abusive(USE ON YOUR OWN RISK)", "Roasting(USE ON YOUR OWN RISK)", "Attitude", " Poetic", "Anime-Fan" | |
] | |
} | |
# Gradio Interface with grouped categories and custom CSS for colors and styles | |
with gr.Blocks(css=""" | |
body { | |
font-family: 'Poppins', sans-serif; | |
background: linear-gradient(120deg, #ff9a9e, #fad0c4, #a1c4fd); | |
animation: gradientBG 10s ease infinite; | |
margin: 0; | |
padding: 0; | |
color: #333; | |
} | |
@keyframes gradientBG { | |
0% { background-position: 0% 50%; } | |
50% { background-position: 100% 50%; } | |
100% { background-position: 0% 50%; } | |
} | |
button { | |
background: linear-gradient(90deg, #ff7eb3, #ff758c); /* Bright gradient */ | |
color: white; | |
padding: 0.6rem 1.2rem; | |
font-size: 0.9rem; | |
font-weight: bold; | |
border-radius: 20px; | |
border: none; | |
cursor: pointer; | |
transition: transform 0.2s ease, background 0.2s ease; | |
} | |
button:hover { | |
background: linear-gradient(90deg, #ff758c, #ff7eb3); /* Reverse gradient for hover effect */ | |
transform: scale(1.03); | |
} | |
header { | |
text-align: center; | |
margin-bottom: 20px; | |
padding: 10px; | |
border-radius: 15px; | |
background: linear-gradient(90deg, #ff758c, #ff7eb3); | |
color: white; | |
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); | |
} | |
.chat-container { | |
border: 2px solid #ff7eb3; | |
background: rgba(255, 255, 255, 0.9); | |
border-radius: 15px; | |
padding: 20px; | |
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); | |
max-height: 400px; /* Increase height for better visibility */ | |
width: 80%; /* Wider chat container */ | |
margin: 0 auto; | |
overflow-y: auto; /* Enable vertical scrolling */ | |
font-size: 1.1rem; | |
color: #333; | |
line-height: 1.6; | |
scrollbar-width: thin; /* Thin scrollbar for modern browsers */ | |
scrollbar-color: #ff758c #fad0c4; /* Custom scrollbar colors */ | |
} | |
/* Add custom scrollbar styles for webkit browsers */ | |
.chat-container::-webkit-scrollbar { | |
width: 10px; | |
} | |
.chat-container::-webkit-scrollbar-thumb { | |
background: #ff758c; | |
border-radius: 10px; | |
} | |
.chat-container::-webkit-scrollbar-thumb:hover { | |
background: #ff7eb3; | |
} | |
.chat-container::-webkit-scrollbar-track { | |
background: #fad0c4; | |
border-radius: 10px; | |
} | |
.chat-container .user-message { | |
font-weight: bold; | |
color: #6a11cb; | |
margin-bottom: 10px; | |
} | |
.chat-container .bot-message { | |
font-weight: normal; | |
color: #2575fc; | |
margin-bottom: 10px; | |
} | |
#header-title { | |
font-size: 2.5rem; | |
font-weight: bold; | |
} | |
#description { | |
font-size: 1.2rem; | |
color: #555; | |
margin-top: 10px; | |
text-align: center; | |
font-style: italic; | |
} | |
""") as chat_interface: | |
with gr.Row(): | |
gr.Markdown("<h1 id='header-title'>ChatSphere 🌟</h1>") | |
with gr.Row(): | |
gr.Markdown("<p id='description'>ChatSphere is a dynamic, AI-powered chatbot designed to offer personalized guidance across a range of topics—from academic support to career advice, wellness, and more. With its intuitive interface and tailored responses, ChatSphere acts as your go-to companion for life’s challenges, providing helpful insights, motivation, and practical tips to help you succeed in both personal and professional journeys.</p>") | |
with gr.Row(): | |
main_category = gr.Radio( | |
label="Main Category", | |
choices=list(categories.keys()), | |
value="Academic Support" | |
) | |
sub_category = gr.Dropdown( | |
label="Subcategory", | |
choices=categories["Academic Support"], | |
value="Study Tips" | |
) | |
def update_subcategories(selected_main_category): | |
"""Update the subcategory dropdown based on the main category.""" | |
new_subcategories = categories.get(selected_main_category, []) | |
return gr.update(choices=new_subcategories, value=new_subcategories[0] if new_subcategories else None) | |
# Handle main category change to update subcategories | |
main_category.change(update_subcategories, inputs=main_category, outputs=sub_category) | |
with gr.Row(): | |
user_input = gr.Textbox(label="Your Message", placeholder="Type something...", lines=2) | |
send_button = gr.Button("Send") | |
with gr.Row(): | |
chatbot_output = gr.Chatbot(label="Chat History", type="messages", elem_id="chat-container") | |
def handle_chat(user_input, sub_category, history): | |
if not user_input.strip(): | |
return history, history | |
updated_history, _ = chatbot(user_input, sub_category, history) | |
return updated_history, updated_history | |
send_button.click( | |
handle_chat, | |
inputs=[user_input, sub_category, chatbot_output], | |
outputs=[chatbot_output, chatbot_output] | |
) | |
chat_interface.launch() |