Encourage-AI / app.py
arpit13's picture
Update app.py
060bcff verified
raw
history blame
7.28 kB
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": "Provide soothing advice and tips to help the user manage stress. Be calm, empathetic, and reassuring.",
"Career Advice": "Offer professional and constructive career advice. Be encouraging, insightful, and action-oriented.",
"General": "Engage in general conversation. Be friendly, approachable, and easygoing.",
"Funny": "Respond with humorous remarks and witty commentary. Be entertaining but remain respectful.",
"Flirty": "Respond playfully and with charm. Keep it light-hearted, fun, and appropriate.",
"Scary": "Respond with spooky or thrilling remarks. Set a mysterious and eerie tone.",
"Business Mind": "Respond with a sharp, professional focus. Offer strategic advice and maintain a results-driven tone.",
"Extrovert": "Respond with high energy and enthusiasm. Be engaging, sociable, and vibrant.",
"Friendly Buddy": "Respond as a supportive and fun friend. Be informal, cheerful, and light-hearted.",
"Study Tips": "Provide effective study strategies, time management advice, and tips for staying organized and focused.",
"Exam Preparation": "Offer tips for preparing for exams, managing anxiety, and optimizing performance on test day.",
"Project Guidance": "Provide advice on how to tackle academic projects, group assignments, and presentations effectively.",
"Time Management": "Help the user manage their time effectively with practical scheduling and prioritization tips.",
"Motivation & Focus": "Provide encouraging advice to stay motivated and maintain focus on long-term goals.",
"Building Confidence": "Offer advice to help boost self-esteem, overcome self-doubt, and build confidence.",
"Friendship & Social Skills": "Provide tips for making friends, improving communication skills, and navigating social dynamics.",
"Networking & Career Building": "Offer advice on networking, building professional relationships, and finding internships or job opportunities.",
"Work-Life Balance": "Help the user balance academics, social life, and personal well-being.",
"Mental Health": "Provide empathetic advice to manage stress, anxiety, and other mental health challenges. Encourage seeking professional help when needed.",
"Physical Health": "Share tips for maintaining physical health, including fitness, sleep, and nutrition.",
"Budgeting Tips": "Provide practical advice for managing money, creating a budget, and saving effectively as a student.",
"Finding Part-Time Jobs": "Share tips for finding and balancing part-time work with academic responsibilities.",
"Scholarships & Financial Aid": "Provide advice on applying for scholarships, grants, and understanding financial aid options.",
"Resume Building": "Offer tips for creating an impressive resume tailored for internships or entry-level positions.",
"Interview Preparation": "Provide advice on how to prepare for interviews, including common questions and presentation tips.",
"Skill Development": "Suggest ways to build skills, gain certifications, and stand out in competitive fields.",
"Exploring New Hobbies": "Encourage trying new activities and provide ideas for hobbies that fit college life.",
"Clubs & Extracurriculars": "Offer advice on joining clubs, participating in activities, and enhancing the college experience.",
"Creative Projects": "Provide inspiration and resources for personal or group creative endeavors.",
}
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)
history.append((f"You: {user_input}", f"Bot: {bot_response}"))
return history, history
# Categories grouped into main and subcategories
categories = {
"Academic Support": [
"Study Tips", "Exam Preparation", "Project Guidance", "Time Management", "Building Confidence"
],
"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"
],
"Social & Personal Growth": [
"Friendship & Social Skills", "Exploring New Hobbies", "Clubs & Extracurriculars", "Creative Projects"
],
"Fun & Miscellaneous": [
"Funny", "Flirty", "Scary", "Business Mind", "Extrovert", "Friendly Buddy"
]
}
# Gradio Interface with grouped categories
with gr.Blocks() as chat_interface:
with gr.Row():
gr.Markdown("<h1 style='text-align:center;'>🌟 Vibrant Personal Assistant Chatbot 🌈</h1>")
with gr.Row():
gr.Markdown("<p style='text-align:center;'>Select a category and type your message to get tailored responses.</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")
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()