Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -24,51 +24,46 @@ if not NASA_API_KEY:
|
|
| 24 |
MODEL_ID = os.getenv("HAL_MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct")
|
| 25 |
REQUEST_TIMEOUT_S = 20
|
| 26 |
|
| 27 |
-
# Keep defaults short to avoid truncation on CPU
|
| 28 |
MAX_NEW_TOKENS_DEFAULT = int(os.getenv("HAL_MAX_NEW_TOKENS", "180"))
|
| 29 |
TOP_P_DEFAULT = float(os.getenv("HAL_TOP_P", "0.9"))
|
| 30 |
TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.0"))
|
| 31 |
|
| 32 |
-
|
| 33 |
-
HEADINGS = [
|
| 34 |
-
"## Answer",
|
| 35 |
-
"## Key Points",
|
| 36 |
-
"## Next Steps",
|
| 37 |
-
]
|
| 38 |
|
| 39 |
-
|
| 40 |
-
You are HAL, a NASA-focused
|
| 41 |
|
| 42 |
-
Hard
|
| 43 |
-
-
|
|
|
|
| 44 |
- Do not repeat the user's question.
|
| 45 |
-
-
|
| 46 |
-
- If you are uncertain
|
| 47 |
-
|
| 48 |
-
If TOOL_DATA is present and relevant:
|
| 49 |
-
- Use it and reference exact fields from TOOL_DATA.
|
| 50 |
|
| 51 |
-
|
| 52 |
## Answer
|
| 53 |
(2 to 4 sentences)
|
| 54 |
|
| 55 |
## Key Points
|
| 56 |
-
(2 to 4 bullet points
|
| 57 |
|
| 58 |
## Next Steps
|
| 59 |
-
(3 short follow-up questions as bullets)
|
| 60 |
""".strip()
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
""
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
|
| 70 |
# ----------------------------
|
| 71 |
-
# Streamlit
|
| 72 |
# ----------------------------
|
| 73 |
st.set_page_config(page_title="HAL — NASA AI Assistant", layout="centered")
|
| 74 |
|
|
@@ -95,21 +90,14 @@ st.markdown(
|
|
| 95 |
align-self: flex-start;
|
| 96 |
}
|
| 97 |
|
| 98 |
-
/* Compact markdown inside bubbles */
|
| 99 |
.bubble p { margin: 0 0 8px 0; }
|
| 100 |
.bubble p:last-child { margin-bottom: 0; }
|
| 101 |
|
| 102 |
-
.bubble ul, .bubble ol {
|
| 103 |
-
margin: 6px 0 6px 0;
|
| 104 |
-
padding-left: 20px;
|
| 105 |
-
}
|
| 106 |
.bubble li { margin: 2px 0; }
|
| 107 |
.bubble li p { margin: 0; }
|
| 108 |
|
| 109 |
-
.bubble h1, .bubble h2, .bubble h3 {
|
| 110 |
-
margin: 10px 0 6px 0;
|
| 111 |
-
font-weight: 700;
|
| 112 |
-
}
|
| 113 |
|
| 114 |
.page-title { margin-bottom: 0; }
|
| 115 |
.page-subtitle { margin-top: 4px; opacity: 0.8; }
|
|
@@ -123,8 +111,6 @@ st.markdown("<div class='page-subtitle'>Local instruction model with NASA tools<
|
|
| 123 |
|
| 124 |
with st.sidebar:
|
| 125 |
st.header("Controls")
|
| 126 |
-
|
| 127 |
-
# Keep the UI capped lower to encourage short completions
|
| 128 |
max_new_tokens = st.slider("Max new tokens", 64, 384, MAX_NEW_TOKENS_DEFAULT, 16)
|
| 129 |
temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)
|
| 130 |
top_p = st.slider("Top-p", 0.1, 1.0, TOP_P_DEFAULT, 0.05)
|
|
@@ -150,7 +136,7 @@ if "chat_history" not in st.session_state:
|
|
| 150 |
|
| 151 |
|
| 152 |
# ----------------------------
|
| 153 |
-
#
|
| 154 |
# ----------------------------
|
| 155 |
def safe_get(url: str, params: Optional[Dict[str, Any]] = None) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
|
| 156 |
try:
|
|
@@ -220,7 +206,6 @@ def ends_cleanly(text: str) -> bool:
|
|
| 220 |
|
| 221 |
|
| 222 |
def looks_truncated(text: str) -> bool:
|
| 223 |
-
# Missing structure OR ends mid-sentence
|
| 224 |
if not has_all_sections(text):
|
| 225 |
return True
|
| 226 |
if not ends_cleanly(text):
|
|
@@ -228,62 +213,12 @@ def looks_truncated(text: str) -> bool:
|
|
| 228 |
return False
|
| 229 |
|
| 230 |
|
| 231 |
-
def
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
Rules:
|
| 238 |
-
- Do not repeat any headings already present.
|
| 239 |
-
- Do not restart sections.
|
| 240 |
-
- Write only what is needed to finish the last incomplete sentence and, if missing,
|
| 241 |
-
finish missing bullets in "## Next Steps".
|
| 242 |
-
- Keep it short.
|
| 243 |
-
|
| 244 |
-
Text to continue (tail):
|
| 245 |
-
{tail}
|
| 246 |
-
|
| 247 |
-
ASSISTANT:
|
| 248 |
-
""".strip()
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
def finish_last_sentence_prompt(existing_answer: str) -> str:
|
| 252 |
-
tail = existing_answer[-600:]
|
| 253 |
-
return f"""
|
| 254 |
-
SYSTEM:
|
| 255 |
-
Finish the last sentence only. Output one short completion fragment.
|
| 256 |
-
Do not add headings. Do not add new paragraphs. Do not repeat any text.
|
| 257 |
-
|
| 258 |
-
Text (tail):
|
| 259 |
-
{tail}
|
| 260 |
-
|
| 261 |
-
ASSISTANT:
|
| 262 |
-
""".strip()
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
def trim_restart_sections(existing: str, cont: str) -> str:
|
| 266 |
-
"""
|
| 267 |
-
If the continuation restarts at a heading, cut it from that point.
|
| 268 |
-
"""
|
| 269 |
-
cont_l = cont.lstrip()
|
| 270 |
-
for h in HEADINGS:
|
| 271 |
-
if h in existing and cont_l.startswith(h):
|
| 272 |
-
return ""
|
| 273 |
-
return cont
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
def trim_overlap(existing: str, cont: str, max_window: int = 1200) -> str:
|
| 277 |
-
a = existing[-max_window:]
|
| 278 |
-
b = cont
|
| 279 |
-
max_k = 0
|
| 280 |
-
max_len = min(len(a), len(b), max_window)
|
| 281 |
-
for k in range(1, max_len + 1):
|
| 282 |
-
if a[-k:] == b[:k]:
|
| 283 |
-
max_k = k
|
| 284 |
-
if max_k > 0:
|
| 285 |
-
return b[max_k:].lstrip()
|
| 286 |
-
return cont
|
| 287 |
|
| 288 |
|
| 289 |
# ----------------------------
|
|
@@ -330,11 +265,7 @@ def load_llm(model_id: str):
|
|
| 330 |
device_map=device_map,
|
| 331 |
)
|
| 332 |
|
| 333 |
-
gen = pipeline(
|
| 334 |
-
"text-generation",
|
| 335 |
-
model=model,
|
| 336 |
-
tokenizer=tokenizer,
|
| 337 |
-
)
|
| 338 |
return gen
|
| 339 |
|
| 340 |
|
|
@@ -342,31 +273,29 @@ gen_pipe = load_llm(MODEL_ID)
|
|
| 342 |
|
| 343 |
|
| 344 |
# ----------------------------
|
| 345 |
-
# Prompt
|
| 346 |
# ----------------------------
|
| 347 |
def build_prompt(user_text: str, history: List[Dict[str, str]], tools: List[Dict[str, Any]]) -> str:
|
| 348 |
-
# Keep history small to reduce
|
| 349 |
recent = history[-2:]
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
{AGENT_INSTRUCTIONS}
|
| 356 |
|
| 357 |
-
|
| 358 |
-
|
|
|
|
|
|
|
| 359 |
|
| 360 |
-
|
| 361 |
-
{
|
| 362 |
|
| 363 |
-
|
| 364 |
-
{tools_block}
|
| 365 |
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
ASSISTANT:
|
| 370 |
""".strip()
|
| 371 |
|
| 372 |
|
|
@@ -397,13 +326,22 @@ def generate(prompt: str, max_new_tokens: int, temperature: float, top_p: float)
|
|
| 397 |
|
| 398 |
text = out[0].get("generated_text", "")
|
| 399 |
ans = strip_prompt(text, prompt)
|
|
|
|
|
|
|
| 400 |
|
| 401 |
-
# Stop if model starts emitting another role block
|
| 402 |
-
for stop in ["\nSYSTEM:", "\nUSER:", "\nASSISTANT:", "\nCONTEXT:", "\nTOOL_DATA:"]:
|
| 403 |
-
if stop in ans:
|
| 404 |
-
ans = ans.split(stop, 1)[0].rstrip()
|
| 405 |
|
| 406 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 407 |
|
| 408 |
|
| 409 |
def get_response(user_text: str) -> str:
|
|
@@ -413,27 +351,29 @@ def get_response(user_text: str) -> str:
|
|
| 413 |
answer = generate(prompt, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p)
|
| 414 |
answer = normalize_list_spacing(answer)
|
| 415 |
|
| 416 |
-
#
|
| 417 |
-
if
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
|
|
|
|
|
|
|
|
|
| 427 |
if not ends_cleanly(answer):
|
| 428 |
-
|
| 429 |
-
frag = generate(p3, max_new_tokens=40, temperature=temperature, top_p=top_p)
|
| 430 |
-
frag = frag.strip()
|
| 431 |
-
frag = trim_restart_sections(answer, frag)
|
| 432 |
-
frag = trim_overlap(answer, frag)
|
| 433 |
if frag:
|
| 434 |
-
# Avoid adding a new paragraph; just finish the sentence
|
| 435 |
answer = (answer.rstrip() + " " + frag.lstrip()).strip()
|
| 436 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 437 |
if verbose_tools and tools:
|
| 438 |
answer += "\n\n---\nTool payload snippets\n"
|
| 439 |
for t in tools:
|
|
@@ -444,7 +384,7 @@ def get_response(user_text: str) -> str:
|
|
| 444 |
|
| 445 |
|
| 446 |
# ----------------------------
|
| 447 |
-
#
|
| 448 |
# ----------------------------
|
| 449 |
user_input = st.chat_input("Ask a NASA question...")
|
| 450 |
|
|
|
|
| 24 |
MODEL_ID = os.getenv("HAL_MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct")
|
| 25 |
REQUEST_TIMEOUT_S = 20
|
| 26 |
|
|
|
|
| 27 |
MAX_NEW_TOKENS_DEFAULT = int(os.getenv("HAL_MAX_NEW_TOKENS", "180"))
|
| 28 |
TOP_P_DEFAULT = float(os.getenv("HAL_TOP_P", "0.9"))
|
| 29 |
TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.0"))
|
| 30 |
|
| 31 |
+
HEADINGS = ["## Answer", "## Key Points", "## Next Steps"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
+
SYSTEM_RULES = """
|
| 34 |
+
You are HAL, a NASA-focused assistant.
|
| 35 |
|
| 36 |
+
Hard rules:
|
| 37 |
+
- Never mention instructions, prompts, policies, or that you are following a task.
|
| 38 |
+
- Never say "the assistant" or describe what you are doing.
|
| 39 |
- Do not repeat the user's question.
|
| 40 |
+
- Keep the response short and complete.
|
| 41 |
+
- If you are uncertain: say so in one sentence and suggest how to verify.
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
Format (use these exact headings):
|
| 44 |
## Answer
|
| 45 |
(2 to 4 sentences)
|
| 46 |
|
| 47 |
## Key Points
|
| 48 |
+
(2 to 4 bullet points)
|
| 49 |
|
| 50 |
## Next Steps
|
| 51 |
+
(exactly 3 short follow-up questions as bullets, under 12 words each)
|
| 52 |
""".strip()
|
| 53 |
|
| 54 |
+
STOP_STRINGS = [
|
| 55 |
+
"\nSYSTEM:",
|
| 56 |
+
"\nUSER:",
|
| 57 |
+
"\nASSISTANT:",
|
| 58 |
+
"\nINSTRUCTIONS:",
|
| 59 |
+
"\nTASK:",
|
| 60 |
+
"\nThe assistant",
|
| 61 |
+
"\nAs an AI",
|
| 62 |
+
]
|
| 63 |
|
| 64 |
|
| 65 |
# ----------------------------
|
| 66 |
+
# Streamlit UI
|
| 67 |
# ----------------------------
|
| 68 |
st.set_page_config(page_title="HAL — NASA AI Assistant", layout="centered")
|
| 69 |
|
|
|
|
| 90 |
align-self: flex-start;
|
| 91 |
}
|
| 92 |
|
|
|
|
| 93 |
.bubble p { margin: 0 0 8px 0; }
|
| 94 |
.bubble p:last-child { margin-bottom: 0; }
|
| 95 |
|
| 96 |
+
.bubble ul, .bubble ol { margin: 6px 0 6px 0; padding-left: 20px; }
|
|
|
|
|
|
|
|
|
|
| 97 |
.bubble li { margin: 2px 0; }
|
| 98 |
.bubble li p { margin: 0; }
|
| 99 |
|
| 100 |
+
.bubble h1, .bubble h2, .bubble h3 { margin: 10px 0 6px 0; font-weight: 700; }
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
.page-title { margin-bottom: 0; }
|
| 103 |
.page-subtitle { margin-top: 4px; opacity: 0.8; }
|
|
|
|
| 111 |
|
| 112 |
with st.sidebar:
|
| 113 |
st.header("Controls")
|
|
|
|
|
|
|
| 114 |
max_new_tokens = st.slider("Max new tokens", 64, 384, MAX_NEW_TOKENS_DEFAULT, 16)
|
| 115 |
temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)
|
| 116 |
top_p = st.slider("Top-p", 0.1, 1.0, TOP_P_DEFAULT, 0.05)
|
|
|
|
| 136 |
|
| 137 |
|
| 138 |
# ----------------------------
|
| 139 |
+
# Helpers
|
| 140 |
# ----------------------------
|
| 141 |
def safe_get(url: str, params: Optional[Dict[str, Any]] = None) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
|
| 142 |
try:
|
|
|
|
| 206 |
|
| 207 |
|
| 208 |
def looks_truncated(text: str) -> bool:
|
|
|
|
| 209 |
if not has_all_sections(text):
|
| 210 |
return True
|
| 211 |
if not ends_cleanly(text):
|
|
|
|
| 213 |
return False
|
| 214 |
|
| 215 |
|
| 216 |
+
def apply_stop_strings(text: str) -> str:
|
| 217 |
+
out = text
|
| 218 |
+
for s in STOP_STRINGS:
|
| 219 |
+
if s in out:
|
| 220 |
+
out = out.split(s, 1)[0].rstrip()
|
| 221 |
+
return out
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
|
| 224 |
# ----------------------------
|
|
|
|
| 265 |
device_map=device_map,
|
| 266 |
)
|
| 267 |
|
| 268 |
+
gen = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
return gen
|
| 270 |
|
| 271 |
|
|
|
|
| 273 |
|
| 274 |
|
| 275 |
# ----------------------------
|
| 276 |
+
# Prompt building (chat-style; avoids meta triggers)
|
| 277 |
# ----------------------------
|
| 278 |
def build_prompt(user_text: str, history: List[Dict[str, str]], tools: List[Dict[str, Any]]) -> str:
|
| 279 |
+
# Keep history small for speed and to reduce drift
|
| 280 |
recent = history[-2:]
|
| 281 |
+
history_lines = []
|
| 282 |
+
for m in recent:
|
| 283 |
+
role = "User" if m["role"] == "user" else "Assistant"
|
| 284 |
+
history_lines.append(f"{role}: {m['content']}")
|
| 285 |
+
history_block = "\n".join(history_lines)
|
|
|
|
| 286 |
|
| 287 |
+
tool_block = ""
|
| 288 |
+
if tools:
|
| 289 |
+
# Provide tool results without labeling it "TOOL_DATA"
|
| 290 |
+
tool_block = "\n\nNASA Data:\n" + json.dumps(tools, indent=2, ensure_ascii=False)
|
| 291 |
|
| 292 |
+
# Note: we do not use sections named "CONTEXT" or "INSTRUCTIONS"
|
| 293 |
+
return f"""System: {SYSTEM_RULES}
|
| 294 |
|
| 295 |
+
{history_block}{tool_block}
|
|
|
|
| 296 |
|
| 297 |
+
User: {user_text}
|
| 298 |
+
Assistant:
|
|
|
|
|
|
|
| 299 |
""".strip()
|
| 300 |
|
| 301 |
|
|
|
|
| 326 |
|
| 327 |
text = out[0].get("generated_text", "")
|
| 328 |
ans = strip_prompt(text, prompt)
|
| 329 |
+
ans = apply_stop_strings(ans)
|
| 330 |
+
return ans.strip()
|
| 331 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 332 |
|
| 333 |
+
def finish_last_sentence(existing_answer: str) -> str:
|
| 334 |
+
tail = existing_answer[-500:]
|
| 335 |
+
prompt = f"""System: Finish the last sentence only. Output a short fragment. Do not add headings.
|
| 336 |
+
|
| 337 |
+
Text:
|
| 338 |
+
{tail}
|
| 339 |
+
|
| 340 |
+
Continuation:
|
| 341 |
+
""".strip()
|
| 342 |
+
frag = generate(prompt, max_new_tokens=40, temperature=temperature, top_p=top_p)
|
| 343 |
+
frag = apply_stop_strings(frag).strip()
|
| 344 |
+
return frag
|
| 345 |
|
| 346 |
|
| 347 |
def get_response(user_text: str) -> str:
|
|
|
|
| 351 |
answer = generate(prompt, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p)
|
| 352 |
answer = normalize_list_spacing(answer)
|
| 353 |
|
| 354 |
+
# If structure missing, do a short repair pass
|
| 355 |
+
if not has_all_sections(answer):
|
| 356 |
+
repair_prompt = f"""System: Rewrite the following into the required format exactly.
|
| 357 |
+
{SYSTEM_RULES}
|
| 358 |
+
|
| 359 |
+
Draft:
|
| 360 |
+
{answer}
|
| 361 |
+
|
| 362 |
+
Rewrite:
|
| 363 |
+
""".strip()
|
| 364 |
+
answer = generate(repair_prompt, max_new_tokens=min(max_new_tokens, 180), temperature=temperature, top_p=top_p)
|
| 365 |
+
answer = normalize_list_spacing(answer)
|
| 366 |
+
|
| 367 |
+
# If still mid-sentence, do a tiny finish pass
|
| 368 |
if not ends_cleanly(answer):
|
| 369 |
+
frag = finish_last_sentence(answer)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 370 |
if frag:
|
|
|
|
| 371 |
answer = (answer.rstrip() + " " + frag.lstrip()).strip()
|
| 372 |
|
| 373 |
+
# Final safety: stop-string trim again
|
| 374 |
+
answer = apply_stop_strings(answer)
|
| 375 |
+
answer = normalize_list_spacing(answer)
|
| 376 |
+
|
| 377 |
if verbose_tools and tools:
|
| 378 |
answer += "\n\n---\nTool payload snippets\n"
|
| 379 |
for t in tools:
|
|
|
|
| 384 |
|
| 385 |
|
| 386 |
# ----------------------------
|
| 387 |
+
# Render
|
| 388 |
# ----------------------------
|
| 389 |
user_input = st.chat_input("Ask a NASA question...")
|
| 390 |
|