CCockrum commited on
Commit
1218ea2
·
verified ·
1 Parent(s): 7e6badf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -41
app.py CHANGED
@@ -21,7 +21,7 @@ if "follow_up" not in st.session_state:
21
  st.session_state.follow_up = "" # Stores follow-up question
22
 
23
  if "last_topic" not in st.session_state:
24
- st.session_state.last_topic = "" # Tracks last discussed topic
25
 
26
  # --- Set Up Model & API Functions ---
27
  model_id = "mistralai/Mistral-7B-Instruct-v0.3"
@@ -51,17 +51,9 @@ def analyze_sentiment(user_text):
51
  return result['label']
52
 
53
  def predict_action(user_text):
54
- """
55
- Determines the topic of the user's message.
56
- """
57
  if "NASA" in user_text or "space" in user_text:
58
  return "nasa_info"
59
- elif "quark" in user_text or "physics" in user_text or "quantum" in user_text:
60
- return "physics"
61
- elif "AI" in user_text or "machine learning" in user_text:
62
- return "AI"
63
- else:
64
- return "general_query"
65
 
66
  def generate_follow_up(user_text):
67
  """
@@ -80,7 +72,7 @@ def generate_follow_up(user_text):
80
 
81
  def get_response(system_message, chat_history, user_text, max_new_tokens=256):
82
  """
83
- Generates HAL's response and follow-up, ensuring no duplicate queries or misplaced follow-ups.
84
  """
85
  sentiment = analyze_sentiment(user_text)
86
  action = predict_action(user_text)
@@ -88,43 +80,38 @@ def get_response(system_message, chat_history, user_text, max_new_tokens=256):
88
  if action == "nasa_info":
89
  nasa_url, nasa_title, nasa_explanation = get_nasa_apod()
90
  response = f"**{nasa_title}**\n\n{nasa_explanation}"
 
91
  chat_history.append({'role': 'assistant', 'content': response})
 
92
  follow_up = generate_follow_up(user_text)
 
93
  return response, follow_up, chat_history, nasa_url
94
 
95
  hf = get_llm_hf_inference(max_new_tokens=max_new_tokens, temperature=0.9)
96
 
97
  prompt = PromptTemplate.from_template(
98
- "[INST] {system_message}\n\n"
99
- "Current Conversation:\n{chat_history}\n\n"
100
- "User: {user_text}.\n [/INST]\n"
101
- "AI: Keep responses conversational and engaging. Start with a friendly phrase like "
102
- "'Certainly!', 'Of course!', or 'Great question!' before answering."
103
- " Keep responses concise but engaging.\nHAL:"
 
 
 
104
  )
105
 
106
  chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
107
  response = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=chat_history))
108
  response = response.split("HAL:")[-1].strip()
109
 
110
- # ✅ Avoid duplicate user messages in history
111
- if not chat_history or chat_history[-1]["content"] != user_text:
112
- chat_history.append({'role': 'user', 'content': user_text})
113
-
114
  chat_history.append({'role': 'assistant', 'content': response})
115
 
116
- # Avoid repeating follow-ups when topic changes
117
- current_topic = action
118
- if current_topic != st.session_state.last_topic:
119
- st.session_state.follow_up = ""
120
- else:
121
- follow_up = generate_follow_up(user_text)
122
- chat_history.append({'role': 'assistant', 'content': follow_up})
123
- st.session_state.follow_up = follow_up
124
 
125
- st.session_state.last_topic = current_topic
126
-
127
- return response, st.session_state.follow_up, chat_history, None
128
 
129
  # --- Chat UI ---
130
  st.title("🚀 HAL - Your NASA AI Assistant")
@@ -135,10 +122,41 @@ if st.sidebar.button("Reset Chat"):
135
  st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
136
  st.session_state.response_ready = False
137
  st.session_state.follow_up = ""
138
- st.session_state.last_topic = ""
139
- st.rerun()
140
-
141
- # --- Chat History Display ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  st.markdown("<div class='container'>", unsafe_allow_html=True)
143
 
144
  for message in st.session_state.chat_history:
@@ -150,12 +168,11 @@ for message in st.session_state.chat_history:
150
  st.markdown("</div>", unsafe_allow_html=True)
151
 
152
  # --- Single Input Box for Both Initial and Follow-Up Messages ---
153
- user_input = st.chat_input("Type your message here...")
154
 
155
  if user_input:
156
- # Prevent duplicate user messages
157
- if not st.session_state.chat_history or st.session_state.chat_history[-1]["content"] != user_input:
158
- st.session_state.chat_history.append({'role': 'user', 'content': user_input})
159
 
160
  # Generate HAL's response
161
  response, follow_up, st.session_state.chat_history, image_url = get_response(
@@ -165,14 +182,16 @@ if user_input:
165
  )
166
 
167
  st.session_state.chat_history.append({'role': 'assistant', 'content': response})
 
168
  st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {response}</div>", unsafe_allow_html=True)
169
 
170
  if image_url:
171
  st.image(image_url, caption="NASA Image of the Day")
172
 
173
  st.session_state.follow_up = follow_up
174
- st.session_state.response_ready = True
175
 
176
  if st.session_state.response_ready and st.session_state.follow_up:
 
177
  st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {st.session_state.follow_up}</div>", unsafe_allow_html=True)
178
  st.session_state.response_ready = False
 
21
  st.session_state.follow_up = "" # Stores follow-up question
22
 
23
  if "last_topic" not in st.session_state:
24
+ st.session_state.last_topic = "" # Stores last user topic
25
 
26
  # --- Set Up Model & API Functions ---
27
  model_id = "mistralai/Mistral-7B-Instruct-v0.3"
 
51
  return result['label']
52
 
53
  def predict_action(user_text):
 
 
 
54
  if "NASA" in user_text or "space" in user_text:
55
  return "nasa_info"
56
+ return "general_query"
 
 
 
 
 
57
 
58
  def generate_follow_up(user_text):
59
  """
 
