Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -8,16 +8,7 @@ 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 |
# --- Initialize Session State Variables ---
|
@@ -41,12 +32,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()
|
@@ -59,38 +50,37 @@ def analyze_sentiment(user_text):
|
|
59 |
return result['label']
|
60 |
|
61 |
def predict_action(user_text):
|
62 |
-
if "
|
63 |
return "nasa_info"
|
64 |
return "general_query"
|
65 |
|
66 |
def generate_follow_up(user_text):
|
67 |
"""
|
68 |
-
Generates
|
69 |
-
|
70 |
"""
|
71 |
prompt_text = (
|
72 |
-
f"
|
73 |
-
"
|
74 |
-
"and another might be 'Would you like to explore another aspect of quantum physics?' Do not include extra commentary."
|
75 |
)
|
76 |
-
hf = get_llm_hf_inference(max_new_tokens=
|
77 |
output = hf.invoke(input=prompt_text).strip()
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
|
|
83 |
|
84 |
def get_response(system_message, chat_history, user_text, max_new_tokens=256):
|
85 |
"""
|
86 |
-
Generates HAL's
|
87 |
-
|
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,27 +107,21 @@ 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 provide a detailed
|
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 |
-
|
141 |
chat_history.append({'role': 'user', 'content': user_text})
|
142 |
chat_history.append({'role': 'assistant', 'content': response})
|
143 |
|
@@ -160,36 +144,14 @@ if st.sidebar.button("Reset Chat"):
|
|
160 |
st.session_state.follow_up = ""
|
161 |
st.experimental_rerun()
|
162 |
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
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 +165,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 first Streamlit command!
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
st.set_page_config(page_title="HAL - NASA ChatBot", page_icon="🚀")
|
13 |
|
14 |
# --- Initialize Session State Variables ---
|
|
|
32 |
repo_id=model_id,
|
33 |
max_new_tokens=max_new_tokens,
|
34 |
temperature=temperature,
|
35 |
+
token=os.getenv("HF_TOKEN"),
|
36 |
task="text-generation"
|
37 |
)
|
38 |
|
39 |
def get_nasa_apod():
|
40 |
+
url = f"https://api.nasa.gov/planetary/apod?api_key={os.getenv('NASA_API_KEY')}"
|
41 |
response = requests.get(url)
|
42 |
if response.status_code == 200:
|
43 |
data = response.json()
|
|
|
50 |
return result['label']
|
51 |
|
52 |
def predict_action(user_text):
|
53 |
+
if "nasa" in user_text.lower() or "space" in user_text.lower():
|
54 |
return "nasa_info"
|
55 |
return "general_query"
|
56 |
|
57 |
def generate_follow_up(user_text):
|
58 |
"""
|
59 |
+
Generates one concise, friendly follow-up question related to the user's input.
|
60 |
+
The prompt instructs the model to output a single question without extra commentary.
|
61 |
"""
|
62 |
prompt_text = (
|
63 |
+
f"Generate one concise, friendly follow-up question related to the topic of the user's question: '{user_text}'. "
|
64 |
+
"The output should be only the question, with no extra text."
|
|
|
65 |
)
|
66 |
+
hf = get_llm_hf_inference(max_new_tokens=60, temperature=0.9)
|
67 |
output = hf.invoke(input=prompt_text).strip()
|
68 |
+
# If the output is too short or empty, return a default fallback question.
|
69 |
+
if len(output) < 10:
|
70 |
+
return "Would you like to explore this topic further?"
|
71 |
+
# Clean the output from any extraneous quotes.
|
72 |
+
follow_up = output.strip(' "\'')
|
73 |
+
return follow_up
|
74 |
|
75 |
def get_response(system_message, chat_history, user_text, max_new_tokens=256):
|
76 |
"""
|
77 |
+
Generates HAL's response with a detailed explanation and a follow-up question.
|
78 |
+
Style instructions (e.g. "in the voice of a physicist") are appended if present.
|
|
|
79 |
"""
|
80 |
sentiment = analyze_sentiment(user_text)
|
81 |
action = predict_action(user_text)
|
82 |
|
83 |
+
# Extract style instruction if present.
|
84 |
style_instruction = ""
|
85 |
lower_text = user_text.lower()
|
86 |
if "in the voice of" in lower_text or "speaking as" in lower_text:
|
|
|
107 |
|
108 |
style_clause = style_instruction if style_instruction else ""
|
109 |
|
|
|
110 |
prompt = PromptTemplate.from_template(
|
111 |
(
|
112 |
"[INST] {system_message}\n\nCurrent Conversation:\n{chat_history}\n\n"
|
113 |
"User: {user_text}.\n [/INST]\n"
|
114 |
+
"AI: Please provide a detailed, in-depth answer in a friendly, conversational tone. "
|
115 |
+
"Begin with a phrase like 'Certainly!', 'Of course!', or 'Great question!'." + style_clause +
|
|
|
116 |
"\nHAL:"
|
117 |
)
|
118 |
)
|
119 |
|
120 |
chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
|
121 |
response = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=filtered_history))
|
|
|
122 |
response = response.split("HAL:")[-1].strip()
|
|
|
|
|
123 |
if not response:
|
124 |
response = "Certainly, here is an in-depth explanation: [Fallback explanation]."
|
|
|
125 |
chat_history.append({'role': 'user', 'content': user_text})
|
126 |
chat_history.append({'role': 'assistant', 'content': response})
|
127 |
|
|
|
144 |
st.session_state.follow_up = ""
|
145 |
st.experimental_rerun()
|
146 |
|
147 |
+
# Render the chat history.
|
148 |
+
st.markdown("<div class='container'>", unsafe_allow_html=True)
|
149 |
+
for message in st.session_state.chat_history:
|
150 |
+
if message["role"] == "user":
|
151 |
+
st.markdown(f"<div class='user-msg'><strong>You:</strong> {message['content']}</div>", unsafe_allow_html=True)
|
152 |
+
else:
|
153 |
+
st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {message['content']}</div>", unsafe_allow_html=True)
|
154 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
155 |
|
156 |
user_input = st.chat_input("Type your message here...")
|
157 |
|
|
|
165 |
st.image(image_url, caption="NASA Image of the Day")
|
166 |
st.session_state.follow_up = follow_up
|
167 |
st.session_state.response_ready = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|