Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
import os
|
|
@@ -24,12 +35,11 @@ if not NASA_API_KEY:
|
|
| 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"))
|
| 27 |
-
|
| 28 |
REQUEST_TIMEOUT_S = 20
|
| 29 |
|
| 30 |
|
| 31 |
# ----------------------------
|
| 32 |
-
#
|
| 33 |
# ----------------------------
|
| 34 |
AGENT_INSTRUCTIONS = """
|
| 35 |
You are HAL, a NASA-focused research assistant.
|
|
@@ -38,31 +48,31 @@ 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
|
| 42 |
-
- Do
|
| 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 |
-
|
| 47 |
- Explain concepts like a careful science educator:
|
| 48 |
- define key terms
|
| 49 |
-
-
|
| 50 |
-
- give examples
|
| 51 |
- include important caveats
|
| 52 |
- If the question has multiple parts, answer each part clearly.
|
| 53 |
|
| 54 |
-
|
| 55 |
- When using TOOL_DATA, cite fields explicitly in-line, like:
|
| 56 |
-
|
| 57 |
-
-
|
| 58 |
|
| 59 |
OUTPUT FORMAT (REQUIRED)
|
| 60 |
-
Return your response in
|
| 61 |
|
| 62 |
## Direct Answer
|
| 63 |
(1–4 paragraphs directly answering the question)
|
| 64 |
|
| 65 |
-
## Key Details
|
| 66 |
- Bullet list of key points and the supporting TOOL_DATA fields (when available)
|
| 67 |
|
| 68 |
## If You Want to Go Deeper
|
|
@@ -71,12 +81,12 @@ Return your response in EXACTLY this structure:
|
|
| 71 |
|
| 72 |
|
| 73 |
# ----------------------------
|
| 74 |
-
# Streamlit
|
| 75 |
# ----------------------------
|
| 76 |
-
st.set_page_config(page_title="HAL - NASA ChatBot", page_icon="
|
| 77 |
|
| 78 |
st.title("HAL — NASA AI Assistant")
|
| 79 |
-
st.caption("Tool-augmented NASA chatbot (APOD
|
| 80 |
|
| 81 |
st.markdown(
|
| 82 |
"""
|
|
@@ -114,31 +124,36 @@ with st.sidebar:
|
|
| 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("
|
| 121 |
st.session_state.chat_history = [
|
| 122 |
-
{"role": "assistant", "content": "Hello
|
| 123 |
]
|
| 124 |
st.rerun()
|
| 125 |
|
| 126 |
|
| 127 |
# ----------------------------
|
| 128 |
-
# Model
|
| 129 |
# ----------------------------
|
| 130 |
@st.cache_resource(show_spinner=True)
|
| 131 |
def load_local_llm(model_id: str):
|
| 132 |
device = 0 if torch.cuda.is_available() else -1
|
|
|
|
| 133 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 134 |
model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
|
|
|
|
| 135 |
gen = pipeline(
|
| 136 |
"text2text-generation",
|
| 137 |
model=model,
|
| 138 |
tokenizer=tokenizer,
|
| 139 |
device=device,
|
| 140 |
)
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
pipe, device_name = load_local_llm(MODEL_ID)
|
| 144 |
|
|
@@ -148,7 +163,7 @@ pipe, device_name = load_local_llm(MODEL_ID)
|
|
| 148 |
# ----------------------------
|
| 149 |
if "chat_history" not in st.session_state:
|
| 150 |
st.session_state.chat_history = [
|
| 151 |
-
{"role": "assistant", "content": "Hello
|
| 152 |
]
|
| 153 |
|
| 154 |
|
|
@@ -158,13 +173,17 @@ if "chat_history" not in st.session_state:
|
|
| 158 |
def ensure_english(text: str) -> str:
|
| 159 |
try:
|
| 160 |
if detect(text) != "en":
|
| 161 |
-
return "I can help best in English right now.
|
| 162 |
except Exception:
|
| 163 |
pass
|
| 164 |
return text
|
| 165 |
|
| 166 |
|
| 167 |
-
def safe_get(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
try:
|
| 169 |
r = requests.get(url, params=params, timeout=timeout)
|
| 170 |
if r.status_code != 200:
|
|
@@ -189,16 +208,17 @@ def clamp_history(history: List[Dict[str, str]], n: int = 8) -> List[Dict[str, s
|
|
| 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] + ("
|
| 193 |
except Exception:
|
| 194 |
-
return str(obj)[:limit] + "
|
| 195 |
|
| 196 |
|
| 197 |
# ----------------------------
|
| 198 |
-
# NASA
|
| 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:
|
|
@@ -206,7 +226,14 @@ def nasa_apod(date: Optional[str] = None) -> Dict[str, Any]:
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
rover = rover.lower().strip()
|
| 211 |
if rover not in {"curiosity", "opportunity", "spirit", "perseverance"}:
|
| 212 |
rover = "curiosity"
|
|
@@ -226,11 +253,13 @@ def nasa_mars_photos(rover: str = "curiosity", sol: Optional[int] = None, earth_
|
|
| 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:
|
|
@@ -238,6 +267,7 @@ def nasa_earth_imagery(lat: float, lon: float, date: Optional[str] = None, dim:
|
|
| 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:
|
|
@@ -247,13 +277,14 @@ def nasa_image_search(q: str, media_type: Optional[str] = None) -> Dict[str, Any
|
|
| 247 |
|
| 248 |
|
| 249 |
# ----------------------------
|
| 250 |
-
# Tool
|
| 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]] = []
|
|
@@ -264,9 +295,9 @@ def plan_tools(user_text: str) -> ToolPlan:
|
|
| 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
|
| 268 |
|
| 269 |
-
# Mars
|
| 270 |
rover = None
|
| 271 |
for r in ["perseverance", "curiosity", "opportunity", "spirit"]:
|
| 272 |
if r in t:
|
|
@@ -288,9 +319,9 @@ def plan_tools(user_text: str) -> ToolPlan:
|
|
| 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
|
| 292 |
|
| 293 |
-
# NEO
|
| 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]):
|
|
@@ -299,11 +330,12 @@ def plan_tools(user_text: str) -> ToolPlan:
|
|
| 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
|
|
|
|
| 303 |
tools.append(nasa_neo_feed(start_date=start, end_date=end))
|
| 304 |
-
notes.append("Fetched
|
| 305 |
|
| 306 |
-
# Earth imagery (
|
| 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:
|
|
@@ -312,7 +344,7 @@ def plan_tools(user_text: str) -> ToolPlan:
|
|
| 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
|
| 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:
|
|
@@ -320,13 +352,13 @@ def plan_tools(user_text: str) -> ToolPlan:
|
|
| 320 |
if len(q) > 120:
|
| 321 |
q = q[:120]
|
| 322 |
tools.append(nasa_image_search(q=q))
|
| 323 |
-
notes.append("
|
| 324 |
|
| 325 |
return ToolPlan(tools=tools, notes=notes)
|
| 326 |
|
| 327 |
|
| 328 |
# ----------------------------
|
| 329 |
-
# Prompt
|
| 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)
|
|
@@ -350,8 +382,8 @@ def build_prompt(user_text: str, history: List[Dict[str, str]], tool_results: Li
|
|
| 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"] = {
|
|
@@ -416,9 +448,16 @@ def generate_with_flan(prompt: str, max_new_tokens: int, temperature: float) ->
|
|
| 416 |
return f"Model error: {e}"
|
| 417 |
|
| 418 |
|
| 419 |
-
def get_response(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 420 |
user_text = ensure_english(user_text)
|
| 421 |
-
if user_text.startswith(""):
|
| 422 |
return user_text
|
| 423 |
|
| 424 |
tool_results: List[Dict[str, Any]] = []
|
|
@@ -433,12 +472,12 @@ def get_response(user_text: str, *, tool_mode: bool, max_new_tokens: int, temper
|
|
| 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---\
|
| 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
|
| 441 |
-
dbg += f"
|
| 442 |
answer += dbg
|
| 443 |
|
| 444 |
return answer
|
|
@@ -447,11 +486,11 @@ def get_response(user_text: str, *, tool_mode: bool, max_new_tokens: int, temper
|
|
| 447 |
# ----------------------------
|
| 448 |
# Chat UI loop
|
| 449 |
# ----------------------------
|
| 450 |
-
user_input = st.chat_input("Ask a NASA question
|
| 451 |
|
| 452 |
if user_input:
|
| 453 |
st.session_state.chat_history.append({"role": "user", "content": user_input})
|
| 454 |
-
with st.spinner("
|
| 455 |
resp = get_response(
|
| 456 |
user_input,
|
| 457 |
tool_mode=tool_mode,
|
|
|
|
| 1 |
+
# file: app.py
|
| 2 |
+
"""
|
| 3 |
+
HAL — NASA Chatbot (Streamlit)
|
| 4 |
+
|
| 5 |
+
Functional Streamlit chatbot with:
|
| 6 |
+
- A single, editable prompt block (AGENT_INSTRUCTIONS)
|
| 7 |
+
- Tool augmentation using NASA APIs when relevant (APOD, Mars Rover Photos, NEO Feed, Earth Imagery, NASA Image Search)
|
| 8 |
+
- In-depth, structured answers with grounded evidence when tool data is available
|
| 9 |
+
- Local instruction-tuned model (Flan-T5) via transformers pipeline
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
from __future__ import annotations
|
| 13 |
|
| 14 |
import os
|
|
|
|
| 35 |
MODEL_ID = os.getenv("HAL_MODEL_ID", "google/flan-t5-large")
|
| 36 |
MAX_NEW_TOKENS_DEFAULT = int(os.getenv("HAL_MAX_NEW_TOKENS", "420"))
|
| 37 |
TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.3"))
|
|
|
|
| 38 |
REQUEST_TIMEOUT_S = 20
|
| 39 |
|
| 40 |
|
| 41 |
# ----------------------------
|
| 42 |
+
# Agent prompt instructions (edit this)
|
| 43 |
# ----------------------------
|
| 44 |
AGENT_INSTRUCTIONS = """
|
| 45 |
You are HAL, a NASA-focused research assistant.
|
|
|
|
| 48 |
- Provide accurate, in-depth answers about NASA science, missions, spacecraft, astronomy, planetary science, and spaceflight.
|
| 49 |
- When NASA tool data is available, ground your claims in it.
|
| 50 |
|
| 51 |
+
TRUTHFULNESS RULES
|
| 52 |
+
- Do not invent facts, dates, mission events, or numbers.
|
| 53 |
- If you are uncertain or missing data, explicitly say what is unknown and what tool/query would verify it.
|
| 54 |
- Prefer TOOL_DATA over general knowledge when TOOL_DATA is relevant.
|
| 55 |
|
| 56 |
+
DEPTH AND CLARITY
|
| 57 |
- Explain concepts like a careful science educator:
|
| 58 |
- define key terms
|
| 59 |
+
- explain mechanisms or causes
|
| 60 |
+
- give examples only if they clarify
|
| 61 |
- include important caveats
|
| 62 |
- If the question has multiple parts, answer each part clearly.
|
| 63 |
|
| 64 |
+
EVIDENCE REFERENCES
|
| 65 |
- When using TOOL_DATA, cite fields explicitly in-line, like:
|
| 66 |
+
(tool=apod.date), (tool=apod.title), (tool=mars_photos.sample[0].camera.full_name)
|
| 67 |
+
- Only cite fields that appear in TOOL_DATA.
|
| 68 |
|
| 69 |
OUTPUT FORMAT (REQUIRED)
|
| 70 |
+
Return your response in exactly this structure:
|
| 71 |
|
| 72 |
## Direct Answer
|
| 73 |
(1–4 paragraphs directly answering the question)
|
| 74 |
|
| 75 |
+
## Key Details and Evidence
|
| 76 |
- Bullet list of key points and the supporting TOOL_DATA fields (when available)
|
| 77 |
|
| 78 |
## If You Want to Go Deeper
|
|
|
|
| 81 |
|
| 82 |
|
| 83 |
# ----------------------------
|
| 84 |
+
# Streamlit setup
|
| 85 |
# ----------------------------
|
| 86 |
+
st.set_page_config(page_title="HAL - NASA ChatBot", page_icon=" ", layout="centered")
|
| 87 |
|
| 88 |
st.title("HAL — NASA AI Assistant")
|
| 89 |
+
st.caption("Tool-augmented NASA chatbot (APOD, Mars Rovers, NEOs, Earth Imagery, NASA Image Search)")
|
| 90 |
|
| 91 |
st.markdown(
|
| 92 |
"""
|
|
|
|
| 124 |
|
| 125 |
st.divider()
|
| 126 |
st.subheader("NASA API Key")
|
| 127 |
+
st.write("Detected" if bool(NASA_API_KEY) else "Missing")
|
| 128 |
|
| 129 |
st.divider()
|
| 130 |
+
if st.button("Clear chat"):
|
| 131 |
st.session_state.chat_history = [
|
| 132 |
+
{"role": "assistant", "content": "Hello. Ask me anything about NASA missions, astronomy, Mars rovers, near-Earth objects, or APOD."}
|
| 133 |
]
|
| 134 |
st.rerun()
|
| 135 |
|
| 136 |
|
| 137 |
# ----------------------------
|
| 138 |
+
# Model loading (cached)
|
| 139 |
# ----------------------------
|
| 140 |
@st.cache_resource(show_spinner=True)
|
| 141 |
def load_local_llm(model_id: str):
|
| 142 |
device = 0 if torch.cuda.is_available() else -1
|
| 143 |
+
|
| 144 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 145 |
model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
|
| 146 |
+
|
| 147 |
gen = pipeline(
|
| 148 |
"text2text-generation",
|
| 149 |
model=model,
|
| 150 |
tokenizer=tokenizer,
|
| 151 |
device=device,
|
| 152 |
)
|
| 153 |
+
|
| 154 |
+
device_name = "cuda" if device == 0 else "cpu"
|
| 155 |
+
return gen, device_name
|
| 156 |
+
|
| 157 |
|
| 158 |
pipe, device_name = load_local_llm(MODEL_ID)
|
| 159 |
|
|
|
|
| 163 |
# ----------------------------
|
| 164 |
if "chat_history" not in st.session_state:
|
| 165 |
st.session_state.chat_history = [
|
| 166 |
+
{"role": "assistant", "content": "Hello. Ask me anything about NASA missions, astronomy, Mars rovers, near-Earth objects, or APOD."}
|
| 167 |
]
|
| 168 |
|
| 169 |
|
|
|
|
| 173 |
def ensure_english(text: str) -> str:
|
| 174 |
try:
|
| 175 |
if detect(text) != "en":
|
| 176 |
+
return "I can help best in English right now. Please rephrase your question in English."
|
| 177 |
except Exception:
|
| 178 |
pass
|
| 179 |
return text
|
| 180 |
|
| 181 |
|
| 182 |
+
def safe_get(
|
| 183 |
+
url: str,
|
| 184 |
+
params: Optional[Dict[str, Any]] = None,
|
| 185 |
+
timeout: int = REQUEST_TIMEOUT_S,
|
| 186 |
+
) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
|
| 187 |
try:
|
| 188 |
r = requests.get(url, params=params, timeout=timeout)
|
| 189 |
if r.status_code != 200:
|
|
|
|
| 208 |
def pretty_json_snip(obj: Any, limit: int = 900) -> str:
|
| 209 |
try:
|
| 210 |
s = json.dumps(obj, indent=2, ensure_ascii=False)
|
| 211 |
+
return s[:limit] + ("..." if len(s) > limit else "")
|
| 212 |
except Exception:
|
| 213 |
+
return str(obj)[:limit] + "..."
|
| 214 |
|
| 215 |
|
| 216 |
# ----------------------------
|
| 217 |
+
# NASA tools
|
| 218 |
# ----------------------------
|
| 219 |
NASA_BASE = "https://api.nasa.gov"
|
| 220 |
|
| 221 |
+
|
| 222 |
def nasa_apod(date: Optional[str] = None) -> Dict[str, Any]:
|
| 223 |
params = {"api_key": NASA_API_KEY}
|
| 224 |
if date:
|
|
|
|
| 226 |
data, err = safe_get(f"{NASA_BASE}/planetary/apod", params=params)
|
| 227 |
return {"tool": "apod", "ok": bool(data), "error": err, "data": data}
|
| 228 |
|
| 229 |
+
|
| 230 |
+
def nasa_mars_photos(
|
| 231 |
+
rover: str = "curiosity",
|
| 232 |
+
sol: Optional[int] = None,
|
| 233 |
+
earth_date: Optional[str] = None,
|
| 234 |
+
camera: Optional[str] = None,
|
| 235 |
+
page: int = 1,
|
| 236 |
+
) -> Dict[str, Any]:
|
| 237 |
rover = rover.lower().strip()
|
| 238 |
if rover not in {"curiosity", "opportunity", "spirit", "perseverance"}:
|
| 239 |
rover = "curiosity"
|
|
|
|
| 253 |
data, err = safe_get(url, params=params)
|
| 254 |
return {"tool": "mars_photos", "ok": bool(data), "error": err, "data": data, "meta": {"rover": rover, "params": params}}
|
| 255 |
|
| 256 |
+
|
| 257 |
def nasa_neo_feed(start_date: str, end_date: str) -> Dict[str, Any]:
|
| 258 |
params = {"api_key": NASA_API_KEY, "start_date": start_date, "end_date": end_date}
|
| 259 |
data, err = safe_get(f"{NASA_BASE}/neo/rest/v1/feed", params=params)
|
| 260 |
return {"tool": "neo_feed", "ok": bool(data), "error": err, "data": data, "meta": {"start_date": start_date, "end_date": end_date}}
|
| 261 |
|
| 262 |
+
|
| 263 |
def nasa_earth_imagery(lat: float, lon: float, date: Optional[str] = None, dim: float = 0.15) -> Dict[str, Any]:
|
| 264 |
params: Dict[str, Any] = {"api_key": NASA_API_KEY, "lat": lat, "lon": lon, "dim": dim}
|
| 265 |
if date:
|
|
|
|
| 267 |
data, err = safe_get(f"{NASA_BASE}/planetary/earth/imagery", params=params)
|
| 268 |
return {"tool": "earth_imagery", "ok": bool(data), "error": err, "data": data, "meta": params}
|
| 269 |
|
| 270 |
+
|
| 271 |
def nasa_image_search(q: str, media_type: Optional[str] = None) -> Dict[str, Any]:
|
| 272 |
params: Dict[str, Any] = {"q": q}
|
| 273 |
if media_type:
|
|
|
|
| 277 |
|
| 278 |
|
| 279 |
# ----------------------------
|
| 280 |
+
# Tool router (simple intent detection)
|
| 281 |
# ----------------------------
|
| 282 |
@dataclass
|
| 283 |
class ToolPlan:
|
| 284 |
tools: List[Dict[str, Any]]
|
| 285 |
notes: List[str]
|
| 286 |
|
| 287 |
+
|
| 288 |
def plan_tools(user_text: str) -> ToolPlan:
|
| 289 |
t = user_text.lower()
|
| 290 |
tools: List[Dict[str, Any]] = []
|
|
|
|
| 295 |
m = re.search(r"(\d{4}-\d{2}-\d{2})", user_text)
|
| 296 |
date = iso_date(m.group(1)) if m else None
|
| 297 |
tools.append(nasa_apod(date=date))
|
| 298 |
+
notes.append("Fetched APOD data.")
|
| 299 |
|
| 300 |
+
# Mars rover photos
|
| 301 |
rover = None
|
| 302 |
for r in ["perseverance", "curiosity", "opportunity", "spirit"]:
|
| 303 |
if r in t:
|
|
|
|
| 319 |
cam = mcam.group(1)
|
| 320 |
|
| 321 |
tools.append(nasa_mars_photos(rover=rover or "curiosity", sol=sol, earth_date=earth_date, camera=cam, page=1))
|
| 322 |
+
notes.append("Fetched Mars rover photo metadata.")
|
| 323 |
|
| 324 |
+
# NEO feed
|
| 325 |
if any(k in t for k in ["asteroid", "near-earth", "near earth", "neo", "potentially hazardous"]):
|
| 326 |
dates = re.findall(r"(\d{4}-\d{2}-\d{2})", user_text)
|
| 327 |
if len(dates) >= 2 and iso_date(dates[0]) and iso_date(dates[1]):
|
|
|
|
| 330 |
end_dt = dt.date.today()
|
| 331 |
start_dt = end_dt - dt.timedelta(days=2)
|
| 332 |
start, end = start_dt.isoformat(), end_dt.isoformat()
|
| 333 |
+
notes.append("No date range found; used the last 3 days for the NEO feed.")
|
| 334 |
+
|
| 335 |
tools.append(nasa_neo_feed(start_date=start, end_date=end))
|
| 336 |
+
notes.append("Fetched NEO feed data.")
|
| 337 |
|
| 338 |
+
# Earth imagery (coords)
|
| 339 |
if "earth imagery" in t or "satellite imagery" in t or ("earth" in t and "imagery" in t):
|
| 340 |
m = re.search(r"(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)", user_text)
|
| 341 |
if m:
|
|
|
|
| 344 |
mdate = re.search(r"(\d{4}-\d{2}-\d{2})", user_text)
|
| 345 |
edate = iso_date(mdate.group(1)) if mdate else None
|
| 346 |
tools.append(nasa_earth_imagery(lat=lat, lon=lon, date=edate))
|
| 347 |
+
notes.append("Fetched Earth imagery metadata.")
|
| 348 |
|
| 349 |
# NASA image search
|
| 350 |
if ("search" in t or "images" in t or "photos" in t or "footage" in t) and not tools:
|
|
|
|
| 352 |
if len(q) > 120:
|
| 353 |
q = q[:120]
|
| 354 |
tools.append(nasa_image_search(q=q))
|
| 355 |
+
notes.append("Queried NASA image and video library search.")
|
| 356 |
|
| 357 |
return ToolPlan(tools=tools, notes=notes)
|
| 358 |
|
| 359 |
|
| 360 |
# ----------------------------
|
| 361 |
+
# Prompt builder
|
| 362 |
# ----------------------------
|
| 363 |
def build_prompt(user_text: str, history: List[Dict[str, str]], tool_results: List[Dict[str, Any]]) -> str:
|
| 364 |
history_compact = clamp_history(history, n=8)
|
|
|
|
| 382 |
|
| 383 |
# Reduce large payloads
|
| 384 |
if tool_name == "neo_feed" and isinstance(data, dict):
|
| 385 |
+
neo = data.get("near_earth_objects", {}) or {}
|
| 386 |
+
small: Dict[str, Any] = {}
|
| 387 |
for k, v in list(neo.items())[:2]:
|
| 388 |
small[k] = v[:3] if isinstance(v, list) else v
|
| 389 |
snippet["data_snippet"] = {
|
|
|
|
| 448 |
return f"Model error: {e}"
|
| 449 |
|
| 450 |
|
| 451 |
+
def get_response(
|
| 452 |
+
user_text: str,
|
| 453 |
+
*,
|
| 454 |
+
tool_mode: bool,
|
| 455 |
+
max_new_tokens: int,
|
| 456 |
+
temperature: float,
|
| 457 |
+
verbose_tools: bool,
|
| 458 |
+
) -> str:
|
| 459 |
user_text = ensure_english(user_text)
|
| 460 |
+
if user_text.startswith("I can help best in English"):
|
| 461 |
return user_text
|
| 462 |
|
| 463 |
tool_results: List[Dict[str, Any]] = []
|
|
|
|
| 472 |
answer = generate_with_flan(prompt, max_new_tokens=max_new_tokens, temperature=temperature)
|
| 473 |
|
| 474 |
if verbose_tools and tool_results:
|
| 475 |
+
dbg = "\n\n---\nTool debug (snippets)\n"
|
| 476 |
if tool_notes:
|
| 477 |
dbg += "\n".join([f"- {n}" for n in tool_notes]) + "\n"
|
| 478 |
for tr in tool_results:
|
| 479 |
+
dbg += f"\n{tr.get('tool','tool')} ok={tr.get('ok')} error={tr.get('error')}\n"
|
| 480 |
+
dbg += f"{pretty_json_snip(tr.get('data'), limit=900)}\n"
|
| 481 |
answer += dbg
|
| 482 |
|
| 483 |
return answer
|
|
|
|
| 486 |
# ----------------------------
|
| 487 |
# Chat UI loop
|
| 488 |
# ----------------------------
|
| 489 |
+
user_input = st.chat_input("Ask a NASA question...")
|
| 490 |
|
| 491 |
if user_input:
|
| 492 |
st.session_state.chat_history.append({"role": "user", "content": user_input})
|
| 493 |
+
with st.spinner("Thinking..."):
|
| 494 |
resp = get_response(
|
| 495 |
user_input,
|
| 496 |
tool_mode=tool_mode,
|