Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -8,25 +8,20 @@ from langchain_core.prompts import PromptTemplate
|
|
8 |
from langchain_core.output_parsers import StrOutputParser
|
9 |
from transformers import pipeline
|
10 |
|
11 |
-
#
|
12 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
13 |
-
if HF_TOKEN is None:
|
14 |
-
raise ValueError("HF_TOKEN environment variable not set. Please set it in your Hugging Face Space settings.")
|
15 |
-
|
16 |
-
NASA_API_KEY = os.getenv("NASA_API_KEY")
|
17 |
-
if NASA_API_KEY is None:
|
18 |
-
raise ValueError("NASA_API_KEY environment variable not set. Please set it in your Hugging Face Space settings.")
|
19 |
-
|
20 |
-
# Set up Streamlit UI
|
21 |
st.set_page_config(page_title="HAL - NASA ChatBot", page_icon="π")
|
22 |
|
23 |
-
#
|
|
|
|
|
24 |
if "chat_history" not in st.session_state:
|
25 |
st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
|
26 |
if "response_ready" not in st.session_state:
|
27 |
st.session_state.response_ready = False
|
28 |
if "follow_up" not in st.session_state:
|
29 |
st.session_state.follow_up = ""
|
|
|
|
|
30 |
|
31 |
# --- Set Up Model & API Functions ---
|
32 |
model_id = "mistralai/Mistral-7B-Instruct-v0.3"
|
@@ -41,12 +36,12 @@ def get_llm_hf_inference(model_id=model_id, max_new_tokens=128, temperature=0.7)
|
|
41 |
repo_id=model_id,
|
42 |
max_new_tokens=max_new_tokens,
|
43 |
temperature=temperature,
|
44 |
-
token=HF_TOKEN,
|
45 |
task="text-generation"
|
46 |
)
|
47 |
|
48 |
def get_nasa_apod():
|
49 |
-
url = f"https://api.nasa.gov/planetary/apod?api_key={NASA_API_KEY}"
|
50 |
response = requests.get(url)
|
51 |
if response.status_code == 200:
|
52 |
data = response.json()
|
@@ -64,14 +59,11 @@ def predict_action(user_text):
|
|
64 |
return "general_query"
|
65 |
|
66 |
def generate_follow_up(user_text):
|
67 |
-
"""
|
68 |
-
Generates two variant follow-up questions and randomly selects one.
|
69 |
-
It also cleans up any unwanted quotation marks or extra meta commentary.
|
70 |
-
"""
|
71 |
prompt_text = (
|
72 |
f"Based on the user's question: '{user_text}', generate two concise, friendly follow-up questions "
|
73 |
-
"that invite further discussion. For example, one might
|
74 |
-
"
|
|
|
75 |
)
|
76 |
hf = get_llm_hf_inference(max_new_tokens=80, temperature=0.9)
|
77 |
output = hf.invoke(input=prompt_text).strip()
|
@@ -82,15 +74,8 @@ def generate_follow_up(user_text):
|
|
82 |
return random.choice(cleaned)
|
83 |
|
84 |
def get_response(system_message, chat_history, user_text, max_new_tokens=256):
|
85 |
-
"""
|
86 |
-
Generates HAL's answer with depth and a follow-up question.
|
87 |
-
The prompt instructs the model to provide a detailed explanation and then generate a follow-up.
|
88 |
-
If the answer comes back empty, a fallback answer is used.
|
89 |
-
"""
|
90 |
sentiment = analyze_sentiment(user_text)
|
91 |
action = predict_action(user_text)
|
92 |
-
|
93 |
-
# Extract style instruction if present
|
94 |
style_instruction = ""
|
95 |
lower_text = user_text.lower()
|
96 |
if "in the voice of" in lower_text or "speaking as" in lower_text:
|
@@ -117,24 +102,20 @@ def get_response(system_message, chat_history, user_text, max_new_tokens=256):
|
|
117 |
|
118 |
style_clause = style_instruction if style_instruction else ""
|
119 |
|
120 |
-
# Instruct the model to generate a detailed, in-depth answer.
|
121 |
prompt = PromptTemplate.from_template(
|
122 |
(
|
123 |
"[INST] {system_message}\n\nCurrent Conversation:\n{chat_history}\n\n"
|
124 |
"User: {user_text}.\n [/INST]\n"
|
125 |
-
"AI: Please
|
126 |
-
"
|
127 |
-
"starting with a phrase like 'Certainly!', 'Of course!', or 'Great question!'." + style_clause +
|
128 |
"\nHAL:"
|
129 |
)
|
130 |
)
|
131 |
|
132 |
chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
|
133 |
response = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=filtered_history))
|
134 |
-
# Remove any extra markers if present.
|
135 |
response = response.split("HAL:")[-1].strip()
|
136 |
|
137 |
-
# Fallback in case the generated answer is empty
|
138 |
if not response:
|
139 |
response = "Certainly, here is an in-depth explanation: [Fallback explanation]."
|
140 |
|
@@ -150,7 +131,22 @@ def get_response(system_message, chat_history, user_text, max_new_tokens=256):
|
|
150 |
|
151 |
return response, follow_up, chat_history, None
|
152 |
|
153 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
154 |
st.title("π HAL - Your NASA AI Assistant")
|
155 |
st.markdown("π *Ask me about space, NASA, and beyond!*")
|
156 |
|
@@ -160,36 +156,13 @@ if st.sidebar.button("Reset Chat"):
|
|
160 |
st.session_state.follow_up = ""
|
161 |
st.experimental_rerun()
|
162 |
|
163 |
-
st.markdown(""
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
margin-bottom: 5px;
|
171 |
-
width: fit-content;
|
172 |
-
max-width: 80%;
|
173 |
-
}
|
174 |
-
.assistant-msg {
|
175 |
-
background-color: #333333;
|
176 |
-
color: white;
|
177 |
-
padding: 10px;
|
178 |
-
border-radius: 10px;
|
179 |
-
margin-bottom: 5px;
|
180 |
-
width: fit-content;
|
181 |
-
max-width: 80%;
|
182 |
-
}
|
183 |
-
.container {
|
184 |
-
display: flex;
|
185 |
-
flex-direction: column;
|
186 |
-
align-items: flex-start;
|
187 |
-
}
|
188 |
-
@media (max-width: 600px) {
|
189 |
-
.user-msg, .assistant-msg { font-size: 16px; max-width: 100%; }
|
190 |
-
}
|
191 |
-
</style>
|
192 |
-
""", unsafe_allow_html=True)
|
193 |
|
194 |
user_input = st.chat_input("Type your message here...")
|
195 |
|
@@ -203,11 +176,3 @@ if user_input:
|
|
203 |
st.image(image_url, caption="NASA Image of the Day")
|
204 |
st.session_state.follow_up = follow_up
|
205 |
st.session_state.response_ready = True
|
206 |
-
|
207 |
-
st.markdown("<div class='container'>", unsafe_allow_html=True)
|
208 |
-
for message in st.session_state.chat_history:
|
209 |
-
if message["role"] == "user":
|
210 |
-
st.markdown(f"<div class='user-msg'><strong>You:</strong> {message['content']}</div>", unsafe_allow_html=True)
|
211 |
-
else:
|
212 |
-
st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {message['content']}</div>", unsafe_allow_html=True)
|
213 |
-
st.markdown("</div>", unsafe_allow_html=True)
|
|
|
8 |
from langchain_core.output_parsers import StrOutputParser
|
9 |
from transformers import pipeline
|
10 |
|
11 |
+
# Must be the very first command!
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
st.set_page_config(page_title="HAL - NASA ChatBot", page_icon="π")
|
13 |
|
14 |
+
# Appearance adjustments (if any) could be added here as well
|
15 |
+
|
16 |
+
# Initialize session state variables
|
17 |
if "chat_history" not in st.session_state:
|
18 |
st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
|
19 |
if "response_ready" not in st.session_state:
|
20 |
st.session_state.response_ready = False
|
21 |
if "follow_up" not in st.session_state:
|
22 |
st.session_state.follow_up = ""
|
23 |
+
if "saved_conversations" not in st.session_state:
|
24 |
+
st.session_state.saved_conversations = {} # Dictionary: conv_id -> chat_history
|
25 |
|
26 |
# --- Set Up Model & API Functions ---
|
27 |
model_id = "mistralai/Mistral-7B-Instruct-v0.3"
|
|
|
36 |
repo_id=model_id,
|
37 |
max_new_tokens=max_new_tokens,
|
38 |
temperature=temperature,
|
39 |
+
token=os.getenv("HF_TOKEN"),
|
40 |
task="text-generation"
|
41 |
)
|
42 |
|
43 |
def get_nasa_apod():
|
44 |
+
url = f"https://api.nasa.gov/planetary/apod?api_key={os.getenv('NASA_API_KEY')}"
|
45 |
response = requests.get(url)
|
46 |
if response.status_code == 200:
|
47 |
data = response.json()
|
|
|
59 |
return "general_query"
|
60 |
|
61 |
def generate_follow_up(user_text):
|
|
|
|
|
|
|
|
|
62 |
prompt_text = (
|
63 |
f"Based on the user's question: '{user_text}', generate two concise, friendly follow-up questions "
|
64 |
+
"that invite further discussion. For example, one variant might ask, "
|
65 |
+
"'Would you like to know more about the six types of quarks?' and another might ask, "
|
66 |
+
"'Would you like to explore another aspect of quantum physics?'. Do not include extra commentary."
|
67 |
)
|
68 |
hf = get_llm_hf_inference(max_new_tokens=80, temperature=0.9)
|
69 |
output = hf.invoke(input=prompt_text).strip()
|
|
|
74 |
return random.choice(cleaned)
|
75 |
|
76 |
def get_response(system_message, chat_history, user_text, max_new_tokens=256):
|
|
|
|
|
|
|
|
|
|
|
77 |
sentiment = analyze_sentiment(user_text)
|
78 |
action = predict_action(user_text)
|
|
|
|
|
79 |
style_instruction = ""
|
80 |
lower_text = user_text.lower()
|
81 |
if "in the voice of" in lower_text or "speaking as" in lower_text:
|
|
|
102 |
|
103 |
style_clause = style_instruction if style_instruction else ""
|
104 |
|
|
|
105 |
prompt = PromptTemplate.from_template(
|
106 |
(
|
107 |
"[INST] {system_message}\n\nCurrent Conversation:\n{chat_history}\n\n"
|
108 |
"User: {user_text}.\n [/INST]\n"
|
109 |
+
"AI: Please answer the user's question in depth in a friendly, conversational tone, starting with a phrase like "
|
110 |
+
"'Certainly!', 'Of course!', or 'Great question!'." + style_clause +
|
|
|
111 |
"\nHAL:"
|
112 |
)
|
113 |
)
|
114 |
|
115 |
chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
|
116 |
response = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=filtered_history))
|
|
|
117 |
response = response.split("HAL:")[-1].strip()
|
118 |
|
|
|
119 |
if not response:
|
120 |
response = "Certainly, here is an in-depth explanation: [Fallback explanation]."
|
121 |
|
|
|
131 |
|
132 |
return response, follow_up, chat_history, None
|
133 |
|
134 |
+
# --- Sidebar: Saved Conversations ---
|
135 |
+
st.sidebar.header("Saved Conversations")
|
136 |
+
if st.sidebar.button("Save Current Conversation"):
|
137 |
+
conv_id = f"Conv {len(st.session_state.saved_conversations) + 1}"
|
138 |
+
# Save a copy of the current conversation history
|
139 |
+
st.session_state.saved_conversations[conv_id] = st.session_state.chat_history.copy()
|
140 |
+
st.sidebar.success(f"Conversation saved as {conv_id}.")
|
141 |
+
|
142 |
+
# Display saved conversation links
|
143 |
+
if st.session_state.saved_conversations:
|
144 |
+
for conv_id in st.session_state.saved_conversations:
|
145 |
+
if st.sidebar.button(f"Load {conv_id}"):
|
146 |
+
st.session_state.chat_history = st.session_state.saved_conversations[conv_id].copy()
|
147 |
+
st.sidebar.info(f"Loaded {conv_id}.")
|
148 |
+
|
149 |
+
# --- Chat UI Rendering ---
|
150 |
st.title("π HAL - Your NASA AI Assistant")
|
151 |
st.markdown("π *Ask me about space, NASA, and beyond!*")
|
152 |
|
|
|
156 |
st.session_state.follow_up = ""
|
157 |
st.experimental_rerun()
|
158 |
|
159 |
+
st.markdown("<div class='container'>", unsafe_allow_html=True)
|
160 |
+
for message in st.session_state.chat_history:
|
161 |
+
if message["role"] == "user":
|
162 |
+
st.markdown(f"<div class='user-msg'><strong>You:</strong> {message['content']}</div>", unsafe_allow_html=True)
|
163 |
+
else:
|
164 |
+
st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {message['content']}</div>", unsafe_allow_html=True)
|
165 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
166 |
|
167 |
user_input = st.chat_input("Type your message here...")
|
168 |
|
|
|
176 |
st.image(image_url, caption="NASA Image of the Day")
|
177 |
st.session_state.follow_up = follow_up
|
178 |
st.session_state.response_ready = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|