Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,6 @@
|
|
1 |
import streamlit as st
|
2 |
import json
|
3 |
import openai
|
4 |
-
import time
|
5 |
|
6 |
# Initialize Streamlit page configuration
|
7 |
st.set_page_config(
|
@@ -12,10 +11,13 @@ st.set_page_config(
|
|
12 |
|
13 |
# Secret management
|
14 |
def get_openai_api_token():
|
15 |
-
|
16 |
-
|
|
|
|
|
|
|
17 |
|
18 |
-
#
|
19 |
@st.cache_resource
|
20 |
def get_openai_client():
|
21 |
openai.api_key = get_openai_api_token()
|
@@ -27,21 +29,21 @@ def load_knowledge_base():
|
|
27 |
try:
|
28 |
with open('knowledge_base.json', 'r', encoding='utf-8') as f:
|
29 |
return json.load(f)
|
30 |
-
except
|
31 |
-
st.error(
|
32 |
return {}
|
33 |
|
34 |
def get_context(query: str, knowledge_base: dict) -> str:
|
35 |
"""Get relevant context for the query"""
|
36 |
query_lower = query.lower()
|
37 |
contexts = []
|
38 |
-
|
39 |
# Project-related queries
|
40 |
if any(word in query_lower for word in ["project", "build", "develop", "create"]):
|
41 |
if "projects" in knowledge_base:
|
42 |
for name, details in knowledge_base["projects"].items():
|
43 |
contexts.append(f"Project - {name}: {details.get('description', '')}")
|
44 |
-
|
45 |
# Skills and expertise
|
46 |
elif any(word in query_lower for word in ["skill", "know", "experience", "expert"]):
|
47 |
if "skills" in knowledge_base.get("personal_details", {}):
|
@@ -49,26 +51,26 @@ def get_context(query: str, knowledge_base: dict) -> str:
|
|
49 |
f"Skill - {skill}: {desc}"
|
50 |
for skill, desc in knowledge_base["personal_details"]["skills"].items()
|
51 |
])
|
52 |
-
|
53 |
# Role fit and career
|
54 |
elif any(word in query_lower for word in ["role", "fit", "job", "position", "career"]):
|
55 |
contexts.append(knowledge_base.get("professional_journey", {}).get("mindset", ""))
|
56 |
contexts.extend(knowledge_base.get("goals_and_aspirations", {}).get("short_term", []))
|
57 |
-
|
58 |
# Background and journey
|
59 |
elif any(word in query_lower for word in ["background", "journey", "story"]):
|
60 |
faq = knowledge_base.get("frequently_asked_questions", [])
|
61 |
for qa in faq:
|
62 |
if "background" in qa["question"].lower():
|
63 |
contexts.append(qa["answer"])
|
64 |
-
|
65 |
# Default context
|
66 |
if not contexts:
|
67 |
contexts = [
|
68 |
f"I am {knowledge_base.get('personal_details', {}).get('full_name', 'Manyue')}",
|
69 |
knowledge_base.get('personal_details', {}).get('professional_summary', '')
|
70 |
]
|
71 |
-
|
72 |
return "\n".join(contexts)
|
73 |
|
74 |
def generate_openai_prompt(query: str, context: str) -> str:
|
@@ -93,32 +95,23 @@ def get_chat_response(query: str, knowledge_base: dict) -> str:
|
|
93 |
try:
|
94 |
# Get context
|
95 |
context = get_context(query, knowledge_base)
|
96 |
-
|
97 |
# Generate prompt
|
98 |
prompt = generate_openai_prompt(query, context)
|
99 |
-
|
100 |
-
# Generate response
|
101 |
response = openai.ChatCompletion.create(
|
102 |
model="gpt-3.5-turbo",
|
103 |
-
messages=[
|
104 |
-
{"role": "system", "content": "You are Manyue's AI assistant. Answer questions about Manyue."},
|
105 |
-
{"role": "user", "content": query},
|
106 |
-
{"role": "assistant", "content": prompt}
|
107 |
-
],
|
108 |
max_tokens=200,
|
109 |
temperature=0.7
|
110 |
)
|
111 |
-
|
112 |
# Extract and clean response
|
113 |
response_text = response['choices'][0]['message']['content'].strip()
|
114 |
-
|
115 |
return response_text
|
116 |
-
|
117 |
-
except Exception as e:
|
118 |
-
st.error(f"Error generating response: {str(e)}")
|
119 |
-
return "I apologize, but I encountered an error. Please try asking again."
|
120 |
|
121 |
-
|
122 |
except Exception as e:
|
123 |
st.error(f"Error generating response: {str(e)}")
|
124 |
return "I apologize, but I encountered an error. Please try asking again."
|
@@ -132,7 +125,6 @@ def initialize_session_state():
|
|
132 |
|
133 |
def display_chat_interface():
|
134 |
"""Display main chat interface"""
|
135 |
-
# Display chat messages
|
136 |
for message in st.session_state.messages:
|
137 |
with st.chat_message(message["role"]):
|
138 |
st.markdown(message["content"])
|
@@ -140,35 +132,35 @@ def display_chat_interface():
|
|
140 |
def main():
|
141 |
st.title("💬 Chat with Manyue's Portfolio")
|
142 |
st.write("Ask me about my skills, projects, experience, or career goals!")
|
143 |
-
|
144 |
# Initialize session state
|
145 |
initialize_session_state()
|
146 |
-
|
147 |
# Create two columns
|
148 |
col1, col2 = st.columns([3, 1])
|
149 |
-
|
150 |
with col1:
|
151 |
# Display chat interface
|
152 |
display_chat_interface()
|
153 |
-
|
154 |
# Chat input
|
155 |
if prompt := st.chat_input("What would you like to know?"):
|
156 |
# Add user message
|
157 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
158 |
-
|
159 |
# Display user message
|
160 |
with st.chat_message("user"):
|
161 |
st.markdown(prompt)
|
162 |
-
|
163 |
# Generate and display response
|
164 |
with st.chat_message("assistant"):
|
165 |
with st.spinner("Thinking..."):
|
166 |
response = get_chat_response(prompt, st.session_state.knowledge_base)
|
167 |
st.markdown(response)
|
168 |
-
|
169 |
# Add assistant response to history
|
170 |
st.session_state.messages.append({"role": "assistant", "content": response})
|
171 |
-
|
172 |
with col2:
|
173 |
st.subheader("Quick Questions")
|
174 |
example_questions = [
|
@@ -177,16 +169,16 @@ def main():
|
|
177 |
"Why are you suitable for ML roles?",
|
178 |
"What is your educational background?"
|
179 |
]
|
180 |
-
|
181 |
-
for question in
|
182 |
if st.button(question):
|
183 |
st.session_state.messages.append({"role": "user", "content": question})
|
184 |
st.experimental_rerun()
|
185 |
-
|
186 |
st.markdown("---")
|
187 |
if st.button("Clear Chat"):
|
188 |
st.session_state.messages = []
|
189 |
st.experimental_rerun()
|
190 |
|
191 |
if __name__ == "__main__":
|
192 |
-
main()
|
|
|
1 |
import streamlit as st
|
2 |
import json
|
3 |
import openai
|
|
|
4 |
|
5 |
# Initialize Streamlit page configuration
|
6 |
st.set_page_config(
|
|
|
11 |
|
12 |
# Secret management
|
13 |
def get_openai_api_token():
|
14 |
+
try:
|
15 |
+
return st.secrets["OPENAI_API_KEY"]
|
16 |
+
except KeyError:
|
17 |
+
st.error("OpenAI API key not found in secrets.")
|
18 |
+
return None
|
19 |
|
20 |
+
# Load and cache OpenAI client
|
21 |
@st.cache_resource
|
22 |
def get_openai_client():
|
23 |
openai.api_key = get_openai_api_token()
|
|
|
29 |
try:
|
30 |
with open('knowledge_base.json', 'r', encoding='utf-8') as f:
|
31 |
return json.load(f)
|
32 |
+
except FileNotFoundError:
|
33 |
+
st.error("Knowledge base file not found.")
|
34 |
return {}
|
35 |
|
36 |
def get_context(query: str, knowledge_base: dict) -> str:
|
37 |
"""Get relevant context for the query"""
|
38 |
query_lower = query.lower()
|
39 |
contexts = []
|
40 |
+
|
41 |
# Project-related queries
|
42 |
if any(word in query_lower for word in ["project", "build", "develop", "create"]):
|
43 |
if "projects" in knowledge_base:
|
44 |
for name, details in knowledge_base["projects"].items():
|
45 |
contexts.append(f"Project - {name}: {details.get('description', '')}")
|
46 |
+
|
47 |
# Skills and expertise
|
48 |
elif any(word in query_lower for word in ["skill", "know", "experience", "expert"]):
|
49 |
if "skills" in knowledge_base.get("personal_details", {}):
|
|
|
51 |
f"Skill - {skill}: {desc}"
|
52 |
for skill, desc in knowledge_base["personal_details"]["skills"].items()
|
53 |
])
|
54 |
+
|
55 |
# Role fit and career
|
56 |
elif any(word in query_lower for word in ["role", "fit", "job", "position", "career"]):
|
57 |
contexts.append(knowledge_base.get("professional_journey", {}).get("mindset", ""))
|
58 |
contexts.extend(knowledge_base.get("goals_and_aspirations", {}).get("short_term", []))
|
59 |
+
|
60 |
# Background and journey
|
61 |
elif any(word in query_lower for word in ["background", "journey", "story"]):
|
62 |
faq = knowledge_base.get("frequently_asked_questions", [])
|
63 |
for qa in faq:
|
64 |
if "background" in qa["question"].lower():
|
65 |
contexts.append(qa["answer"])
|
66 |
+
|
67 |
# Default context
|
68 |
if not contexts:
|
69 |
contexts = [
|
70 |
f"I am {knowledge_base.get('personal_details', {}).get('full_name', 'Manyue')}",
|
71 |
knowledge_base.get('personal_details', {}).get('professional_summary', '')
|
72 |
]
|
73 |
+
|
74 |
return "\n".join(contexts)
|
75 |
|
76 |
def generate_openai_prompt(query: str, context: str) -> str:
|
|
|
95 |
try:
|
96 |
# Get context
|
97 |
context = get_context(query, knowledge_base)
|
98 |
+
|
99 |
# Generate prompt
|
100 |
prompt = generate_openai_prompt(query, context)
|
101 |
+
|
102 |
+
# Generate response
|
103 |
response = openai.ChatCompletion.create(
|
104 |
model="gpt-3.5-turbo",
|
105 |
+
messages=[{"role": "user", "content": prompt}],
|
|
|
|
|
|
|
|
|
106 |
max_tokens=200,
|
107 |
temperature=0.7
|
108 |
)
|
109 |
+
|
110 |
# Extract and clean response
|
111 |
response_text = response['choices'][0]['message']['content'].strip()
|
112 |
+
|
113 |
return response_text
|
|
|
|
|
|
|
|
|
114 |
|
|
|
115 |
except Exception as e:
|
116 |
st.error(f"Error generating response: {str(e)}")
|
117 |
return "I apologize, but I encountered an error. Please try asking again."
|
|
|
125 |
|
126 |
def display_chat_interface():
|
127 |
"""Display main chat interface"""
|
|
|
128 |
for message in st.session_state.messages:
|
129 |
with st.chat_message(message["role"]):
|
130 |
st.markdown(message["content"])
|
|
|
132 |
def main():
|
133 |
st.title("💬 Chat with Manyue's Portfolio")
|
134 |
st.write("Ask me about my skills, projects, experience, or career goals!")
|
135 |
+
|
136 |
# Initialize session state
|
137 |
initialize_session_state()
|
138 |
+
|
139 |
# Create two columns
|
140 |
col1, col2 = st.columns([3, 1])
|
141 |
+
|
142 |
with col1:
|
143 |
# Display chat interface
|
144 |
display_chat_interface()
|
145 |
+
|
146 |
# Chat input
|
147 |
if prompt := st.chat_input("What would you like to know?"):
|
148 |
# Add user message
|
149 |
st.session_state.messages.append({"role": "user", "content": prompt})
|
150 |
+
|
151 |
# Display user message
|
152 |
with st.chat_message("user"):
|
153 |
st.markdown(prompt)
|
154 |
+
|
155 |
# Generate and display response
|
156 |
with st.chat_message("assistant"):
|
157 |
with st.spinner("Thinking..."):
|
158 |
response = get_chat_response(prompt, st.session_state.knowledge_base)
|
159 |
st.markdown(response)
|
160 |
+
|
161 |
# Add assistant response to history
|
162 |
st.session_state.messages.append({"role": "assistant", "content": response})
|
163 |
+
|
164 |
with col2:
|
165 |
st.subheader("Quick Questions")
|
166 |
example_questions = [
|
|
|
169 |
"Why are you suitable for ML roles?",
|
170 |
"What is your educational background?"
|
171 |
]
|
172 |
+
|
173 |
+
for question in example_questions:
|
174 |
if st.button(question):
|
175 |
st.session_state.messages.append({"role": "user", "content": question})
|
176 |
st.experimental_rerun()
|
177 |
+
|
178 |
st.markdown("---")
|
179 |
if st.button("Clear Chat"):
|
180 |
st.session_state.messages = []
|
181 |
st.experimental_rerun()
|
182 |
|
183 |
if __name__ == "__main__":
|
184 |
+
main()
|