a personalized ai
To upload files, please first save the app
import streamlit as st
import json
from datetime import datetime
from sqlalchemy import create_engine, Column, Integer, String, Text, DateTime
from sqlalchemy.orm import DeclarativeBase, Session
# Database setup
class Base(DeclarativeBase):
pass
class UserProfile(Base):
__tablename__ = 'user_profiles'
id = Column(Integer, primary_key=True)
name = Column(String(100), nullable=False)
preferences = Column(Text) # JSON string
created_at = Column(DateTime, default=datetime.utcnow)
class Conversation(Base):
__tablename__ = 'conversations'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, nullable=False)
message = Column(Text, nullable=False)
response = Column(Text, nullable=False)
timestamp = Column(DateTime, default=datetime.utcnow)
# Create database engine and tables
engine = create_engine("sqlite:///personalized_ai.sqlite")
Base.metadata.create_all(bind=engine)
# AI Response Generator
def generate_personalized_response(message, user_preferences):
"""Generate a personalized AI response based on user preferences"""
# Parse preferences
prefs = json.loads(user_preferences) if user_preferences else {}
communication_style = prefs.get('communication_style', 'friendly')
interests = prefs.get('interests', [])
expertise_level = prefs.get('expertise_level', 'beginner')
# Base response logic
message_lower = message.lower()
# Personalized responses based on communication style
if communication_style == 'professional':
greeting = "I understand your inquiry regarding"
tone = "formal and detailed"
elif communication_style == 'casual':
greeting = "Hey! So you're asking about"
tone = "relaxed and conversational"
else: # friendly
greeting = "Hi there! I'd be happy to help you with"
tone = "warm and approachable"
# Generate response based on message content and preferences
if any(word in message_lower for word in ['hello', 'hi', 'hey']):
if interests:
response = f"Hello! Nice to see you again! I remember you're interested in {', '.join(interests[:2])}. How can I help you today?"
else:
response = "Hello! How can I assist you today?"
elif any(word in message_lower for word in ['recommend', 'suggest', 'advice']):
if interests:
related_interests = [interest for interest in interests if any(word in message_lower for word in interest.lower().split())]
if related_interests:
response = f"Based on your interest in {', '.join(related_interests)}, here are some personalized recommendations..."
else:
response = f"Given your interests in {', '.join(interests[:2])}, I'd suggest exploring related topics..."
else:
response = "I'd be happy to provide recommendations! Could you tell me more about your interests?"
elif any(word in message_lower for word in ['learn', 'understand', 'explain']):
if expertise_level == 'expert':
response = f"{greeting} this topic. I'll provide you with advanced insights and technical details..."
elif expertise_level == 'intermediate':
response = f"{greeting} this. Let me give you a comprehensive explanation with some practical examples..."
else: # beginner
response = f"{greeting} this topic. I'll explain it in simple terms and start with the basics..."
else:
# General response
response = f"{greeting} your question. Let me provide you with a helpful answer in a {tone} manner."
if interests:
response += f" I notice you're interested in {', '.join(interests[:2])}, so I'll try to relate my answer to those areas when possible."
return response
# Streamlit App
st.set_page_config(page_title="Personalized AI Assistant", page_icon="🤖", layout="wide")
st.title("🤖 Personalized AI Assistant")
st.markdown("Your AI that learns and adapts to your preferences!")
# Sidebar for user profile
with st.sidebar:
st.header("👤 Your Profile")
# User selection/creation
with Session(engine) as session:
users = session.query(UserProfile).all()
user_names = [user.name for user in users]
if user_names:
selected_user = st.selectbox("Select User", ["Create New User"] + user_names)
else:
selected_user = "Create New User"
if selected_user == "Create New User":
st.subheader("Create New Profile")
new_name = st.text_input("Your Name")
# Preferences
st.subheader("Preferences")
communication_style = st.selectbox(
"Communication Style",
["friendly", "professional", "casual"],
help="How would you like me to communicate with you?"
)
interests = st.multiselect(
"Your Interests",
["Technology", "Science", "Arts", "Sports", "Music", "Travel", "Cooking", "Books", "Movies", "Health", "Finance", "Education"],
help="What topics are you most interested in?"
)
expertise_level = st.selectbox(
"Your Expertise Level",
["beginner", "intermediate", "expert"],
help="How would you describe your general knowledge level?"
)
if st.button("Create Profile") and new_name:
preferences = {
"communication_style": communication_style,
"interests": interests,
"expertise_level": expertise_level
}
with Session(engine) as session:
new_user = UserProfile(
name=new_name,
preferences=json.dumps(preferences)
)
session.add(new_user)
session.commit()
st.success(f"Profile created for {new_name}!")
st.rerun()
else:
# Load existing user
with Session(engine) as session:
current_user = session.query(UserProfile).filter_by(name=selected_user).first()
if current_user:
st.success(f"Welcome back, {current_user.name}!")
# Show current preferences
prefs = json.loads(current_user.preferences) if current_user.preferences else {}
st.write("**Your Preferences:**")
st.write(f"- Style: {prefs.get('communication_style', 'Not set')}")
st.write(f"- Interests: {', '.join(prefs.get('interests', []))}")
st.write(f"- Level: {prefs.get('expertise_level', 'Not set')}")
# Option to update preferences
if st.button("Update Preferences"):
st.session_state['updating_preferences'] = True
if st.session_state.get('updating_preferences', False):
st.subheader("Update Preferences")
new_style = st.selectbox(
"Communication Style",
["friendly", "professional", "casual"],
index=["friendly", "professional", "casual"].index(prefs.get('communication_style', 'friendly'))
)
new_interests = st.multiselect(
"Your Interests",
["Technology", "Science", "Arts", "Sports", "Music", "Travel", "Cooking", "Books", "Movies", "Health", "Finance", "Education"],
default=prefs.get('interests', [])
)
new_level = st.selectbox(
"Your Expertise Level",
["beginner", "intermediate", "expert"],
index=["beginner", "intermediate", "expert"].index(prefs.get('expertise_level', 'beginner'))
)
if st.button("Save Changes"):
new_preferences = {
"communication_style": new_style,
"interests": new_interests,
"expertise_level": new_level
}
with Session(engine) as session:
user = session.query(UserProfile).filter_by(name=selected_user).first()
user.preferences = json.dumps(new_preferences)
session.commit()
st.success("Preferences updated!")
st.session_state['updating_preferences'] = False
st.rerun()
# Main chat interface
if selected_user and selected_user != "Create New User":
st.header("💬 Chat")
# Initialize chat history
if "messages" not in st.session_state:
st.session_state.messages = []
# Load conversation history
with Session(engine) as session:
user = session.query(UserProfile).filter_by(name=selected_user).first()
if user:
conversations = session.query(Conversation).filter_by(user_id=user.id).order_by(Conversation.timestamp).limit(10).all()
for conv in conversations:
st.session_state.messages.append({"role": "user", "content": conv.message})
st.session_state.messages.append({"role": "assistant", "content": conv.response})
# 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 to chat history
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message
with st.chat_message("user"):
st.markdown(prompt)
# Generate and display assistant response
with st.chat_message("assistant"):
with Session(engine) as session:
user = session.query(UserProfile).filter_by(name=selected_user).first()
response = generate_personalized_response(prompt, user.preferences)
st.markdown(response)
# Save conversation to database
conversation = Conversation(
user_id=user.id,
message=prompt,
response=response
)
session.add(conversation)
session.commit()
# Add assistant response to chat history
st.session_state.messages.append({"role": "assistant", "content": response})
else:
st.info("👈 Please create or select a user profile to start chatting!")
# Show demo features
col1, col2, col3 = st.columns(3)
with col1:
st.subheader("🎯 Personalized Responses")
st.write("The AI adapts its communication style, complexity level, and content based on your preferences.")
with col2:
st.subheader("🧠 Memory & Learning")
st.write("Your conversations are saved and the AI remembers your interests and previous discussions.")
with col3:
st.subheader("⚙️ Customizable")
st.write("Set your communication style, interests, and expertise level to get tailored responses.")
# Footer
st.markdown("---")
st.markdown("Built with ❤️ using Streamlit - Your AI learns from every conversation!")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?