CCockrum commited on
Commit
7c773a3
·
verified ·
1 Parent(s): fab3bdd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -53
app.py CHANGED
@@ -2,10 +2,11 @@
2
  """
3
  HAL — NASA Chatbot (Streamlit)
4
 
5
- - Single authoritative agent prompt (AGENT_INSTRUCTIONS)
6
- - Tool-augmented with NASA APIs (APOD, Mars Rovers, NEOs, Earth Imagery, Image Search)
7
- - Local Flan-T5 model via transformers
8
- - Hugging Face Spaces safe
 
9
  """
10
 
11
  from __future__ import annotations
@@ -14,13 +15,12 @@ import os
14
  import re
15
  import json
16
  import datetime as dt
17
- from dataclasses import dataclass
18
  from typing import Any, Dict, List, Optional, Tuple
19
 
20
  import requests
21
  import streamlit as st
22
  import torch
23
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
24
 
25
 
26
  # ----------------------------
@@ -30,9 +30,14 @@ NASA_API_KEY = os.getenv("NASA_API_KEY")
30
  if not NASA_API_KEY:
31
  raise ValueError("NASA_API_KEY is not set.")
32
 
33
- MODEL_ID = os.getenv("HAL_MODEL_ID", "google/flan-t5-large")
 
 
 
34
  MAX_NEW_TOKENS_DEFAULT = int(os.getenv("HAL_MAX_NEW_TOKENS", "420"))
35
  TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.3"))
 
 
36
  REQUEST_TIMEOUT_S = 20
37
 
38
 
@@ -48,7 +53,7 @@ MISSION
48
 
49
  TRUTHFULNESS
50
  - Do not invent facts, dates, or mission details.
51
- - If uncertain, clearly state what is unknown and how it could be verified.
52
  - Prefer TOOL_DATA over general knowledge when relevant.
53
 
54
  EXPLANATION STYLE
@@ -62,9 +67,16 @@ EVIDENCE REFERENCES
62
  (tool=apod.date), (tool=mars_photos.sample[0].camera.full_name)
63
 
64
  OUTPUT FORMAT
 
 
65
  ## Direct Answer
 
 
66
  ## Key Details and Evidence
 
 
67
  ## If You Want to Go Deeper
 
68
  """.strip()
69
 
70
 
@@ -73,16 +85,20 @@ OUTPUT FORMAT
73
  # ----------------------------
74
  st.set_page_config(page_title="HAL — NASA AI Assistant", layout="centered")
75
  st.title("HAL — NASA AI Assistant")
76
- st.caption("Tool-augmented NASA chatbot")
77
 
78
  with st.sidebar:
 
79
  max_new_tokens = st.slider("Max new tokens", 64, 900, MAX_NEW_TOKENS_DEFAULT, 16)
80
  temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)
 
 
81
  tool_mode = st.toggle("Use NASA tools when relevant", value=True)
82
  verbose_tools = st.toggle("Show tool payload snippets", value=False)
83
 
84
  st.divider()
85
- st.write("Model:", MODEL_ID)
 
86
  st.write("Device:", "cuda" if torch.cuda.is_available() else "cpu")
87
 
88
  if st.button("Clear chat"):
@@ -92,20 +108,6 @@ with st.sidebar:
92
  st.rerun()
93
 
94
 
95
- # ----------------------------
96
- # Load Model
97
- # ----------------------------
98
- @st.cache_resource(show_spinner=True)
99
- def load_llm(model_id: str):
100
- device = 0 if torch.cuda.is_available() else -1
101
- tokenizer = AutoTokenizer.from_pretrained(model_id)
102
- model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
103
- gen = pipeline("text2text-generation", model=model, tokenizer=tokenizer, device=device)
104
- return gen
105
-
106
- pipe = load_llm(MODEL_ID)
107
-
108
-
109
  # ----------------------------
110
  # Chat History
111
  # ----------------------------
@@ -122,7 +124,7 @@ def safe_get(url: str, params: Optional[Dict[str, Any]] = None) -> Tuple[Optiona
122
  try:
123
  r = requests.get(url, params=params, timeout=REQUEST_TIMEOUT_S)
124
  if r.status_code != 200:
125
- return None, f"HTTP {r.status_code}"
126
  return r.json(), None
127
  except Exception as e:
128
  return None, str(e)
@@ -136,78 +138,156 @@ def iso_date(s: str) -> Optional[str]:
136
  return None
137
 
138
 
 
 
 
 
 
 
 
 
139
  # ----------------------------
140
- # NASA Tools
141
  # ----------------------------
142
  NASA_BASE = "https://api.nasa.gov"
143
 
144
- def nasa_apod(date: Optional[str] = None):
145
  params = {"api_key": NASA_API_KEY}
146
  if date:
147
  params["date"] = date
148
- data, err = safe_get(f"{NASA_BASE}/planetary/apod", params)
149
  return {"tool": "apod", "ok": bool(data), "data": data, "error": err}
150
 
151
 
152
- def nasa_mars_photos(rover="curiosity", sol=1000):
153
- params = {"api_key": NASA_API_KEY, "sol": sol}
154
- data, err = safe_get(f"{NASA_BASE}/mars-photos/api/v1/rovers/{rover}/photos", params)
155
- return {"tool": "mars_photos", "ok": bool(data), "data": data, "error": err}
 
 
 
 
 
 
156
 
157
 
158
  # ----------------------------
159
- # Tool Planning
160
  # ----------------------------
161
- def plan_tools(user_text: str):
162
- tools = []
163
- text = user_text.lower()
 
 
 
 
 
 
 
 
 
 
164
 
165
- if "apod" in text:
166
- tools.append(nasa_apod())
 
 
 
 
167
 
168
- if "mars" in text and "photo" in text:
169
- tools.append(nasa_mars_photos())
170
 
171
- return tools
172
 
173
 
174
  # ----------------------------
175
- # Prompt Builder
176
  # ----------------------------
177
  def build_prompt(user_text: str, history: List[Dict[str, str]], tools: List[Dict[str, Any]]) -> str:
178
- history_block = "\n".join(f"{m['role'].upper()}: {m['content']}" for m in history[-6:])
179
- tools_block = json.dumps(tools, indent=2) if tools else "None"
 
 
 
180
 
181
- return f"""
 
 
 
