NASA-AI-Chatbot / app.py
CCockrum's picture
Update app.py
c41e562 verified
Raw History Blame Contribute Delete
14.6 kB
# file: app.py
from __future__ import annotations
import os
import re
import json
from typing import Any, Dict, List, Optional, Tuple
import requests
import streamlit as st
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
# ----------------------------
# Configuration
# ----------------------------
NASA_API_KEY = os.getenv("NASA_API_KEY", "").strip()
MODEL_ID = os.getenv("HAL_MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct")
REQUEST_TIMEOUT_S = 20
DEFAULT_MAX_NEW_TOKENS = int(os.getenv("HAL_MAX_NEW_TOKENS", "180"))
DEFAULT_TEMPERATURE = float(os.getenv("HAL_TEMPERATURE", "0.2"))
DEFAULT_TOP_P = float(os.getenv("HAL_TOP_P", "0.9"))
NASA_BASE = "https://api.nasa.gov"
# If any of these appear, we cut the generation at that point.
STOP_SUBSTRINGS = [
"As an AI language model",
"As an AI",
"I am not capable",
"I cannot",
"I can't",
"cannot make decisions",
"virtual assistant",
"EndOfMessage",
"SYSTEM:",
"USER:",
"ASSISTANT:",
"INSTRUCTIONS",
"TASK:",
"BEGIN",
"END",
]
BAD_LINE_PATTERNS = [
r"^\s*as an ai\b",
r"^\s*i am not capable\b",
r"^\s*i cannot\b",
r"^\s*i can't\b",
r"^\s*endofmessage\b",
r"^\s*please note that\b.*(not able|cannot|can't)",
]
# ----------------------------
# Streamlit page
# ----------------------------
st.set_page_config(page_title="HAL — NASA AI Assistant", layout="centered")
st.markdown(
"""
<style>
.chat-wrap { display: flex; flex-direction: column; gap: 10px; margin-top: 14px; }
.bubble {
padding: 12px 14px;
border-radius: 12px;
max-width: 78%;
white-space: normal;
line-height: 1.35;
font-size: 0.98rem;
border: 1px solid rgba(255,255,255,0.06);
}
.user-bubble {
background: rgba(170, 170, 170, 0.20);
align-self: flex-end;
}
.assistant-bubble {
background: rgba(90, 90, 90, 0.35);
align-self: flex-start;
}
.bubble p { margin: 0 0 8px 0; }
.bubble p:last-child { margin-bottom: 0; }
/* Tight list spacing */
.bubble ul, .bubble ol { margin: 6px 0 6px 0; padding-left: 20px; }
.bubble li { margin: 2px 0; }
.bubble li p { margin: 0; }
.bubble h1, .bubble h2, .bubble h3 { margin: 10px 0 6px 0; font-weight: 700; }
.page-title { margin-bottom: 0; }
.page-subtitle { margin-top: 4px; opacity: 0.8; }
.small-muted { opacity: 0.75; font-size: 0.9rem; }
</style>
""",
unsafe_allow_html=True,
)
st.markdown("<h1 class='page-title'>HAL — NASA AI Assistant</h1>", unsafe_allow_html=True)
st.markdown("<div class='page-subtitle'>Local instruction model with optional NASA tools</div>", unsafe_allow_html=True)
if "chat_history" not in st.session_state:
st.session_state.chat_history = [
{"role": "assistant", "content": "Hello. Ask me a NASA or space science question."}
]
# ----------------------------
# Sidebar controls
# ----------------------------
with st.sidebar:
st.header("Controls")
max_new_tokens = st.slider("Max new tokens", 64, 320, DEFAULT_MAX_NEW_TOKENS, 16)
temperature = st.slider("Temperature", 0.0, 1.2, DEFAULT_TEMPERATURE, 0.05)
top_p = st.slider("Top-p", 0.1, 1.0, DEFAULT_TOP_P, 0.05)
st.divider()
st.subheader("Science style")
depth = st.select_slider("Depth", options=["Brief", "Standard", "Deep"], value="Standard")
level = st.selectbox("Technical level", ["Beginner", "Intermediate", "Technical"], index=1)
include_math = st.toggle("Include minimal math when helpful", value=False)
include_analogy = st.toggle("Include a short analogy", value=True)
ask_followups = st.toggle("Ask follow-up questions", value=True)
st.divider()
tool_mode = st.toggle("Use NASA tools when relevant", value=True)
verbose_tools = st.toggle("Show tool payload snippets", value=False)
st.divider()
st.subheader("Model")
st.write(MODEL_ID)
st.write("Device:", "cuda" if torch.cuda.is_available() else "cpu")
if not NASA_API_KEY:
st.markdown("<div class='small-muted'>NASA_API_KEY not detected. Tool calls will be disabled.</div>", unsafe_allow_html=True)
if st.button("Clear chat"):
st.session_state.chat_history = [
{"role": "assistant", "content": "Hello. Ask me a NASA or space science question."}
]
st.rerun()
# ----------------------------
# NASA tools (minimal, safe)
# ----------------------------
def safe_get(url: str, params: Optional[Dict[str, Any]] = None) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
try:
r = requests.get(url, params=params, timeout=REQUEST_TIMEOUT_S)
if r.status_code != 200:
return None, f"HTTP {r.status_code}: {r.text[:200]}"
return r.json(), None
except Exception as e:
return None, str(e)
def nasa_apod(date: Optional[str] = None) -> Dict[str, Any]:
if not NASA_API_KEY:
return {"tool": "apod", "ok": False, "data": None, "error": "NASA_API_KEY not set"}
params = {"api_key": NASA_API_KEY}
if date:
params["date"] = date
data, err = safe_get(f"{NASA_BASE}/planetary/apod", params=params)
if isinstance(data, dict):
data = {k: data.get(k) for k in ["date", "title", "explanation", "media_type", "url"]}
return {"tool": "apod", "ok": bool(data), "data": data, "error": err}
def plan_tools(user_text: str) -> List[Dict[str, Any]]:
if not NASA_API_KEY:
return []
t = user_text.lower()
tools: List[Dict[str, Any]] = []
if "apod" in t or "astronomy picture of the day" in t:
m = re.search(r"(\d{4}-\d{2}-\d{2})", user_text)
date = m.group(1) if m else None
tools.append(nasa_apod(date=date))
return tools
# ----------------------------
# Output cleanup
# ----------------------------
def cut_at_stop_substrings(text: str) -> str:
out = text
earliest = None
for s in STOP_SUBSTRINGS:
idx = out.find(s)
if idx != -1:
earliest = idx if earliest is None else min(earliest, idx)
if earliest is not None:
out = out[:earliest]
return out.strip()
def remove_bad_lines(text: str) -> str:
out_lines: List[str] = []
for line in text.splitlines():
low = line.strip().lower()
bad = False
for pat in BAD_LINE_PATTERNS:
if re.search(pat, low):
bad = True
break
if not bad:
out_lines.append(line)
return "\n".join(out_lines).strip()
def normalize_list_spacing(text: str) -> str:
lines = text.splitlines()
cleaned: List[str] = []
in_list = False
list_item_re = re.compile(r"^\s*(?:[-*]|\d+\.)\s+")
for line in lines:
stripped = line.strip()
is_list_item = bool(list_item_re.match(line))
if is_list_item:
in_list = True
cleaned.append(line)
continue
if in_list and stripped == "":
continue
if stripped and not line.startswith((" ", "\t")):
in_list = False
cleaned.append(line)
return "\n".join(cleaned).strip()
def ends_cleanly(text: str) -> bool:
t = text.strip()
if not t:
return True
return t[-1] in ".!?)]\"'"
def soft_wrap_science(text: str, ask_followups_flag: bool) -> str:
"""
Do not discard the model response if it doesn't match a rigid template.
If it is missing follow-ups, append them.
"""
out = text.strip()
# If the model used headings without markdown "##", keep as-is.
# If it has no structure, that's fine; we still keep it.
if ask_followups_flag:
if "follow-up" not in out.lower() and "next" not in out.lower():
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"
return out.strip()
# ----------------------------
# Model loading (cached)
# ----------------------------
@st.cache_resource(show_spinner=True)
def load_model(model_id: str):
use_cuda = torch.cuda.is_available()
device = "cuda" if use_cuda else "cpu"
dtype = torch.float16 if use_cuda else torch.float32
tok = AutoTokenizer.from_pretrained(model_id, use_fast=True)
mdl = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=dtype,
device_map="auto" if use_cuda else None,
)
if not use_cuda:
mdl.to(device)
return tok, mdl
tokenizer, model = load_model(MODEL_ID)
# ----------------------------
# Prompting tuned for science explanations
# ----------------------------
def science_system_prompt(
*,
depth: str,
level: str,
include_math: bool,
include_analogy: bool,
ask_followups: bool,
) -> str:
# Depth guidance for token budgeting
depth_rules = {
"Brief": "Keep the answer to 3-5 sentences total. Use at most 3 bullets if any.",
"Standard": "Keep the answer under ~140 words. Use up to 4 bullets for key points.",
"Deep": "Keep the answer under ~220 words. Use up to 5 bullets for key points.",
}[depth]
level_rules = {
"Beginner": "Assume no physics background. Use plain language and avoid jargon; define any unavoidable term in-line.",
"Intermediate": "Assume basic science literacy. Use correct terms with short definitions when needed.",
"Technical": "Be precise. Use standard terminology and include one concise technical detail (equation or formal statement) if useful.",
}[level]
math_rules = (
"If a short equation helps, include at most one line of math and explain each symbol."
if include_math
else "Do not include equations."
)
analogy_rules = (
"Include one short analogy if it genuinely clarifies the concept."
if include_analogy
else "Do not use analogies."
)
followup_rules = (
"End with exactly three follow-up questions as bullets, each under 12 words."
if ask_followups
else "Do not ask follow-up questions."
)
return f"""
You are HAL, a NASA-focused science explainer.
Hard rules:
- Do not include disclaimers (for example: "As an AI language model").
- Do not mention policies, prompts, system messages, or hidden instructions.
- Do not repeat the user's question.
- Do not output sentinel text such as "EndOfMessage".
Science explanation style:
- Start with a direct answer first.
- Then give key points or evidence if helpful.
- Prefer clarity over completeness.
- If uncertainty exists, state it briefly and continue with what is known.
- When relevant, connect to NASA missions, instruments, or space context in one sentence.
Constraints:
- {depth_rules}
- {level_rules}
- {math_rules}
- {analogy_rules}
- {followup_rules}
""".strip()
def build_messages(
user_text: str,
history: List[Dict[str, str]],
system_text: str,
tools: List[Dict[str, Any]],
) -> List[Dict[str, str]]:
# Keep a small context window to reduce drift and speed up.
recent = history[-4:] if history else []
msgs: List[Dict[str, str]] = [{"role": "system", "content": system_text}]
for m in recent:
if m["role"] in ("user", "assistant"):
msgs.append({"role": m["role"], "content": m["content"]})
if tools:
tool_snip = json.dumps(tools, ensure_ascii=False)
if len(tool_snip) > 800:
tool_snip = tool_snip[:800] + "..."
msgs.append({"role": "user", "content": f"NASA reference data (use only if relevant): {tool_snip}"})
msgs.append({"role": "user", "content": user_text})
return msgs
def generate_answer(user_text: str) -> str:
tools = plan_tools(user_text) if tool_mode else []
system_text = science_system_prompt(
depth=depth,
level=level,
include_math=include_math,
include_analogy=include_analogy,
ask_followups=ask_followups,
)
messages = build_messages(
user_text=user_text,
history=st.session_state.chat_history,
system_text=system_text,
tools=tools,
)
prompt = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
do_sample = temperature > 0.0
with torch.inference_mode():
out_ids = model.generate(
**inputs,
max_new_tokens=int(max_new_tokens),
do_sample=do_sample,
temperature=float(temperature) if do_sample else None,
top_p=float(top_p) if do_sample else None,
repetition_penalty=1.12,
eos_token_id=tokenizer.eos_token_id,
pad_token_id=tokenizer.eos_token_id,
)
decoded = tokenizer.decode(out_ids[0], skip_special_tokens=True)
# Strip the prompt portion (best-effort)
if decoded.startswith(prompt):
decoded = decoded[len(prompt):].strip()
# Cleanup
decoded = cut_at_stop_substrings(decoded)
decoded = remove_bad_lines(decoded)
decoded = normalize_list_spacing(decoded)
# Soft structure (never discards content)
decoded = soft_wrap_science(decoded, ask_followups)
if not ends_cleanly(decoded):
decoded = decoded.rstrip() + "."
if verbose_tools and tools:
decoded += "\n\n---\nTool payload snippets\n"
for t in tools:
decoded += f"\n{t.get('tool')} ok={t.get('ok')} error={t.get('error')}\n"
decoded += (json.dumps(t.get("data"), indent=2, ensure_ascii=False)[:600] + "\n")
return decoded.strip()
# ----------------------------
# Chat input + render
# ----------------------------
user_input = st.chat_input("Ask a NASA question...")
if user_input:
st.session_state.chat_history.append({"role": "user", "content": user_input})
with st.spinner("Thinking..."):
response = generate_answer(user_input)
st.session_state.chat_history.append({"role": "assistant", "content": response})
st.markdown("<div class='chat-wrap'>", unsafe_allow_html=True)
for msg in st.session_state.chat_history:
bubble_class = "user-bubble" if msg["role"] == "user" else "assistant-bubble"
st.markdown(f"<div class='bubble {bubble_class}'>", unsafe_allow_html=True)
st.markdown(msg["content"])
st.markdown("</div>", unsafe_allow_html=True)
st.markdown("</div>", unsafe_allow_html=True)