Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,31 +1,8 @@
|
|
| 1 |
-
# file: hal_bot.py
|
| 2 |
-
"""
|
| 3 |
-
🚀 HAL — NASA Chatbot (Streamlit)
|
| 4 |
-
Revised to be:
|
| 5 |
-
- Functional (no broken LangChain piping / output parsers)
|
| 6 |
-
- In-depth (tool-augmented: HAL fetches NASA data when relevant)
|
| 7 |
-
- Prompt-engineered (clear system + style + grounding + citations to NASA API payloads)
|
| 8 |
-
- Robust on CPU-only Streamlit hosting (loads model once, uses caching, handles timeouts)
|
| 9 |
-
|
| 10 |
-
✅ Setup (environment variables):
|
| 11 |
-
- NASA_API_KEY : required (get one at https://api.nasa.gov)
|
| 12 |
-
Optional:
|
| 13 |
-
- HF_TOKEN : not required in this version (we use local Flan-T5). Kept for compatibility.
|
| 14 |
-
|
| 15 |
-
Recommended requirements.txt (example):
|
| 16 |
-
streamlit
|
| 17 |
-
requests
|
| 18 |
-
transformers
|
| 19 |
-
torch
|
| 20 |
-
langdetect
|
| 21 |
-
"""
|
| 22 |
-
|
| 23 |
from __future__ import annotations
|
| 24 |
|
| 25 |
import os
|
| 26 |
import re
|
| 27 |
import json
|
| 28 |
-
import time
|
| 29 |
import datetime as dt
|
| 30 |
from dataclasses import dataclass
|
| 31 |
from typing import Any, Dict, List, Optional, Tuple
|
|
@@ -38,15 +15,12 @@ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
|
| 38 |
|
| 39 |
|
| 40 |
# ----------------------------
|
| 41 |
-
# Config
|
| 42 |
# ----------------------------
|
| 43 |
NASA_API_KEY = os.getenv("NASA_API_KEY")
|
| 44 |
if not NASA_API_KEY:
|
| 45 |
raise ValueError("NASA_API_KEY is not set. Add it as an environment variable.")
|
| 46 |
|
| 47 |
-
# Optional (not required in this version)
|
| 48 |
-
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 49 |
-
|
| 50 |
MODEL_ID = os.getenv("HAL_MODEL_ID", "google/flan-t5-large")
|
| 51 |
MAX_NEW_TOKENS_DEFAULT = int(os.getenv("HAL_MAX_NEW_TOKENS", "420"))
|
| 52 |
TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.3"))
|
|
@@ -54,12 +28,54 @@ TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.3"))
|
|
| 54 |
REQUEST_TIMEOUT_S = 20
|
| 55 |
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
# ----------------------------
|
| 58 |
# Streamlit Setup
|
| 59 |
# ----------------------------
|
| 60 |
st.set_page_config(page_title="HAL - NASA ChatBot", page_icon="🚀", layout="centered")
|
| 61 |
|
| 62 |
-
st.title("
|
| 63 |
st.caption("Tool-augmented NASA chatbot (APOD • Mars Rovers • NEOs • Earth Imagery • NASA Image Search)")
|
| 64 |
|
| 65 |
st.markdown(
|
|
@@ -85,17 +101,26 @@ st.markdown(
|
|
| 85 |
)
|
| 86 |
|
| 87 |
with st.sidebar:
|
| 88 |
-
st.header("
|
| 89 |
max_new_tokens = st.slider("Max new tokens", 64, 900, MAX_NEW_TOKENS_DEFAULT, 16)
|
| 90 |
temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)
|
| 91 |
tool_mode = st.toggle("Use NASA tools when relevant", value=True)
|
| 92 |
verbose_tools = st.toggle("Show tool payload snippets", value=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
st.divider()
|
| 94 |
st.subheader("NASA API Key")
|
| 95 |
-
st.write("Detected
|
|
|
|
| 96 |
st.divider()
|
| 97 |
if st.button("🧹 Clear chat"):
|
| 98 |
-
st.session_state.chat_history = [
|
|
|
|
|
|
|
| 99 |
st.rerun()
|
| 100 |
|
| 101 |
|
|
@@ -113,4 +138,333 @@ def load_local_llm(model_id: str):
|
|
| 113 |
tokenizer=tokenizer,
|
| 114 |
device=device,
|
| 115 |
)
|
| 116 |
-
return gen, ("cuda" if device == 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import os
|
| 4 |
import re
|
| 5 |
import json
|
|
|
|
| 6 |
import datetime as dt
|
| 7 |
from dataclasses import dataclass
|
| 8 |
from typing import Any, Dict, List, Optional, Tuple
|
|
|
|
| 15 |
|
| 16 |
|
| 17 |
# ----------------------------
|
| 18 |
+
# Environment / Config
|
| 19 |
# ----------------------------
|
| 20 |
NASA_API_KEY = os.getenv("NASA_API_KEY")
|
| 21 |
if not NASA_API_KEY:
|
| 22 |
raise ValueError("NASA_API_KEY is not set. Add it as an environment variable.")
|
| 23 |
|
|
|
|
|
|
|
|
|
|
| 24 |
MODEL_ID = os.getenv("HAL_MODEL_ID", "google/flan-t5-large")
|
| 25 |
MAX_NEW_TOKENS_DEFAULT = int(os.getenv("HAL_MAX_NEW_TOKENS", "420"))
|
| 26 |
TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.3"))
|
|
|
|
| 28 |
REQUEST_TIMEOUT_S = 20
|
| 29 |
|
| 30 |
|
| 31 |
+
# ----------------------------
|
| 32 |
+
# AGENT PROMPT INSTRUCTIONS
|
| 33 |
+
# ----------------------------
|
| 34 |
+
AGENT_INSTRUCTIONS = """
|
| 35 |
+
You are HAL, a NASA-focused research assistant.
|
| 36 |
+
|
| 37 |
+
MISSION
|
| 38 |
+
- Provide accurate, in-depth answers about NASA science, missions, spacecraft, astronomy, planetary science, and spaceflight.
|
| 39 |
+
- When NASA tool data is available, ground your claims in it.
|
| 40 |
+
|
| 41 |
+
TRUTHFULNESS & SAFETY RULES
|
| 42 |
+
- Do NOT invent facts, dates, mission events, or numbers.
|
| 43 |
+
- If you are uncertain or missing data, explicitly say what is unknown and what tool/query would verify it.
|
| 44 |
+
- Prefer TOOL_DATA over general knowledge when TOOL_DATA is relevant.
|
| 45 |
+
|
| 46 |
+
REASONING & DEPTH
|
| 47 |
+
- Explain concepts like a careful science educator:
|
| 48 |
+
- define key terms
|
| 49 |
+
- walk through mechanisms or causes
|
| 50 |
+
- give examples and analogies (only if they clarify)
|
| 51 |
+
- include important caveats
|
| 52 |
+
- If the question has multiple parts, answer each part clearly.
|
| 53 |
+
|
| 54 |
+
CITATION STYLE (LIGHTWEIGHT)
|
| 55 |
+
- When using TOOL_DATA, cite fields explicitly in-line, like:
|
| 56 |
+
- (tool=apod.date), (tool=apod.title), (tool=mars_photos.sample[0].camera.full_name)
|
| 57 |
+
- Do not fabricate citations; only cite fields present in TOOL_DATA.
|
| 58 |
+
|
| 59 |
+
OUTPUT FORMAT (REQUIRED)
|
| 60 |
+
Return your response in EXACTLY this structure:
|
| 61 |
+
|
| 62 |
+
## Direct Answer
|
| 63 |
+
(1–4 paragraphs directly answering the question)
|
| 64 |
+
|
| 65 |
+
## Key Details & Evidence
|
| 66 |
+
- Bullet list of key points and the supporting TOOL_DATA fields (when available)
|
| 67 |
+
|
| 68 |
+
## If You Want to Go Deeper
|
| 69 |
+
- 3–6 suggested follow-up questions or next steps
|
| 70 |
+
""".strip()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
# ----------------------------
|
| 74 |
# Streamlit Setup
|
| 75 |
# ----------------------------
|
| 76 |
st.set_page_config(page_title="HAL - NASA ChatBot", page_icon="🚀", layout="centered")
|
| 77 |
|
| 78 |
+
st.title("HAL — NASA AI Assistant")
|
| 79 |
st.caption("Tool-augmented NASA chatbot (APOD • Mars Rovers • NEOs • Earth Imagery • NASA Image Search)")
|
| 80 |
|
| 81 |
st.markdown(
|
|
|
|
| 101 |
)
|
| 102 |
|
| 103 |
with st.sidebar:
|
| 104 |
+
st.header("Controls")
|
| 105 |
max_new_tokens = st.slider("Max new tokens", 64, 900, MAX_NEW_TOKENS_DEFAULT, 16)
|
| 106 |
temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)
|
| 107 |
tool_mode = st.toggle("Use NASA tools when relevant", value=True)
|
| 108 |
verbose_tools = st.toggle("Show tool payload snippets", value=False)
|
| 109 |
+
|
| 110 |
+
st.divider()
|
| 111 |
+
st.subheader("Model")
|
| 112 |
+
st.code(MODEL_ID)
|
| 113 |
+
st.write("Device:", "cuda" if torch.cuda.is_available() else "cpu")
|
| 114 |
+
|
| 115 |
st.divider()
|
| 116 |
st.subheader("NASA API Key")
|
| 117 |
+
st.write("Detected" if bool(NASA_API_KEY) else "Missing ❌")
|
| 118 |
+
|
| 119 |
st.divider()
|
| 120 |
if st.button("🧹 Clear chat"):
|
| 121 |
+
st.session_state.chat_history = [
|
| 122 |
+
{"role": "assistant", "content": "Hello! Ask me anything about NASA missions, astronomy, Mars rovers, near-Earth objects, or today's APOD."}
|
| 123 |
+
]
|
| 124 |
st.rerun()
|
| 125 |
|
| 126 |
|
|
|
|
| 138 |
tokenizer=tokenizer,
|
| 139 |
device=device,
|
| 140 |
)
|
| 141 |
+
return gen, ("cuda" if device == 0 else "cpu")
|
| 142 |
+
|
| 143 |
+
pipe, device_name = load_local_llm(MODEL_ID)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
# ----------------------------
|
| 147 |
+
# Chat history
|
| 148 |
+
# ----------------------------
|
| 149 |
+
if "chat_history" not in st.session_state:
|
| 150 |
+
st.session_state.chat_history = [
|
| 151 |
+
{"role": "assistant", "content": "Hello! Ask me anything about NASA missions, astronomy, Mars rovers, near-Earth objects, or today's APOD."}
|
| 152 |
+
]
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# ----------------------------
|
| 156 |
+
# Utilities
|
| 157 |
+
# ----------------------------
|
| 158 |
+
def ensure_english(text: str) -> str:
|
| 159 |
+
try:
|
| 160 |
+
if detect(text) != "en":
|
| 161 |
+
return "I can help best in English right now. Could you rephrase your question in English?"
|
| 162 |
+
except Exception:
|
| 163 |
+
pass
|
| 164 |
+
return text
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def safe_get(url: str, params: Optional[Dict[str, Any]] = None, timeout: int = REQUEST_TIMEOUT_S) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
|
| 168 |
+
try:
|
| 169 |
+
r = requests.get(url, params=params, timeout=timeout)
|
| 170 |
+
if r.status_code != 200:
|
| 171 |
+
return None, f"HTTP {r.status_code}: {r.text[:300]}"
|
| 172 |
+
return r.json(), None
|
| 173 |
+
except Exception as e:
|
| 174 |
+
return None, str(e)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def iso_date(s: str) -> Optional[str]:
|
| 178 |
+
try:
|
| 179 |
+
dt.datetime.strptime(s, "%Y-%m-%d")
|
| 180 |
+
return s
|
| 181 |
+
except Exception:
|
| 182 |
+
return None
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def clamp_history(history: List[Dict[str, str]], n: int = 8) -> List[Dict[str, str]]:
|
| 186 |
+
return history[-n:]
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def pretty_json_snip(obj: Any, limit: int = 900) -> str:
|
| 190 |
+
try:
|
| 191 |
+
s = json.dumps(obj, indent=2, ensure_ascii=False)
|
| 192 |
+
return s[:limit] + ("…" if len(s) > limit else "")
|
| 193 |
+
except Exception:
|
| 194 |
+
return str(obj)[:limit] + "…"
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
# ----------------------------
|
| 198 |
+
# NASA Tools (APIs)
|
| 199 |
+
# ----------------------------
|
| 200 |
+
NASA_BASE = "https://api.nasa.gov"
|
| 201 |
+
|
| 202 |
+
def nasa_apod(date: Optional[str] = None) -> Dict[str, Any]:
|
| 203 |
+
params = {"api_key": NASA_API_KEY}
|
| 204 |
+
if date:
|
| 205 |
+
params["date"] = date
|
| 206 |
+
data, err = safe_get(f"{NASA_BASE}/planetary/apod", params=params)
|
| 207 |
+
return {"tool": "apod", "ok": bool(data), "error": err, "data": data}
|
| 208 |
+
|
| 209 |
+
def nasa_mars_photos(rover: str = "curiosity", sol: Optional[int] = None, earth_date: Optional[str] = None, camera: Optional[str] = None, page: int = 1) -> Dict[str, Any]:
|
| 210 |
+
rover = rover.lower().strip()
|
| 211 |
+
if rover not in {"curiosity", "opportunity", "spirit", "perseverance"}:
|
| 212 |
+
rover = "curiosity"
|
| 213 |
+
|
| 214 |
+
params: Dict[str, Any] = {"api_key": NASA_API_KEY, "page": page}
|
| 215 |
+
if sol is not None:
|
| 216 |
+
params["sol"] = int(sol)
|
| 217 |
+
elif earth_date:
|
| 218 |
+
params["earth_date"] = earth_date
|
| 219 |
+
else:
|
| 220 |
+
params["sol"] = 1000
|
| 221 |
+
|
| 222 |
+
if camera:
|
| 223 |
+
params["camera"] = camera
|
| 224 |
+
|
| 225 |
+
url = f"{NASA_BASE}/mars-photos/api/v1/rovers/{rover}/photos"
|
| 226 |
+
data, err = safe_get(url, params=params)
|
| 227 |
+
return {"tool": "mars_photos", "ok": bool(data), "error": err, "data": data, "meta": {"rover": rover, "params": params}}
|
| 228 |
+
|
| 229 |
+
def nasa_neo_feed(start_date: str, end_date: str) -> Dict[str, Any]:
|
| 230 |
+
params = {"api_key": NASA_API_KEY, "start_date": start_date, "end_date": end_date}
|
| 231 |
+
data, err = safe_get(f"{NASA_BASE}/neo/rest/v1/feed", params=params)
|
| 232 |
+
return {"tool": "neo_feed", "ok": bool(data), "error": err, "data": data, "meta": {"start_date": start_date, "end_date": end_date}}
|
| 233 |
+
|
| 234 |
+
def nasa_earth_imagery(lat: float, lon: float, date: Optional[str] = None, dim: float = 0.15) -> Dict[str, Any]:
|
| 235 |
+
params: Dict[str, Any] = {"api_key": NASA_API_KEY, "lat": lat, "lon": lon, "dim": dim}
|
| 236 |
+
if date:
|
| 237 |
+
params["date"] = date
|
| 238 |
+
data, err = safe_get(f"{NASA_BASE}/planetary/earth/imagery", params=params)
|
| 239 |
+
return {"tool": "earth_imagery", "ok": bool(data), "error": err, "data": data, "meta": params}
|
| 240 |
+
|
| 241 |
+
def nasa_image_search(q: str, media_type: Optional[str] = None) -> Dict[str, Any]:
|
| 242 |
+
params: Dict[str, Any] = {"q": q}
|
| 243 |
+
if media_type:
|
| 244 |
+
params["media_type"] = media_type
|
| 245 |
+
data, err = safe_get("https://images-api.nasa.gov/search", params=params)
|
| 246 |
+
return {"tool": "image_search", "ok": bool(data), "error": err, "data": data, "meta": params}
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
# ----------------------------
|
| 250 |
+
# Tool Router (simple intent detection)
|
| 251 |
+
# ----------------------------
|
| 252 |
+
@dataclass
|
| 253 |
+
class ToolPlan:
|
| 254 |
+
tools: List[Dict[str, Any]]
|
| 255 |
+
notes: List[str]
|
| 256 |
+
|
| 257 |
+
def plan_tools(user_text: str) -> ToolPlan:
|
| 258 |
+
t = user_text.lower()
|
| 259 |
+
tools: List[Dict[str, Any]] = []
|
| 260 |
+
notes: List[str] = []
|
| 261 |
+
|
| 262 |
+
# APOD
|
| 263 |
+
if "apod" in t or "astronomy picture of the day" in t or "picture of the day" in t:
|
| 264 |
+
m = re.search(r"(\d{4}-\d{2}-\d{2})", user_text)
|
| 265 |
+
date = iso_date(m.group(1)) if m else None
|
| 266 |
+
tools.append(nasa_apod(date=date))
|
| 267 |
+
notes.append("Fetched NASA APOD data to ground the response.")
|
| 268 |
+
|
| 269 |
+
# Mars Rover Photos
|
| 270 |
+
rover = None
|
| 271 |
+
for r in ["perseverance", "curiosity", "opportunity", "spirit"]:
|
| 272 |
+
if r in t:
|
| 273 |
+
rover = r
|
| 274 |
+
break
|
| 275 |
+
|
| 276 |
+
if rover or ("mars rover" in t and ("photo" in t or "image" in t)):
|
| 277 |
+
sol = None
|
| 278 |
+
msol = re.search(r"\bsol\s*(\d+)\b", t)
|
| 279 |
+
if msol:
|
| 280 |
+
sol = int(msol.group(1))
|
| 281 |
+
|
| 282 |
+
mdate = re.search(r"(\d{4}-\d{2}-\d{2})", user_text)
|
| 283 |
+
earth_date = iso_date(mdate.group(1)) if mdate else None
|
| 284 |
+
|
| 285 |
+
cam = None
|
| 286 |
+
mcam = re.search(r"\bcamera\s*[:=]?\s*([a-zA-Z0-9_]+)\b", t)
|
| 287 |
+
if mcam:
|
| 288 |
+
cam = mcam.group(1)
|
| 289 |
+
|
| 290 |
+
tools.append(nasa_mars_photos(rover=rover or "curiosity", sol=sol, earth_date=earth_date, camera=cam, page=1))
|
| 291 |
+
notes.append("Fetched Mars rover photos metadata from NASA.")
|
| 292 |
+
|
| 293 |
+
# NEO Feed
|
| 294 |
+
if any(k in t for k in ["asteroid", "near-earth", "near earth", "neo", "potentially hazardous"]):
|
| 295 |
+
dates = re.findall(r"(\d{4}-\d{2}-\d{2})", user_text)
|
| 296 |
+
if len(dates) >= 2 and iso_date(dates[0]) and iso_date(dates[1]):
|
| 297 |
+
start, end = dates[0], dates[1]
|
| 298 |
+
else:
|
| 299 |
+
end_dt = dt.date.today()
|
| 300 |
+
start_dt = end_dt - dt.timedelta(days=2)
|
| 301 |
+
start, end = start_dt.isoformat(), end_dt.isoformat()
|
| 302 |
+
notes.append("No explicit date range found; used the last 3 days for the NEO feed.")
|
| 303 |
+
tools.append(nasa_neo_feed(start_date=start, end_date=end))
|
| 304 |
+
notes.append("Fetched NASA NEO feed data for the requested range.")
|
| 305 |
+
|
| 306 |
+
# Earth imagery (coordinates)
|
| 307 |
+
if "earth imagery" in t or "satellite imagery" in t or ("earth" in t and "imagery" in t):
|
| 308 |
+
m = re.search(r"(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)", user_text)
|
| 309 |
+
if m:
|
| 310 |
+
lat = float(m.group(1))
|
| 311 |
+
lon = float(m.group(2))
|
| 312 |
+
mdate = re.search(r"(\d{4}-\d{2}-\d{2})", user_text)
|
| 313 |
+
edate = iso_date(mdate.group(1)) if mdate else None
|
| 314 |
+
tools.append(nasa_earth_imagery(lat=lat, lon=lon, date=edate))
|
| 315 |
+
notes.append("Fetched NASA Earth imagery metadata based on provided coordinates.")
|
| 316 |
+
|
| 317 |
+
# NASA image search
|
| 318 |
+
if ("search" in t or "images" in t or "photos" in t or "footage" in t) and not tools:
|
| 319 |
+
q = user_text.strip()
|
| 320 |
+
if len(q) > 120:
|
| 321 |
+
q = q[:120]
|
| 322 |
+
tools.append(nasa_image_search(q=q))
|
| 323 |
+
notes.append("Used NASA Image and Video Library search to ground results.")
|
| 324 |
+
|
| 325 |
+
return ToolPlan(tools=tools, notes=notes)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
# ----------------------------
|
| 329 |
+
# Prompt Builder (AGENT_INSTRUCTIONS + context + tool data)
|
| 330 |
+
# ----------------------------
|
| 331 |
+
def build_prompt(user_text: str, history: List[Dict[str, str]], tool_results: List[Dict[str, Any]]) -> str:
|
| 332 |
+
history_compact = clamp_history(history, n=8)
|
| 333 |
+
history_block = "\n".join([f"{m['role'].upper()}: {m['content']}" for m in history_compact])
|
| 334 |
+
|
| 335 |
+
tool_blocks: List[str] = []
|
| 336 |
+
for tr in tool_results:
|
| 337 |
+
tool_name = tr.get("tool", "tool")
|
| 338 |
+
ok = tr.get("ok", False)
|
| 339 |
+
err = tr.get("error")
|
| 340 |
+
data = tr.get("data")
|
| 341 |
+
meta = tr.get("meta")
|
| 342 |
+
|
| 343 |
+
snippet: Dict[str, Any] = {
|
| 344 |
+
"tool": tool_name,
|
| 345 |
+
"ok": ok,
|
| 346 |
+
"error": err,
|
| 347 |
+
"meta": meta,
|
| 348 |
+
"data_snippet": data,
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
# Reduce large payloads
|
| 352 |
+
if tool_name == "neo_feed" and isinstance(data, dict):
|
| 353 |
+
neo = data.get("near_earth_objects", {})
|
| 354 |
+
small = {}
|
| 355 |
+
for k, v in list(neo.items())[:2]:
|
| 356 |
+
small[k] = v[:3] if isinstance(v, list) else v
|
| 357 |
+
snippet["data_snippet"] = {
|
| 358 |
+
"element_count": data.get("element_count"),
|
| 359 |
+
"near_earth_objects_sample": small,
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
if tool_name == "mars_photos" and isinstance(data, dict):
|
| 363 |
+
photos = data.get("photos", []) or []
|
| 364 |
+
snippet["data_snippet"] = {
|
| 365 |
+
"count": len(photos),
|
| 366 |
+
"sample": photos[:3],
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
if tool_name == "image_search" and isinstance(data, dict):
|
| 370 |
+
coll = data.get("collection", {}) or {}
|
| 371 |
+
items = coll.get("items", []) or []
|
| 372 |
+
snippet["data_snippet"] = {
|
| 373 |
+
"items_count": len(items),
|
| 374 |
+
"items_sample": items[:2],
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
if tool_name == "apod" and isinstance(data, dict):
|
| 378 |
+
keep = {k: data.get(k) for k in ["date", "title", "explanation", "media_type", "url", "hdurl", "copyright"]}
|
| 379 |
+
snippet["data_snippet"] = keep
|
| 380 |
+
|
| 381 |
+
tool_blocks.append(pretty_json_snip(snippet, limit=1600))
|
| 382 |
+
|
| 383 |
+
tools_block = "\n\n".join(tool_blocks) if tool_blocks else "None"
|
| 384 |
+
|
| 385 |
+
prompt = f"""
|
| 386 |
+
{AGENT_INSTRUCTIONS}
|
| 387 |
+
|
| 388 |
+
CONVERSATION CONTEXT
|
| 389 |
+
{history_block}
|
| 390 |
+
|
| 391 |
+
TOOL_DATA (JSON excerpts; may be None)
|
| 392 |
+
{tools_block}
|
| 393 |
+
|
| 394 |
+
USER QUESTION
|
| 395 |
+
{user_text}
|
| 396 |
+
|
| 397 |
+
Now produce the formatted answer.
|
| 398 |
+
""".strip()
|
| 399 |
+
|
| 400 |
+
return prompt
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def generate_with_flan(prompt: str, max_new_tokens: int, temperature: float) -> str:
|
| 404 |
+
try:
|
| 405 |
+
out = pipe(
|
| 406 |
+
prompt,
|
| 407 |
+
max_new_tokens=int(max_new_tokens),
|
| 408 |
+
do_sample=bool(temperature and temperature > 0),
|
| 409 |
+
temperature=float(temperature) if temperature and temperature > 0 else 0.0,
|
| 410 |
+
top_p=0.9,
|
| 411 |
+
)
|
| 412 |
+
if isinstance(out, list) and out:
|
| 413 |
+
return (out[0].get("generated_text") or "").strip()
|
| 414 |
+
return str(out).strip()
|
| 415 |
+
except Exception as e:
|
| 416 |
+
return f"Model error: {e}"
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def get_response(user_text: str, *, tool_mode: bool, max_new_tokens: int, temperature: float, verbose_tools: bool) -> str:
|
| 420 |
+
user_text = ensure_english(user_text)
|
| 421 |
+
if user_text.startswith(""):
|
| 422 |
+
return user_text
|
| 423 |
+
|
| 424 |
+
tool_results: List[Dict[str, Any]] = []
|
| 425 |
+
tool_notes: List[str] = []
|
| 426 |
+
|
| 427 |
+
if tool_mode:
|
| 428 |
+
plan = plan_tools(user_text)
|
| 429 |
+
tool_results = plan.tools
|
| 430 |
+
tool_notes = plan.notes
|
| 431 |
+
|
| 432 |
+
prompt = build_prompt(user_text, st.session_state.chat_history, tool_results)
|
| 433 |
+
answer = generate_with_flan(prompt, max_new_tokens=max_new_tokens, temperature=temperature)
|
| 434 |
+
|
| 435 |
+
if verbose_tools and tool_results:
|
| 436 |
+
dbg = "\n\n---\n### Tool Debug (snippets)\n"
|
| 437 |
+
if tool_notes:
|
| 438 |
+
dbg += "\n".join([f"- {n}" for n in tool_notes]) + "\n"
|
| 439 |
+
for tr in tool_results:
|
| 440 |
+
dbg += f"\n**{tr.get('tool','tool')}** ok={tr.get('ok')} error={tr.get('error')}\n"
|
| 441 |
+
dbg += f"```json\n{pretty_json_snip(tr.get('data'), limit=900)}\n```\n"
|
| 442 |
+
answer += dbg
|
| 443 |
+
|
| 444 |
+
return answer
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
# ----------------------------
|
| 448 |
+
# Chat UI loop
|
| 449 |
+
# ----------------------------
|
| 450 |
+
user_input = st.chat_input("Ask a NASA question… (e.g., 'What is APOD today?' or 'Show Perseverance photos from sol 100')")
|
| 451 |
+
|
| 452 |
+
if user_input:
|
| 453 |
+
st.session_state.chat_history.append({"role": "user", "content": user_input})
|
| 454 |
+
with st.spinner("HAL is thinking…"):
|
| 455 |
+
resp = get_response(
|
| 456 |
+
user_input,
|
| 457 |
+
tool_mode=tool_mode,
|
| 458 |
+
max_new_tokens=max_new_tokens,
|
| 459 |
+
temperature=temperature,
|
| 460 |
+
verbose_tools=verbose_tools,
|
| 461 |
+
)
|
| 462 |
+
st.session_state.chat_history.append({"role": "assistant", "content": resp})
|
| 463 |
+
|
| 464 |
+
st.markdown("<div class='container'>", unsafe_allow_html=True)
|
| 465 |
+
for message in st.session_state.chat_history:
|
| 466 |
+
if message["role"] == "user":
|
| 467 |
+
st.markdown(f"<div class='user-msg'><strong>You:</strong> {message['content']}</div>", unsafe_allow_html=True)
|
| 468 |
+
else:
|
| 469 |
+
st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {message['content']}</div>", unsafe_allow_html=True)
|
| 470 |
+
st.markdown("</div>", unsafe_allow_html=True)
|