Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -13,39 +13,18 @@ from transformers import AutoTokenizer, AutoModelForCausalLM
|
|
| 13 |
|
| 14 |
|
| 15 |
# ----------------------------
|
| 16 |
-
#
|
| 17 |
# ----------------------------
|
| 18 |
-
NASA_API_KEY = os.getenv("NASA_API_KEY")
|
| 19 |
-
if not NASA_API_KEY:
|
| 20 |
-
raise ValueError("NASA_API_KEY is not set.")
|
| 21 |
|
| 22 |
MODEL_ID = os.getenv("HAL_MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct")
|
| 23 |
REQUEST_TIMEOUT_S = 20
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
|
| 29 |
-
|
| 30 |
-
You are HAL, a NASA-focused assistant.
|
| 31 |
-
|
| 32 |
-
Non-negotiable rules:
|
| 33 |
-
- Do not write disclaimers like "As an AI language model" or "I cannot..."
|
| 34 |
-
- Do not mention policies, prompts, system messages, hidden rules, or tasks.
|
| 35 |
-
- Do not output "EndOfMessage" or any sentinel markers.
|
| 36 |
-
- Do not repeat the user's question.
|
| 37 |
-
- Keep it short, complete, and directly helpful.
|
| 38 |
-
|
| 39 |
-
Output format (use these headings exactly):
|
| 40 |
-
## Answer
|
| 41 |
-
Write 2 to 4 sentences.
|
| 42 |
-
|
| 43 |
-
## Key Points
|
| 44 |
-
Write 2 to 4 bullet points.
|
| 45 |
-
|
| 46 |
-
## Next Steps
|
| 47 |
-
Write exactly 3 bullet questions, under 12 words each.
|
| 48 |
-
""".strip()
|
| 49 |
|
| 50 |
# If any of these appear, we cut the generation at that point.
|
| 51 |
STOP_SUBSTRINGS = [
|
|
@@ -62,9 +41,10 @@ STOP_SUBSTRINGS = [
|
|
| 62 |
"ASSISTANT:",
|
| 63 |
"INSTRUCTIONS",
|
| 64 |
"TASK:",
|
|
|
|
|
|
|
| 65 |
]
|
| 66 |
|
| 67 |
-
# Lines matching these patterns are removed during cleanup
|
| 68 |
BAD_LINE_PATTERNS = [
|
| 69 |
r"^\s*as an ai\b",
|
| 70 |
r"^\s*i am not capable\b",
|
|
@@ -75,11 +55,8 @@ BAD_LINE_PATTERNS = [
|
|
| 75 |
]
|
| 76 |
|
| 77 |
|
| 78 |
-
NASA_BASE = "https://api.nasa.gov"
|
| 79 |
-
|
| 80 |
-
|
| 81 |
# ----------------------------
|
| 82 |
-
# Streamlit
|
| 83 |
# ----------------------------
|
| 84 |
st.set_page_config(page_title="HAL — NASA AI Assistant", layout="centered")
|
| 85 |
|
|
@@ -109,6 +86,7 @@ st.markdown(
|
|
| 109 |
.bubble p { margin: 0 0 8px 0; }
|
| 110 |
.bubble p:last-child { margin-bottom: 0; }
|
| 111 |
|
|
|
|
| 112 |
.bubble ul, .bubble ol { margin: 6px 0 6px 0; padding-left: 20px; }
|
| 113 |
.bubble li { margin: 2px 0; }
|
| 114 |
.bubble li p { margin: 0; }
|
|
@@ -117,20 +95,40 @@ st.markdown(
|
|
| 117 |
|
| 118 |
.page-title { margin-bottom: 0; }
|
| 119 |
.page-subtitle { margin-top: 4px; opacity: 0.8; }
|
|
|
|
| 120 |
</style>
|
| 121 |
""",
|
| 122 |
unsafe_allow_html=True,
|
| 123 |
)
|
| 124 |
|
| 125 |
st.markdown("<h1 class='page-title'>HAL — NASA AI Assistant</h1>", unsafe_allow_html=True)
|
| 126 |
-
st.markdown("<div class='page-subtitle'>Local instruction model with NASA tools</div>", unsafe_allow_html=True)
|
| 127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
with st.sidebar:
|
| 129 |
st.header("Controls")
|
| 130 |
-
max_new_tokens = st.slider("Max new tokens", 64, 320, MAX_NEW_TOKENS_DEFAULT, 16)
|
| 131 |
-
temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)
|
| 132 |
-
top_p = st.slider("Top-p", 0.1, 1.0, TOP_P_DEFAULT, 0.05)
|
| 133 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
tool_mode = st.toggle("Use NASA tools when relevant", value=True)
|
| 135 |
verbose_tools = st.toggle("Show tool payload snippets", value=False)
|
| 136 |
|
|
@@ -139,20 +137,18 @@ with st.sidebar:
|
|
| 139 |
st.write(MODEL_ID)
|
| 140 |
st.write("Device:", "cuda" if torch.cuda.is_available() else "cpu")
|
| 141 |
|
|
|
|
|
|
|
|
|
|
| 142 |
if st.button("Clear chat"):
|
| 143 |
st.session_state.chat_history = [
|
| 144 |
{"role": "assistant", "content": "Hello. Ask me a NASA or space science question."}
|
| 145 |
]
|
| 146 |
st.rerun()
|
| 147 |
|
| 148 |
-
if "chat_history" not in st.session_state:
|
| 149 |
-
st.session_state.chat_history = [
|
| 150 |
-
{"role": "assistant", "content": "Hello. Ask me a NASA or space science question."}
|
| 151 |
-
]
|
| 152 |
-
|
| 153 |
|
| 154 |
# ----------------------------
|
| 155 |
-
#
|
| 156 |
# ----------------------------
|
| 157 |
def safe_get(url: str, params: Optional[Dict[str, Any]] = None) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
|
| 158 |
try:
|
|
@@ -165,6 +161,8 @@ def safe_get(url: str, params: Optional[Dict[str, Any]] = None) -> Tuple[Optiona
|
|
| 165 |
|
| 166 |
|
| 167 |
def nasa_apod(date: Optional[str] = None) -> Dict[str, Any]:
|
|
|
|
|
|
|
| 168 |
params = {"api_key": NASA_API_KEY}
|
| 169 |
if date:
|
| 170 |
params["date"] = date
|
|
@@ -175,6 +173,8 @@ def nasa_apod(date: Optional[str] = None) -> Dict[str, Any]:
|
|
| 175 |
|
| 176 |
|
| 177 |
def plan_tools(user_text: str) -> List[Dict[str, Any]]:
|
|
|
|
|
|
|
| 178 |
t = user_text.lower()
|
| 179 |
tools: List[Dict[str, Any]] = []
|
| 180 |
if "apod" in t or "astronomy picture of the day" in t:
|
|
@@ -184,32 +184,9 @@ def plan_tools(user_text: str) -> List[Dict[str, Any]]:
|
|
| 184 |
return tools
|
| 185 |
|
| 186 |
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
in_list = False
|
| 191 |
-
list_item_re = re.compile(r"^\s*(?:[-*]|\d+\.)\s+")
|
| 192 |
-
|
| 193 |
-
for line in lines:
|
| 194 |
-
stripped = line.strip()
|
| 195 |
-
is_list_item = bool(list_item_re.match(line))
|
| 196 |
-
|
| 197 |
-
if is_list_item:
|
| 198 |
-
in_list = True
|
| 199 |
-
cleaned.append(line)
|
| 200 |
-
continue
|
| 201 |
-
|
| 202 |
-
if in_list and stripped == "":
|
| 203 |
-
continue
|
| 204 |
-
|
| 205 |
-
if stripped and not line.startswith((" ", "\t")):
|
| 206 |
-
in_list = False
|
| 207 |
-
|
| 208 |
-
cleaned.append(line)
|
| 209 |
-
|
| 210 |
-
return "\n".join(cleaned).strip()
|
| 211 |
-
|
| 212 |
-
|
| 213 |
def cut_at_stop_substrings(text: str) -> str:
|
| 214 |
out = text
|
| 215 |
earliest = None
|
|
@@ -236,22 +213,30 @@ def remove_bad_lines(text: str) -> str:
|
|
| 236 |
return "\n".join(out_lines).strip()
|
| 237 |
|
| 238 |
|
| 239 |
-
def
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
|
| 256 |
|
| 257 |
def ends_cleanly(text: str) -> bool:
|
|
@@ -261,6 +246,22 @@ def ends_cleanly(text: str) -> bool:
|
|
| 261 |
return t[-1] in ".!?)]\"'"
|
| 262 |
|
| 263 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
# ----------------------------
|
| 265 |
# Model loading (cached)
|
| 266 |
# ----------------------------
|
|
@@ -271,33 +272,107 @@ def load_model(model_id: str):
|
|
| 271 |
dtype = torch.float16 if use_cuda else torch.float32
|
| 272 |
|
| 273 |
tok = AutoTokenizer.from_pretrained(model_id, use_fast=True)
|
| 274 |
-
|
| 275 |
model_id,
|
| 276 |
torch_dtype=dtype,
|
| 277 |
device_map="auto" if use_cuda else None,
|
| 278 |
)
|
| 279 |
if not use_cuda:
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
|
| 287 |
|
| 288 |
-
def build_messages(
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
for m in recent:
|
| 294 |
if m["role"] in ("user", "assistant"):
|
| 295 |
msgs.append({"role": m["role"], "content": m["content"]})
|
| 296 |
|
| 297 |
if tools:
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
|
|
|
| 301 |
|
| 302 |
msgs.append({"role": "user", "content": user_text})
|
| 303 |
return msgs
|
|
@@ -306,7 +381,20 @@ def build_messages(user_text: str, history: List[Dict[str, str]], tools: List[Di
|
|
| 306 |
def generate_answer(user_text: str) -> str:
|
| 307 |
tools = plan_tools(user_text) if tool_mode else []
|
| 308 |
|
| 309 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
|
| 311 |
prompt = tokenizer.apply_chat_template(
|
| 312 |
messages,
|
|
@@ -315,7 +403,6 @@ def generate_answer(user_text: str) -> str:
|
|
| 315 |
)
|
| 316 |
|
| 317 |
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 318 |
-
|
| 319 |
do_sample = temperature > 0.0
|
| 320 |
|
| 321 |
with torch.inference_mode():
|
|
@@ -325,7 +412,7 @@ def generate_answer(user_text: str) -> str:
|
|
| 325 |
do_sample=do_sample,
|
| 326 |
temperature=float(temperature) if do_sample else None,
|
| 327 |
top_p=float(top_p) if do_sample else None,
|
| 328 |
-
repetition_penalty=1.
|
| 329 |
eos_token_id=tokenizer.eos_token_id,
|
| 330 |
pad_token_id=tokenizer.eos_token_id,
|
| 331 |
)
|
|
@@ -336,13 +423,14 @@ def generate_answer(user_text: str) -> str:
|
|
| 336 |
if decoded.startswith(prompt):
|
| 337 |
decoded = decoded[len(prompt):].strip()
|
| 338 |
|
| 339 |
-
#
|
| 340 |
decoded = cut_at_stop_substrings(decoded)
|
| 341 |
decoded = remove_bad_lines(decoded)
|
| 342 |
decoded = normalize_list_spacing(decoded)
|
| 343 |
-
decoded = ensure_sections(decoded)
|
| 344 |
|
| 345 |
-
#
|
|
|
|
|
|
|
| 346 |
if not ends_cleanly(decoded):
|
| 347 |
decoded = decoded.rstrip() + "."
|
| 348 |
|
|
@@ -356,7 +444,7 @@ def generate_answer(user_text: str) -> str:
|
|
| 356 |
|
| 357 |
|
| 358 |
# ----------------------------
|
| 359 |
-
#
|
| 360 |
# ----------------------------
|
| 361 |
user_input = st.chat_input("Ask a NASA question...")
|
| 362 |
|
|
@@ -370,7 +458,6 @@ st.markdown("<div class='chat-wrap'>", unsafe_allow_html=True)
|
|
| 370 |
|
| 371 |
for msg in st.session_state.chat_history:
|
| 372 |
bubble_class = "user-bubble" if msg["role"] == "user" else "assistant-bubble"
|
| 373 |
-
# Streamlit markdown is fine here; our CSS fixes list spacing
|
| 374 |
st.markdown(f"<div class='bubble {bubble_class}'>", unsafe_allow_html=True)
|
| 375 |
st.markdown(msg["content"])
|
| 376 |
st.markdown("</div>", unsafe_allow_html=True)
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
# ----------------------------
|
| 16 |
+
# Configuration
|
| 17 |
# ----------------------------
|
| 18 |
+
NASA_API_KEY = os.getenv("NASA_API_KEY", "").strip()
|
|
|
|
|
|
|
| 19 |
|
| 20 |
MODEL_ID = os.getenv("HAL_MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct")
|
| 21 |
REQUEST_TIMEOUT_S = 20
|
| 22 |
|
| 23 |
+
DEFAULT_MAX_NEW_TOKENS = int(os.getenv("HAL_MAX_NEW_TOKENS", "180"))
|
| 24 |
+
DEFAULT_TEMPERATURE = float(os.getenv("HAL_TEMPERATURE", "0.2"))
|
| 25 |
+
DEFAULT_TOP_P = float(os.getenv("HAL_TOP_P", "0.9"))
|
| 26 |
|
| 27 |
+
NASA_BASE = "https://api.nasa.gov"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
# If any of these appear, we cut the generation at that point.
|
| 30 |
STOP_SUBSTRINGS = [
|
|
|
|
| 41 |
"ASSISTANT:",
|
| 42 |
"INSTRUCTIONS",
|
| 43 |
"TASK:",
|
| 44 |
+
"BEGIN",
|
| 45 |
+
"END",
|
| 46 |
]
|
| 47 |
|
|
|
|
| 48 |
BAD_LINE_PATTERNS = [
|
| 49 |
r"^\s*as an ai\b",
|
| 50 |
r"^\s*i am not capable\b",
|
|
|
|
| 55 |
]
|
| 56 |
|
| 57 |
|
|
|
|
|
|
|
|
|
|
| 58 |
# ----------------------------
|
| 59 |
+
# Streamlit page
|
| 60 |
# ----------------------------
|
| 61 |
st.set_page_config(page_title="HAL — NASA AI Assistant", layout="centered")
|
| 62 |
|
|
|
|
| 86 |
.bubble p { margin: 0 0 8px 0; }
|
| 87 |
.bubble p:last-child { margin-bottom: 0; }
|
| 88 |
|
| 89 |
+
/* Tight list spacing */
|
| 90 |
.bubble ul, .bubble ol { margin: 6px 0 6px 0; padding-left: 20px; }
|
| 91 |
.bubble li { margin: 2px 0; }
|
| 92 |
.bubble li p { margin: 0; }
|
|
|
|
| 95 |
|
| 96 |
.page-title { margin-bottom: 0; }
|
| 97 |
.page-subtitle { margin-top: 4px; opacity: 0.8; }
|
| 98 |
+
.small-muted { opacity: 0.75; font-size: 0.9rem; }
|
| 99 |
</style>
|
| 100 |
""",
|
| 101 |
unsafe_allow_html=True,
|
| 102 |
)
|
| 103 |
|
| 104 |
st.markdown("<h1 class='page-title'>HAL — NASA AI Assistant</h1>", unsafe_allow_html=True)
|
| 105 |
+
st.markdown("<div class='page-subtitle'>Local instruction model with optional NASA tools</div>", unsafe_allow_html=True)
|
| 106 |
|
| 107 |
+
if "chat_history" not in st.session_state:
|
| 108 |
+
st.session_state.chat_history = [
|
| 109 |
+
{"role": "assistant", "content": "Hello. Ask me a NASA or space science question."}
|
| 110 |
+
]
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# ----------------------------
|
| 114 |
+
# Sidebar controls
|
| 115 |
+
# ----------------------------
|
| 116 |
with st.sidebar:
|
| 117 |
st.header("Controls")
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
max_new_tokens = st.slider("Max new tokens", 64, 320, DEFAULT_MAX_NEW_TOKENS, 16)
|
| 120 |
+
temperature = st.slider("Temperature", 0.0, 1.2, DEFAULT_TEMPERATURE, 0.05)
|
| 121 |
+
top_p = st.slider("Top-p", 0.1, 1.0, DEFAULT_TOP_P, 0.05)
|
| 122 |
+
|
| 123 |
+
st.divider()
|
| 124 |
+
st.subheader("Science style")
|
| 125 |
+
depth = st.select_slider("Depth", options=["Brief", "Standard", "Deep"], value="Standard")
|
| 126 |
+
level = st.selectbox("Technical level", ["Beginner", "Intermediate", "Technical"], index=1)
|
| 127 |
+
include_math = st.toggle("Include minimal math when helpful", value=False)
|
| 128 |
+
include_analogy = st.toggle("Include a short analogy", value=True)
|
| 129 |
+
ask_followups = st.toggle("Ask follow-up questions", value=True)
|
| 130 |
+
|
| 131 |
+
st.divider()
|
| 132 |
tool_mode = st.toggle("Use NASA tools when relevant", value=True)
|
| 133 |
verbose_tools = st.toggle("Show tool payload snippets", value=False)
|
| 134 |
|
|
|
|
| 137 |
st.write(MODEL_ID)
|
| 138 |
st.write("Device:", "cuda" if torch.cuda.is_available() else "cpu")
|
| 139 |
|
| 140 |
+
if not NASA_API_KEY:
|
| 141 |
+
st.markdown("<div class='small-muted'>NASA_API_KEY not detected. Tool calls will be disabled.</div>", unsafe_allow_html=True)
|
| 142 |
+
|
| 143 |
if st.button("Clear chat"):
|
| 144 |
st.session_state.chat_history = [
|
| 145 |
{"role": "assistant", "content": "Hello. Ask me a NASA or space science question."}
|
| 146 |
]
|
| 147 |
st.rerun()
|
| 148 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
# ----------------------------
|
| 151 |
+
# NASA tools (minimal, safe)
|
| 152 |
# ----------------------------
|
| 153 |
def safe_get(url: str, params: Optional[Dict[str, Any]] = None) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
|
| 154 |
try:
|
|
|
|
| 161 |
|
| 162 |
|
| 163 |
def nasa_apod(date: Optional[str] = None) -> Dict[str, Any]:
|
| 164 |
+
if not NASA_API_KEY:
|
| 165 |
+
return {"tool": "apod", "ok": False, "data": None, "error": "NASA_API_KEY not set"}
|
| 166 |
params = {"api_key": NASA_API_KEY}
|
| 167 |
if date:
|
| 168 |
params["date"] = date
|
|
|
|
| 173 |
|
| 174 |
|
| 175 |
def plan_tools(user_text: str) -> List[Dict[str, Any]]:
|
| 176 |
+
if not NASA_API_KEY:
|
| 177 |
+
return []
|
| 178 |
t = user_text.lower()
|
| 179 |
tools: List[Dict[str, Any]] = []
|
| 180 |
if "apod" in t or "astronomy picture of the day" in t:
|
|
|
|
| 184 |
return tools
|
| 185 |
|
| 186 |
|
| 187 |
+
# ----------------------------
|
| 188 |
+
# Output cleanup
|
| 189 |
+
# ----------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
def cut_at_stop_substrings(text: str) -> str:
|
| 191 |
out = text
|
| 192 |
earliest = None
|
|
|
|
| 213 |
return "\n".join(out_lines).strip()
|
| 214 |
|
| 215 |
|
| 216 |
+
def normalize_list_spacing(text: str) -> str:
|
| 217 |
+
lines = text.splitlines()
|
| 218 |
+
cleaned: List[str] = []
|
| 219 |
+
in_list = False
|
| 220 |
+
list_item_re = re.compile(r"^\s*(?:[-*]|\d+\.)\s+")
|
| 221 |
+
|
| 222 |
+
for line in lines:
|
| 223 |
+
stripped = line.strip()
|
| 224 |
+
is_list_item = bool(list_item_re.match(line))
|
| 225 |
+
|
| 226 |
+
if is_list_item:
|
| 227 |
+
in_list = True
|
| 228 |
+
cleaned.append(line)
|
| 229 |
+
continue
|
| 230 |
+
|
| 231 |
+
if in_list and stripped == "":
|
| 232 |
+
continue
|
| 233 |
+
|
| 234 |
+
if stripped and not line.startswith((" ", "\t")):
|
| 235 |
+
in_list = False
|
| 236 |
+
|
| 237 |
+
cleaned.append(line)
|
| 238 |
+
|
| 239 |
+
return "\n".join(cleaned).strip()
|
| 240 |
|
| 241 |
|
| 242 |
def ends_cleanly(text: str) -> bool:
|
|
|
|
| 246 |
return t[-1] in ".!?)]\"'"
|
| 247 |
|
| 248 |
|
| 249 |
+
def soft_wrap_science(text: str, ask_followups_flag: bool) -> str:
|
| 250 |
+
"""
|
| 251 |
+
Do not discard the model response if it doesn't match a rigid template.
|
| 252 |
+
If it is missing follow-ups, append them.
|
| 253 |
+
"""
|
| 254 |
+
out = text.strip()
|
| 255 |
+
|
| 256 |
+
# If the model used headings without markdown "##", keep as-is.
|
| 257 |
+
# If it has no structure, that's fine; we still keep it.
|
| 258 |
+
if ask_followups_flag:
|
| 259 |
+
if "follow-up" not in out.lower() and "next" not in out.lower():
|
| 260 |
+
out = out.rstrip() + "\n\nFollow-up questions:\n- Want a simpler analogy?\n- Should we connect this to a NASA mission or instrument?\n- Do you want the technical version with equations?\n"
|
| 261 |
+
|
| 262 |
+
return out.strip()
|
| 263 |
+
|
| 264 |
+
|
| 265 |
# ----------------------------
|
| 266 |
# Model loading (cached)
|
| 267 |
# ----------------------------
|
|
|
|
| 272 |
dtype = torch.float16 if use_cuda else torch.float32
|
| 273 |
|
| 274 |
tok = AutoTokenizer.from_pretrained(model_id, use_fast=True)
|
| 275 |
+
mdl = AutoModelForCausalLM.from_pretrained(
|
| 276 |
model_id,
|
| 277 |
torch_dtype=dtype,
|
| 278 |
device_map="auto" if use_cuda else None,
|
| 279 |
)
|
| 280 |
if not use_cuda:
|
| 281 |
+
mdl.to(device)
|
| 282 |
+
|
| 283 |
+
return tok, mdl
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
tokenizer, model = load_model(MODEL_ID)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
# ----------------------------
|
| 290 |
+
# Prompting tuned for science explanations
|
| 291 |
+
# ----------------------------
|
| 292 |
+
def science_system_prompt(
|
| 293 |
+
*,
|
| 294 |
+
depth: str,
|
| 295 |
+
level: str,
|
| 296 |
+
include_math: bool,
|
| 297 |
+
include_analogy: bool,
|
| 298 |
+
ask_followups: bool,
|
| 299 |
+
) -> str:
|
| 300 |
+
# Depth guidance for token budgeting
|
| 301 |
+
depth_rules = {
|
| 302 |
+
"Brief": "Keep the answer to 3-5 sentences total. Use at most 3 bullets if any.",
|
| 303 |
+
"Standard": "Keep the answer under ~140 words. Use up to 4 bullets for key points.",
|
| 304 |
+
"Deep": "Keep the answer under ~220 words. Use up to 5 bullets for key points.",
|
| 305 |
+
}[depth]
|
| 306 |
+
|
| 307 |
+
level_rules = {
|
| 308 |
+
"Beginner": "Assume no physics background. Use plain language and avoid jargon; define any unavoidable term in-line.",
|
| 309 |
+
"Intermediate": "Assume basic science literacy. Use correct terms with short definitions when needed.",
|
| 310 |
+
"Technical": "Be precise. Use standard terminology and include one concise technical detail (equation or formal statement) if useful.",
|
| 311 |
+
}[level]
|
| 312 |
+
|
| 313 |
+
math_rules = (
|
| 314 |
+
"If a short equation helps, include at most one line of math and explain each symbol."
|
| 315 |
+
if include_math
|
| 316 |
+
else "Do not include equations."
|
| 317 |
+
)
|
| 318 |
|
| 319 |
+
analogy_rules = (
|
| 320 |
+
"Include one short analogy if it genuinely clarifies the concept."
|
| 321 |
+
if include_analogy
|
| 322 |
+
else "Do not use analogies."
|
| 323 |
+
)
|
| 324 |
|
| 325 |
+
followup_rules = (
|
| 326 |
+
"End with exactly three follow-up questions as bullets, each under 12 words."
|
| 327 |
+
if ask_followups
|
| 328 |
+
else "Do not ask follow-up questions."
|
| 329 |
+
)
|
| 330 |
|
| 331 |
+
return f"""
|
| 332 |
+
You are HAL, a NASA-focused science explainer.
|
| 333 |
+
|
| 334 |
+
Hard rules:
|
| 335 |
+
- Do not include disclaimers (for example: "As an AI language model").
|
| 336 |
+
- Do not mention policies, prompts, system messages, or hidden instructions.
|
| 337 |
+
- Do not repeat the user's question.
|
| 338 |
+
- Do not output sentinel text such as "EndOfMessage".
|
| 339 |
+
|
| 340 |
+
Science explanation style:
|
| 341 |
+
- Start with a direct answer first.
|
| 342 |
+
- Then give key points or evidence if helpful.
|
| 343 |
+
- Prefer clarity over completeness.
|
| 344 |
+
- If uncertainty exists, state it briefly and continue with what is known.
|
| 345 |
+
- When relevant, connect to NASA missions, instruments, or space context in one sentence.
|
| 346 |
+
|
| 347 |
+
Constraints:
|
| 348 |
+
- {depth_rules}
|
| 349 |
+
- {level_rules}
|
| 350 |
+
- {math_rules}
|
| 351 |
+
- {analogy_rules}
|
| 352 |
+
- {followup_rules}
|
| 353 |
+
""".strip()
|
| 354 |
|
| 355 |
|
| 356 |
+
def build_messages(
|
| 357 |
+
user_text: str,
|
| 358 |
+
history: List[Dict[str, str]],
|
| 359 |
+
system_text: str,
|
| 360 |
+
tools: List[Dict[str, Any]],
|
| 361 |
+
) -> List[Dict[str, str]]:
|
| 362 |
+
# Keep a small context window to reduce drift and speed up.
|
| 363 |
+
recent = history[-4:] if history else []
|
| 364 |
+
|
| 365 |
+
msgs: List[Dict[str, str]] = [{"role": "system", "content": system_text}]
|
| 366 |
|
| 367 |
for m in recent:
|
| 368 |
if m["role"] in ("user", "assistant"):
|
| 369 |
msgs.append({"role": m["role"], "content": m["content"]})
|
| 370 |
|
| 371 |
if tools:
|
| 372 |
+
tool_snip = json.dumps(tools, ensure_ascii=False)
|
| 373 |
+
if len(tool_snip) > 800:
|
| 374 |
+
tool_snip = tool_snip[:800] + "..."
|
| 375 |
+
msgs.append({"role": "user", "content": f"NASA reference data (use only if relevant): {tool_snip}"})
|
| 376 |
|
| 377 |
msgs.append({"role": "user", "content": user_text})
|
| 378 |
return msgs
|
|
|
|
| 381 |
def generate_answer(user_text: str) -> str:
|
| 382 |
tools = plan_tools(user_text) if tool_mode else []
|
| 383 |
|
| 384 |
+
system_text = science_system_prompt(
|
| 385 |
+
depth=depth,
|
| 386 |
+
level=level,
|
| 387 |
+
include_math=include_math,
|
| 388 |
+
include_analogy=include_analogy,
|
| 389 |
+
ask_followups=ask_followups,
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
messages = build_messages(
|
| 393 |
+
user_text=user_text,
|
| 394 |
+
history=st.session_state.chat_history,
|
| 395 |
+
system_text=system_text,
|
| 396 |
+
tools=tools,
|
| 397 |
+
)
|
| 398 |
|
| 399 |
prompt = tokenizer.apply_chat_template(
|
| 400 |
messages,
|
|
|
|
| 403 |
)
|
| 404 |
|
| 405 |
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
|
|
|
| 406 |
do_sample = temperature > 0.0
|
| 407 |
|
| 408 |
with torch.inference_mode():
|
|
|
|
| 412 |
do_sample=do_sample,
|
| 413 |
temperature=float(temperature) if do_sample else None,
|
| 414 |
top_p=float(top_p) if do_sample else None,
|
| 415 |
+
repetition_penalty=1.12,
|
| 416 |
eos_token_id=tokenizer.eos_token_id,
|
| 417 |
pad_token_id=tokenizer.eos_token_id,
|
| 418 |
)
|
|
|
|
| 423 |
if decoded.startswith(prompt):
|
| 424 |
decoded = decoded[len(prompt):].strip()
|
| 425 |
|
| 426 |
+
# Cleanup
|
| 427 |
decoded = cut_at_stop_substrings(decoded)
|
| 428 |
decoded = remove_bad_lines(decoded)
|
| 429 |
decoded = normalize_list_spacing(decoded)
|
|
|
|
| 430 |
|
| 431 |
+
# Soft structure (never discards content)
|
| 432 |
+
decoded = soft_wrap_science(decoded, ask_followups)
|
| 433 |
+
|
| 434 |
if not ends_cleanly(decoded):
|
| 435 |
decoded = decoded.rstrip() + "."
|
| 436 |
|
|
|
|
| 444 |
|
| 445 |
|
| 446 |
# ----------------------------
|
| 447 |
+
# Chat input + render
|
| 448 |
# ----------------------------
|
| 449 |
user_input = st.chat_input("Ask a NASA question...")
|
| 450 |
|
|
|
|
| 458 |
|
| 459 |
for msg in st.session_state.chat_history:
|
| 460 |
bubble_class = "user-bubble" if msg["role"] == "user" else "assistant-bubble"
|
|
|
|
| 461 |
st.markdown(f"<div class='bubble {bubble_class}'>", unsafe_allow_html=True)
|
| 462 |
st.markdown(msg["content"])
|
| 463 |
st.markdown("</div>", unsafe_allow_html=True)
|