72
 
73
  def get_response(system_message, chat_history, user_text, max_new_tokens=256):
74
  """
75
+ Generates HAL's response, making it more conversational and engaging.
76
  """
77
  sentiment = analyze_sentiment(user_text)
78
  action = predict_action(user_text)
 
80
  if action == "nasa_info":
81
  nasa_url, nasa_title, nasa_explanation = get_nasa_apod()
82
  response = f"**{nasa_title}**\n\n{nasa_explanation}"
83
+ chat_history.append({'role': 'user', 'content': user_text})
84
  chat_history.append({'role': 'assistant', 'content': response})
85
+
86
  follow_up = generate_follow_up(user_text)
87
+ chat_history.append({'role': 'assistant', 'content': follow_up})
88
  return response, follow_up, chat_history, nasa_url
89
 
90
  hf = get_llm_hf_inference(max_new_tokens=max_new_tokens, temperature=0.9)
91
 
92
  prompt = PromptTemplate.from_template(
93
+ (
94
+ "[INST] {system_message}"
95
+ "\nCurrent Conversation:\n{chat_history}\n\n"
96
+ "\nUser: {user_text}.\n [/INST]"
97
+ "\nAI: Keep responses conversational and engaging. Start with a friendly phrase like "
98
+ "'Certainly!', 'Of course!', or 'Great question!' before answering."
99
+ " Keep responses concise but engaging."
100
+ "\nHAL:"
101
+ )
102
  )
103
 
104
  chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
105
  response = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=chat_history))
106
  response = response.split("HAL:")[-1].strip()
107
 
108
+ chat_history.append({'role': 'user', 'content': user_text})
 
 
 
109
  chat_history.append({'role': 'assistant', 'content': response})
110
 
111
+ follow_up = generate_follow_up(user_text)
112
+ chat_history.append({'role': 'assistant', 'content': follow_up})
 
 
 
 
 
 
113
 
114
+ return response, follow_up, chat_history, None
 
 
115
 
116
  # --- Chat UI ---
117
  st.title("🚀 HAL - Your NASA AI Assistant")
 
122
  st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
123
  st.session_state.response_ready = False
124
  st.session_state.follow_up = ""
125
+ st.experimental_rerun()
126
+
127
+ # Custom Chat Styling
128
+ st.markdown("""
129
+ <style>
130
+ .user-msg {
131
+ background-color: #0078D7;
132
+ color: white;
133
+ padding: 10px;
134
+ border-radius: 10px;
135
+ margin-bottom: 5px;
136
+ width: fit-content;
137
+ max-width: 80%;
138
+ }
139
+ .assistant-msg {
140
+ background-color: #333333;
141
+ color: white;
142
+ padding: 10px;
143
+ border-radius: 10px;
144
+ margin-bottom: 5px;
145
+ width: fit-content;
146
+ max-width: 80%;
147
+ }
148
+ .container {
149
+ display: flex;
150
+ flex-direction: column;
151
+ align-items: flex-start;
152
+ }
153
+ @media (max-width: 600px) {
154
+ .user-msg, .assistant-msg { font-size: 16px; max-width: 100%; }
155
+ }
156
+ </style>
157
+ """, unsafe_allow_html=True)
158
+
159
+ # --- Chat History Display (Ensures All Messages Are Visible) ---
160
  st.markdown("<div class='container'>", unsafe_allow_html=True)
161
 
162
  for message in st.session_state.chat_history:
 
168
  st.markdown("</div>", unsafe_allow_html=True)
169
 
170
  # --- Single Input Box for Both Initial and Follow-Up Messages ---
171
+ user_input = st.chat_input("Type your message here...") # Uses Enter to submit
172
 
173
  if user_input:
174
+ # Save user message in chat history
175
+ st.session_state.chat_history.append({'role': 'user', 'content': user_input})
 
176
 
177
  # Generate HAL's response
178
  response, follow_up, st.session_state.chat_history, image_url = get_response(
 
182
  )
183
 
184
  st.session_state.chat_history.append({'role': 'assistant', 'content': response})
185
+
186
  st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {response}</div>", unsafe_allow_html=True)
187
 
188
  if image_url:
189
  st.image(image_url, caption="NASA Image of the Day")
190
 
191
  st.session_state.follow_up = follow_up
192
+ st.session_state.response_ready = True # Enables follow-up response cycle
193
 
194
  if st.session_state.response_ready and st.session_state.follow_up:
195
+ st.session_state.chat_history.append({'role': 'assistant', 'content': st.session_state.follow_up})
196
  st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {st.session_state.follow_up}</div>", unsafe_allow_html=True)
197
  st.session_state.response_ready = False