182
  {AGENT_INSTRUCTIONS}
183
 
184
- CONVERSATION CONTEXT
185
  {history_block}
186
 
187
- TOOL_DATA
188
  {tools_block}
189
 
190
- USER QUESTION
191
  {user_text}
 
 
 
192
  """.strip()
193
 
 
 
 
 
 
 
 
 
 
194
 
195
  # ----------------------------
196
  # Generation
197
  # ----------------------------
198
- def generate(prompt: str) -> str:
199
- out = pipe(prompt, max_new_tokens=max_new_tokens, temperature=temperature)
200
- return out[0]["generated_text"].strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
 
203
  def get_response(user_text: str) -> str:
204
  tools = plan_tools(user_text) if tool_mode else []
205
  prompt = build_prompt(user_text, st.session_state.chat_history, tools)
206
- return generate(prompt)
 
 
 
 
 
 
 
 
 
207
 
208
 
209
  # ----------------------------
210
- # UI Loop
211
  # ----------------------------
212
  user_input = st.chat_input("Ask a NASA question...")
213
 
 
2
  """
3
  HAL — NASA Chatbot (Streamlit)
4
 
5
+ Changes in this version:
6
+ - Uses a stronger local instruction model: Qwen2.5 Instruct (causal LM)
7
+ - Uses text-generation pipeline instead of text2text-generation
8
+ - Uses an explicit chat-style prompt to reduce echoing and improve answer depth
9
+ - Keeps NASA tool augmentation hooks (minimal examples included; extend as needed)
10
  """
11
 
12
  from __future__ import annotations
 
15
  import re
16
  import json
17
  import datetime as dt
 
18
  from typing import Any, Dict, List, Optional, Tuple
19
 
20
  import requests
21
  import streamlit as st
22
  import torch
23
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
24
 
25
 
26
  # ----------------------------
 
30
  if not NASA_API_KEY:
31
  raise ValueError("NASA_API_KEY is not set.")
32
 
33
+ # Stronger local instruction model (CPU-friendly).
34
+ # If CPU is too slow/heavy, try: Qwen/Qwen2.5-0.5B-Instruct
35
+ MODEL_ID = os.getenv("HAL_MODEL_ID", "Qwen/Qwen2.5-1.5B-Instruct")
36
+
37
  MAX_NEW_TOKENS_DEFAULT = int(os.getenv("HAL_MAX_NEW_TOKENS", "420"))
38
  TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.3"))
39
+ TOP_P_DEFAULT = float(os.getenv("HAL_TOP_P", "0.9"))
40
+
41
  REQUEST_TIMEOUT_S = 20
42
 
43
 
 
53
 
54
  TRUTHFULNESS
55
  - Do not invent facts, dates, or mission details.
56
+ - If uncertain, state what is unknown and how it could be verified.
57
  - Prefer TOOL_DATA over general knowledge when relevant.
58
 
59
  EXPLANATION STYLE
 
67
  (tool=apod.date), (tool=mars_photos.sample[0].camera.full_name)
68
 
69
  OUTPUT FORMAT
70
+ Return your response in exactly this structure:
71
+
72
  ## Direct Answer
73
+ (1–4 paragraphs)
74
+
75
  ## Key Details and Evidence
76
+ - Bullet points with tool field references when available
77
+
78
  ## If You Want to Go Deeper
79
+ - 3–6 follow-up questions or next steps
80
  """.strip()
