a personalized ai
To upload files, please first save the app
import streamlit as st
import json
import time
# Initialize session state
if 'messages' not in st.session_state:
st.session_state.messages = []
if 'user_profile' not in st.session_state:
st.session_state.user_profile = {
'name': '',
'interests': [],
'communication_style': 'friendly',
'expertise_level': 'beginner'
}
if 'profile_setup' not in st.session_state:
st.session_state.profile_setup = False
st.set_page_config(page_title="Personalized AI Assistant", page_icon="🤖")
st.title("🤖 Personalized AI Assistant")
# Sidebar for user profile
with st.sidebar:
st.header("👤 Your Profile")
if not st.session_state.profile_setup:
st.write("Let's set up your profile for a personalized experience!")
name = st.text_input("What's your name?", value=st.session_state.user_profile['name'])
interests = st.multiselect(
"What are your interests?",
["Technology", "Science", "Art", "Music", "Sports", "Cooking", "Travel",
"Books", "Movies", "Gaming", "Health", "Business", "Education"],
default=st.session_state.user_profile['interests']
)
communication_style = st.selectbox(
"How would you like me to communicate?",
["friendly", "professional", "casual", "formal", "enthusiastic"],
index=["friendly", "professional", "casual", "formal", "enthusiastic"].index(
st.session_state.user_profile['communication_style']
)
)
expertise_level = st.selectbox(
"What's your general expertise level?",
["beginner", "intermediate", "advanced", "expert"],
index=["beginner", "intermediate", "advanced", "expert"].index(
st.session_state.user_profile['expertise_level']
)
)
if st.button("Save Profile"):
st.session_state.user_profile = {
'name': name,
'interests': interests,
'communication_style': communication_style,
'expertise_level': expertise_level
}
st.session_state.profile_setup = True
st.rerun()
else:
# Display current profile
st.write(f"**Name:** {st.session_state.user_profile['name']}")
st.write(f"**Interests:** {', '.join(st.session_state.user_profile['interests'])}")
st.write(f"**Style:** {st.session_state.user_profile['communication_style']}")
st.write(f"**Level:** {st.session_state.user_profile['expertise_level']}")
if st.button("Edit Profile"):
st.session_state.profile_setup = False
st.rerun()
st.divider()
# Quick actions based on interests
st.subheader("💡 Suggested Topics")
for interest in st.session_state.user_profile['interests'][:3]:
if st.button(f"Tell me about {interest}"):
st.session_state.messages.append({
"role": "user",
"content": f"Tell me something interesting about {interest}"
})
st.rerun()
# Main chat interface
if st.session_state.profile_setup:
# Display chat messages
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input
if prompt := st.chat_input("What would you like to know?"):
# Add user message
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
# Generate AI response
with st.chat_message("assistant"):
# Create personalized context
profile = st.session_state.user_profile
context = f"""
You are a personalized AI assistant. Here's what you know about the user:
- Name: {profile['name']}
- Interests: {', '.join(profile['interests'])}
- Communication style preference: {profile['communication_style']}
- Expertise level: {profile['expertise_level']}
Please respond in a {profile['communication_style']} manner, tailored to their {profile['expertise_level']} level.
If relevant, connect your response to their interests: {', '.join(profile['interests'])}.
"""
# Simulate AI response generation
response = generate_personalized_response(prompt, context, profile)
# Stream the response
def response_generator():
for word in response.split():
yield word + " "
time.sleep(0.02)
full_response = st.write_stream(response_generator())
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": full_response})
else:
st.info("👈 Please set up your profile in the sidebar to get started!")
# Clear chat button
if st.session_state.messages:
if st.button("🗑️ Clear Chat"):
st.session_state.messages = []
st.rerun()
def generate_personalized_response(prompt, context, profile):
"""Generate a personalized response based on user profile"""
# Sample responses based on different communication styles and topics
name = profile['name'] if profile['name'] else "there"
# Simple keyword matching for demo purposes
prompt_lower = prompt.lower()
# Technology responses
if any(word in prompt_lower for word in ['technology', 'tech', 'ai', 'computer', 'programming']):
if profile['communication_style'] == 'enthusiastic':
return f"Hey {name}! 🚀 Technology is absolutely fascinating! Since you're interested in {', '.join(profile['interests'])}, you'll love how tech intersects with these areas. For someone at the {profile['expertise_level']} level, I'd recommend starting with the basics and building up. What specific aspect interests you most?"
elif profile['communication_style'] == 'professional':
return f"Hello {name}. Technology is a broad field with many applications. Given your {profile['expertise_level']} background and interest in {', '.join(profile['interests'])}, I can provide tailored insights. Which particular technology domain would you like to explore?"
else:
return f"Hi {name}! Tech is pretty cool stuff. Since you're into {', '.join(profile['interests'])}, there's probably some overlap there. What kind of tech stuff are you curious about?"
# Science responses
elif any(word in prompt_lower for word in ['science', 'research', 'discovery', 'experiment']):
if profile['expertise_level'] == 'beginner':
return f"Great question, {name}! Science is all about understanding how things work. Since you're just starting out, I'll explain things in simple terms. Your interest in {', '.join(profile['interests'])} actually connects to science in many ways!"
else:
return f"Excellent inquiry, {name}. Given your {profile['expertise_level']} level understanding, we can dive deeper into the scientific principles. How does this relate to your interests in {', '.join(profile['interests'])}?"
# General greeting
elif any(word in prompt_lower for word in ['hello', 'hi', 'hey', 'greetings']):
return f"Hello {name}! Great to chat with you. I see you're interested in {', '.join(profile['interests'])}. How can I help you today?"
# Default personalized response
else:
interests_text = f" Since you're into {', '.join(profile['interests'])}, " if profile['interests'] else " "
style_response = {
'friendly': f"That's a great question, {name}!{interests_text}I'd be happy to help explain this in a way that makes sense for your {profile['expertise_level']} level.",
'professional': f"Thank you for your inquiry, {name}.{interests_text}I'll provide a comprehensive response appropriate for your {profile['expertise_level']} background.",
'casual': f"Hey {name}!{interests_text}Let me break this down for you in a simple way.",
'formal': f"Good day, {name}.{interests_text}I shall endeavor to provide you with a thorough explanation suitable for your {profile['expertise_level']} level of understanding.",
'enthusiastic': f"Awesome question, {name}! 🎉{interests_text}This is going to be fun to explore together!"
}
return style_response.get(profile['communication_style'], style_response['friendly']) + f" Could you tell me more specifically what you'd like to know about '{prompt}'?"
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?