1# app.py
2import streamlit as st
3from openai import OpenAI
4
5st.title("🤖 Personal AI Assistant")
6
7# Initialize OpenAI
8client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
9
10# Session state for conversation history
11if "messages" not in st.session_state:
12 st.session_state.messages = []
13
14# System prompt selector
15system_role = st.sidebar.selectbox(
16 "Choose AI Role:",
17 ["General Assistant", "Code Expert", "Writing Coach", "Data Analyst"]
18)
19
20system_prompts = {
21 "General Assistant": "You are a helpful AI assistant.",
22 "Code Expert": "You are an expert programmer. Provide clean, efficient code with explanations.",
23 "Writing Coach": "You are a professional writing coach. Help improve writing clarity and style.",
24 "Data Analyst": "You are a data analyst. Provide insights and data-driven recommendations."
25}
26
27# Display chat messages
28for message in st.session_state.messages:
29 with st.chat_message(message["role"]):
30 st.markdown(message["content"])
31
32# Chat input
33if prompt := st.chat_input("What would you like to know?"):
34 # Add user message
35 st.session_state.messages.append({"role": "user", "content": prompt})
36 with st.chat_message("user"):
37 st.markdown(prompt)
38
39 # Get AI response
40 with st.chat_message("assistant"):
41 messages = [
42 {"role": "system", "content": system_prompts[system_role]},
43 *st.session_state.messages
44 ]
45
46 stream = client.chat.completions.create(
47 model="gpt-4-turbo-preview",
48 messages=messages,
49 stream=True
50 )
51
52 response = st.write_stream(stream)
53
54 st.session_state.messages.append({"role": "assistant", "content": response})
55
56# Sidebar controls
57if st.sidebar.button("Clear Conversation"):
58 st.session_state.messages = []
59 st.rerun()
60
61# Export conversation
62if st.sidebar.button("Export Chat"):
63 chat_export = {
64 "timestamp": datetime.now().isoformat(),
65 "role": system_role,
66 "messages": st.session_state.messages
67 }
68 st.sidebar.download_button(
69 "Download JSON",
70 data=json.dumps(chat_export, indent=2),
71 file_name=f"chat_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
72 )