81
 
82
 
 
85
  # ----------------------------
86
  st.set_page_config(page_title="HAL — NASA AI Assistant", layout="centered")
87
  st.title("HAL — NASA AI Assistant")
88
+ st.caption("Tool-augmented NASA chatbot (local instruction model)")
89
 
90
  with st.sidebar:
91
+ st.header("Controls")
92
  max_new_tokens = st.slider("Max new tokens", 64, 900, MAX_NEW_TOKENS_DEFAULT, 16)
93
  temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)
94
+ top_p = st.slider("Top-p", 0.1, 1.0, TOP_P_DEFAULT, 0.05)
95
+
96
  tool_mode = st.toggle("Use NASA tools when relevant", value=True)
97
  verbose_tools = st.toggle("Show tool payload snippets", value=False)
98
 
99
  st.divider()
100
+ st.subheader("Model")
101
+ st.write(MODEL_ID)
102
  st.write("Device:", "cuda" if torch.cuda.is_available() else "cpu")
103
 
104
  if st.button("Clear chat"):
 
108
  st.rerun()
109
 
110
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  # ----------------------------
112
  # Chat History
113
  # ----------------------------
 
124
  try:
125
  r = requests.get(url, params=params, timeout=REQUEST_TIMEOUT_S)
126
  if r.status_code != 200:
127
+ return None, f"HTTP {r.status_code}: {r.text[:200]}"
128
  return r.json(), None
129
  except Exception as e:
130
  return None, str(e)
 
138
  return None
139
 
140
 
141
+ def pretty_json_snip(obj: Any, limit: int = 900) -> str:
142
+ try:
143
+ s = json.dumps(obj, indent=2, ensure_ascii=False)
144
+ return s[:limit] + ("..." if len(s) > limit else "")
145
+ except Exception:
146
+ return str(obj)[:limit] + "..."
147
+
148
+
149
  # ----------------------------
150
+ # NASA Tools (minimal; extend as needed)
151
  # ----------------------------
152
  NASA_BASE = "https://api.nasa.gov"
153
 
154
+ def nasa_apod(date: Optional[str] = None) -> Dict[str, Any]:
155
  params = {"api_key": NASA_API_KEY}
156
  if date:
157
  params["date"] = date
158
+ data, err = safe_get(f"{NASA_BASE}/planetary/apod", params=params)
159
  return {"tool": "apod", "ok": bool(data), "data": data, "error": err}
160
 
161
 
162
+ def plan_tools(user_text: str) -> List[Dict[str, Any]]:
163
+ t = user_text.lower()
164
+ tools: List[Dict[str, Any]] = []
165
+
166
+ if "apod" in t or "astronomy picture of the day" in t:
167
+ m = re.search(r"(\d{4}-\d{2}-\d{2})", user_text)
168
+ date = iso_date(m.group(1)) if m else None
169
+ tools.append(nasa_apod(date=date))
170
+
171
+ return tools
172
 
173
 
174
  # ----------------------------
175
+ # Model loading (cached)
176
  # ----------------------------
