Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,51 +1,83 @@
|
|
1 |
import os
|
2 |
-
|
3 |
import streamlit as st
|
|
|
4 |
from langchain_core.prompts import PromptTemplate
|
5 |
from langchain_core.output_parsers import StrOutputParser
|
6 |
-
import
|
7 |
-
from config import NASA_API_KEY #
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
model_id = "mistralai/Mistral-7B-Instruct-v0.3"
|
10 |
|
|
|
|
|
|
|
11 |
def get_llm_hf_inference(model_id=model_id, max_new_tokens=128, temperature=0.1):
|
12 |
-
|
13 |
repo_id=model_id,
|
14 |
max_new_tokens=max_new_tokens,
|
15 |
temperature=temperature,
|
16 |
-
token=os.getenv("HF_TOKEN") # Hugging Face
|
17 |
)
|
18 |
-
return llm
|
19 |
|
20 |
def get_nasa_apod():
|
21 |
-
"""
|
22 |
-
Fetch the Astronomy Picture of the Day (APOD) from the NASA API.
|
23 |
-
"""
|
24 |
url = f"https://api.nasa.gov/planetary/apod?api_key={NASA_API_KEY}"
|
25 |
response = requests.get(url)
|
26 |
if response.status_code == 200:
|
27 |
data = response.json()
|
28 |
-
return
|
29 |
else:
|
30 |
-
return "I couldn't fetch data from NASA right now. Please try again later."
|
|
|
|
|
|
|
|
|
31 |
|
32 |
-
def
|
33 |
-
eos_token_id=['User'], max_new_tokens=256, get_llm_hf_kws={}):
|
34 |
if "NASA" in user_text or "space" in user_text:
|
35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
chat_history.append({'role': 'user', 'content': user_text})
|
37 |
-
chat_history.append({'role': 'assistant', 'content':
|
38 |
-
|
|
|
|
|
|
|
39 |
|
40 |
hf = get_llm_hf_inference(max_new_tokens=max_new_tokens, temperature=0.1)
|
41 |
|
42 |
prompt = PromptTemplate.from_template(
|
43 |
-
|
44 |
-
"[INST] {system_message}"
|
45 |
-
"\nCurrent Conversation:\n{chat_history}\n\n"
|
46 |
-
"\nUser: {user_text}.\n [/INST]"
|
47 |
-
"\nAI:"
|
48 |
-
)
|
49 |
)
|
50 |
chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
|
51 |
response = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=chat_history))
|
@@ -53,31 +85,91 @@ def get_response(system_message, chat_history, user_text,
|
|
53 |
|
54 |
chat_history.append({'role': 'user', 'content': user_text})
|
55 |
chat_history.append({'role': 'assistant', 'content': response})
|
56 |
-
return response, chat_history
|
57 |
|
58 |
-
|
59 |
-
|
60 |
-
st.title("NASA Personal Assistant")
|
61 |
-
st.markdown(f"*This chatbot uses {model_id} and NASA's APIs to provide information and responses.*")
|
62 |
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
|
|
|
|
|
|
|
|
|
|
68 |
if st.sidebar.button("Reset Chat"):
|
69 |
st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
|
71 |
-
# Main chat interface
|
72 |
-
user_input = st.chat_input(placeholder="Type your message here...")
|
73 |
if user_input:
|
74 |
-
response, st.session_state.chat_history = get_response(
|
75 |
system_message="You are a helpful AI assistant.",
|
76 |
user_text=user_input,
|
77 |
-
chat_history=st.session_state.chat_history
|
78 |
-
max_new_tokens=128
|
79 |
)
|
80 |
-
# Display messages
|
81 |
-
for message in st.session_state.chat_history:
|
82 |
-
st.chat_message(message["role"]).write(message["content"])
|
83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
+
import requests
|
3 |
import streamlit as st
|
4 |
+
from langchain_huggingface import HuggingFaceEndpoint
|
5 |
from langchain_core.prompts import PromptTemplate
|
6 |
from langchain_core.output_parsers import StrOutputParser
|
7 |
+
from transformers import pipeline
|
8 |
+
from config import NASA_API_KEY # Ensure this file exists with your NASA API Key
|
9 |
+
|
10 |
+
# Set up Streamlit UI
|
11 |
+
st.set_page_config(page_title="HAL - NASA ChatBot", page_icon="π")
|
12 |
+
|
13 |
+
# --- Ensure Session State Variables are Initialized ---
|
14 |
+
if "chat_history" not in st.session_state:
|
15 |
+
st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
|
16 |
|
17 |
+
if "response_ready" not in st.session_state:
|
18 |
+
st.session_state.response_ready = False # Tracks whether HAL has responded
|
19 |
+
|
20 |
+
if "follow_up" not in st.session_state:
|
21 |
+
st.session_state.follow_up = "" # Stores follow-up question
|
22 |
+
|
23 |
+
# --- Set Up Model & API Functions ---
|
24 |
model_id = "mistralai/Mistral-7B-Instruct-v0.3"
|
25 |
|
26 |
+
# Initialize sentiment analysis pipeline
|
27 |
+
sentiment_analyzer = pipeline("sentiment-analysis")
|
28 |
+
|
29 |
def get_llm_hf_inference(model_id=model_id, max_new_tokens=128, temperature=0.1):
|
30 |
+
return HuggingFaceEndpoint(
|
31 |
repo_id=model_id,
|
32 |
max_new_tokens=max_new_tokens,
|
33 |
temperature=temperature,
|
34 |
+
token=os.getenv("HF_TOKEN") # Hugging Face API Token
|
35 |
)
|
|
|
36 |
|
37 |
def get_nasa_apod():
|
|
|
|
|
|
|
38 |
url = f"https://api.nasa.gov/planetary/apod?api_key={NASA_API_KEY}"
|
39 |
response = requests.get(url)
|
40 |
if response.status_code == 200:
|
41 |
data = response.json()
|
42 |
+
return data.get("url", ""), data.get("title", ""), data.get("explanation", "")
|
43 |
else:
|
44 |
+
return "", "NASA Data Unavailable", "I couldn't fetch data from NASA right now. Please try again later."
|
45 |
+
|
46 |
+
def analyze_sentiment(user_text):
|
47 |
+
result = sentiment_analyzer(user_text)[0]
|
48 |
+
return result['label']
|
49 |
|
50 |
+
def predict_action(user_text):
|
|
|
51 |
if "NASA" in user_text or "space" in user_text:
|
52 |
+
return "nasa_info"
|
53 |
+
return "general_query"
|
54 |
+
|
55 |
+
def generate_follow_up(user_text):
|
56 |
+
prompt_text = (
|
57 |
+
f"Based on the user's message: '{user_text}', suggest a natural follow-up question "
|
58 |
+
"to keep the conversation engaging."
|
59 |
+
)
|
60 |
+
hf = get_llm_hf_inference(max_new_tokens=64, temperature=0.7)
|
61 |
+
return hf.invoke(input=prompt_text).strip()
|
62 |
+
|
63 |
+
def get_response(system_message, chat_history, user_text, max_new_tokens=256):
|
64 |
+
sentiment = analyze_sentiment(user_text)
|
65 |
+
action = predict_action(user_text)
|
66 |
+
|
67 |
+
if action == "nasa_info":
|
68 |
+
nasa_url, nasa_title, nasa_explanation = get_nasa_apod()
|
69 |
+
response = f"**{nasa_title}**\n\n{nasa_explanation}"
|
70 |
chat_history.append({'role': 'user', 'content': user_text})
|
71 |
+
chat_history.append({'role': 'assistant', 'content': response})
|
72 |
+
|
73 |
+
follow_up = generate_follow_up(user_text)
|
74 |
+
chat_history.append({'role': 'assistant', 'content': follow_up})
|
75 |
+
return response, follow_up, chat_history, nasa_url
|
76 |
|
77 |
hf = get_llm_hf_inference(max_new_tokens=max_new_tokens, temperature=0.1)
|
78 |
|
79 |
prompt = PromptTemplate.from_template(
|
80 |
+
"[INST] {system_message}\n\nCurrent Conversation:\n{chat_history}\n\nUser: {user_text}.\n [/INST]\nAI:"
|
|
|
|
|
|
|
|
|
|
|
81 |
)
|
82 |
chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
|
83 |
response = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=chat_history))
|
|
|
85 |
|
86 |
chat_history.append({'role': 'user', 'content': user_text})
|
87 |
chat_history.append({'role': 'assistant', 'content': response})
|
|
|
88 |
|
89 |
+
if sentiment == "NEGATIVE":
|
90 |
+
response += "\nπ I'm sorry to hear that. How can I assist you further?"
|
|
|
|
|
91 |
|
92 |
+
follow_up = generate_follow_up(user_text)
|
93 |
+
chat_history.append({'role': 'assistant', 'content': follow_up})
|
94 |
+
|
95 |
+
return response, follow_up, chat_history, None
|
96 |
+
|
97 |
+
# --- Chat UI ---
|
98 |
+
st.title("π HAL - Your NASA AI Assistant")
|
99 |
+
st.markdown("π *Ask me about space, NASA, and beyond!*")
|
100 |
+
|
101 |
+
# Sidebar: Reset Chat
|
102 |
if st.sidebar.button("Reset Chat"):
|
103 |
st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
|
104 |
+
st.session_state.response_ready = False
|
105 |
+
st.session_state.follow_up = ""
|
106 |
+
st.experimental_rerun()
|
107 |
+
|
108 |
+
# Custom Chat Styling
|
109 |
+
st.markdown("""
|
110 |
+
<style>
|
111 |
+
.user-msg {
|
112 |
+
background-color: #0078D7;
|
113 |
+
color: white;
|
114 |
+
padding: 10px;
|
115 |
+
border-radius: 10px;
|
116 |
+
margin-bottom: 5px;
|
117 |
+
width: fit-content;
|
118 |
+
max-width: 80%;
|
119 |
+
}
|
120 |
+
.assistant-msg {
|
121 |
+
background-color: #333333;
|
122 |
+
color: white;
|
123 |
+
padding: 10px;
|
124 |
+
border-radius: 10px;
|
125 |
+
margin-bottom: 5px;
|
126 |
+
width: fit-content;
|
127 |
+
max-width: 80%;
|
128 |
+
}
|
129 |
+
.container {
|
130 |
+
display: flex;
|
131 |
+
flex-direction: column;
|
132 |
+
align-items: flex-start;
|
133 |
+
}
|
134 |
+
@media (max-width: 600px) {
|
135 |
+
.user-msg, .assistant-msg { font-size: 16px; max-width: 100%; }
|
136 |
+
}
|
137 |
+
</style>
|
138 |
+
""", unsafe_allow_html=True)
|
139 |
+
|
140 |
+
# Chat History Display
|
141 |
+
st.markdown("<div class='container'>", unsafe_allow_html=True)
|
142 |
+
for message in st.session_state.chat_history:
|
143 |
+
if message["role"] == "user":
|
144 |
+
st.markdown(f"<div class='user-msg'><strong>You:</strong> {message['content']}</div>", unsafe_allow_html=True)
|
145 |
+
else:
|
146 |
+
st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {message['content']}</div>", unsafe_allow_html=True)
|
147 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
148 |
+
|
149 |
+
# --- Single Input Box for Both Initial and Follow-Up Messages ---
|
150 |
+
user_input = st.chat_input("Type your message here...") # Only ONE chat_input()
|
151 |
|
|
|
|
|
152 |
if user_input:
|
153 |
+
response, follow_up, st.session_state.chat_history, image_url = get_response(
|
154 |
system_message="You are a helpful AI assistant.",
|
155 |
user_text=user_input,
|
156 |
+
chat_history=st.session_state.chat_history
|
|
|
157 |
)
|
|
|
|
|
|
|
158 |
|
159 |
+
# Display HAL's response
|
160 |
+
st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {response}</div>", unsafe_allow_html=True)
|
161 |
+
|
162 |
+
# Display NASA image if available
|
163 |
+
if image_url:
|
164 |
+
st.image(image_url, caption="NASA Image of the Day")
|
165 |
+
|
166 |
+
# Store follow-up question in session state
|
167 |
+
st.session_state.follow_up = follow_up
|
168 |
+
st.session_state.response_ready = True # Enables follow-up response cycle
|
169 |
+
|
170 |
+
# Display follow-up question inside chat if available
|
171 |
+
if st.session_state.response_ready and st.session_state.follow_up:
|
172 |
+
st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {st.session_state.follow_up}</div>", unsafe_allow_html=True)
|
173 |
+
|
174 |
+
# Reset response state so user can type next input
|
175 |
+
st.session_state.response_ready = False
|