177
+ @st.cache_resource(show_spinner=True)
178
+ def load_llm(model_id: str):
179
+ # For CPU Spaces, float32 is safest. If you have GPU, you can use float16.
180
+ use_cuda = torch.cuda.is_available()
181
+ torch_dtype = torch.float16 if use_cuda else torch.float32
182
+ device_map = "auto" if use_cuda else None
183
+
184
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
185
+ model = AutoModelForCausalLM.from_pretrained(
186
+ model_id,
187
+ torch_dtype=torch_dtype,
188
+ device_map=device_map,
189
+ )
190
 
191
+ gen = pipeline(
192
+ "text-generation",
193
+ model=model,
194
+ tokenizer=tokenizer,
195
+ )
196
+ return gen, tokenizer
197
 
 
 
198
 
199
+ gen_pipe, gen_tokenizer = load_llm(MODEL_ID)
200
 
201
 
202
  # ----------------------------
203
+ # Prompt builder for instruct causal LMs
204
  # ----------------------------
205
  def build_prompt(user_text: str, history: List[Dict[str, str]], tools: List[Dict[str, Any]]) -> str:
206
+ # Keep history short for speed
207
+ recent = history[-6:]
208
+ history_block = "\n".join(f"{m['role'].upper()}: {m['content']}" for m in recent)
209
+
210
+ tools_block = json.dumps(tools, indent=2, ensure_ascii=False) if tools else "None"
211
 
212
+ # A simple, robust instruction/chat style prompt.
213
+ # The explicit "Do not repeat the user's question" reduces echoing.
214
+ prompt = f"""
215
+ SYSTEM:
216
  {AGENT_INSTRUCTIONS}
217
 
218
+ CONVERSATION CONTEXT:
219
  {history_block}
220
 
221
+ TOOL_DATA:
222
  {tools_block}
223
 
224
+ USER:
225
  {user_text}
226
+
227
+ ASSISTANT:
228
+ Do not repeat the user's question. Follow the required output format. Write the answer now.
229
  """.strip()
230
 
231
+ return prompt
232
+
233
+
234
+ def extract_assistant_text(full_text: str, prompt: str) -> str:
235
+ # The pipeline returns prompt + completion. Remove the prompt prefix when present.
236
+ if full_text.startswith(prompt):
237
+ return full_text[len(prompt):].lstrip()
238
+ return full_text.strip()
239
+
240
 
241
  # ----------------------------
242
  # Generation
243
  # ----------------------------
244
+ def generate(prompt: str, max_new_tokens: int, temperature: float, top_p: float) -> str:
245
+ # For explainers, deterministic decoding is often best. We do:
246
+ # - If temperature is 0: greedy (do_sample False)
247
+ # - Else: nucleus sampling
248
+ do_sample = bool(temperature and temperature > 0.0)
249
+
250
+ out = gen_pipe(
251
+ prompt,
252
+ max_new_tokens=int(max_new_tokens),
253
+ do_sample=do_sample,
254
+ temperature=float(temperature) if do_sample else None,
255
+ top_p=float(top_p) if do_sample else None,
256
+ repetition_penalty=1.08,
257
+ return_full_text=True,
258
+ )
259
+
260
+ if not out or not isinstance(out, list):
261
+ return "Model returned no output."
262
+
263
+ text = out[0].get("generated_text", "")
264
+ answer = extract_assistant_text(text, prompt)
265
+
266
+ # Basic cleanup: if the model drifts into additional role tags, trim.
267
+ for stop in ["\nSYSTEM:", "\nUSER:", "\nASSISTANT:", "\nCONVERSATION CONTEXT:"]:
268
+ if stop in answer:
269
+ answer = answer.split(stop, 1)[0].rstrip()
270
+
271
+ return answer.strip()
272
 
273
 
274
  def get_response(user_text: str) -> str:
275
  tools = plan_tools(user_text) if tool_mode else []
276
  prompt = build_prompt(user_text, st.session_state.chat_history, tools)
277
+ answer = generate(prompt, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p)
278
+
279
+ if verbose_tools and tools:
280
+ debug = "\n\n---\nTool payload snippets\n"
281
+ for t in tools:
282
+ debug += f"\n{t.get('tool')} ok={t.get('ok')} error={t.get('error')}\n"
283
+ debug += pretty_json_snip(t.get("data"), limit=700) + "\n"
284
+ answer += debug
285
+
286
+ return answer
287
 
288
 
289
  # ----------------------------
290
+ # UI loop
291
  # ----------------------------
292
  user_input = st.chat_input("Ask a NASA question...")
293