CCockrum commited on
Commit
9dbf148
·
verified ·
1 Parent(s): 7465eb1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -99
app.py CHANGED
@@ -1,14 +1,4 @@
1
  # file: app.py
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
13
 
14
  import os
@@ -24,75 +14,46 @@ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
24
 
25
 
26
  # ----------------------------
27
- # Environment / Config
28
  # ----------------------------
29
  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
- # 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
 
44
- # ----------------------------
45
- # Agent Instructions
46
- # ----------------------------
47
  AGENT_INSTRUCTIONS = """
48
  You are HAL, a NASA-focused research assistant.
49
 
50
- MISSION
51
- - Provide accurate, in-depth answers about NASA science, missions, spacecraft, astronomy, planetary science, and spaceflight.
52
- - Ground claims in NASA tool data when available.
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
60
- - Define key terms.
61
- - Explain mechanisms clearly.
62
- - Use examples only when they improve understanding.
63
- - Address multi-part questions explicitly.
64
-
65
- EVIDENCE REFERENCES
66
- - When using TOOL_DATA, reference fields explicitly:
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
 
83
  # ----------------------------
84
- # Streamlit Setup
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
 
@@ -108,9 +69,6 @@ with st.sidebar:
108
  st.rerun()
109
 
110
 
111
- # ----------------------------
112
- # Chat History
113
- # ----------------------------
114
  if "chat_history" not in st.session_state:
115
  st.session_state.chat_history = [
116
  {"role": "assistant", "content": "Hello. Ask me anything about NASA missions, astronomy, Mars rovers, near-Earth objects, or APOD."}
@@ -138,7 +96,7 @@ def iso_date(s: str) -> Optional[str]:
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 "")
@@ -147,7 +105,7 @@ def pretty_json_snip(obj: Any, limit: int = 900) -> str:
147
 
148
 
149
  # ----------------------------
150
- # NASA Tools (minimal; extend as needed)
151
  # ----------------------------
152
  NASA_BASE = "https://api.nasa.gov"
153
 
@@ -156,6 +114,9 @@ def nasa_apod(date: Optional[str] = None) -> Dict[str, Any]:
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
 
@@ -176,7 +137,6 @@ def plan_tools(user_text: str) -> List[Dict[str, Any]]:
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
@@ -193,29 +153,24 @@ def load_llm(model_id: str):
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:
@@ -225,63 +180,51 @@ 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
 
 
1
  # file: app.py
 
 
 
 
 
 
 
 
 
 
2
  from __future__ import annotations
3
 
4
  import os
 
14
 
15
 
16
  # ----------------------------
17
+ # Config
18
  # ----------------------------
19
  NASA_API_KEY = os.getenv("NASA_API_KEY")
20
  if not NASA_API_KEY:
21
  raise ValueError("NASA_API_KEY is not set.")
22
 
23
+ # Fast CPU local instruction model
24
+ MODEL_ID = os.getenv("HAL_MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct")
 
 
 
 
 
25
 
26
  REQUEST_TIMEOUT_S = 20
27
 
28
+ MAX_NEW_TOKENS_DEFAULT = int(os.getenv("HAL_MAX_NEW_TOKENS", "192")) # lower = faster
29
+ # For speed + stability we use greedy decoding, so temperature is UI-only (kept for later)
30
+ TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.0"))
31
+
32
 
 
 
 
33
  AGENT_INSTRUCTIONS = """
34
  You are HAL, a NASA-focused research assistant.
35
 
36
+ Rules:
37
+ - Do not invent facts. If uncertain, say what is unknown and how to verify it.
38
+ - When TOOL_DATA is present and relevant, use it and reference the exact fields.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ Output format:
41
  ## Direct Answer
 
 
42
  ## Key Details and Evidence
 
 
43
  ## If You Want to Go Deeper
 
44
  """.strip()
45
 
46
 
47
  # ----------------------------
48
+ # Streamlit
49
  # ----------------------------
50
  st.set_page_config(page_title="HAL — NASA AI Assistant", layout="centered")
51
  st.title("HAL — NASA AI Assistant")
52
+ st.caption("Local instruction model with NASA tools")
53
 
54
  with st.sidebar:
55
  st.header("Controls")
56
+ max_new_tokens = st.slider("Max new tokens", 64, 512, MAX_NEW_TOKENS_DEFAULT, 16)
 
 
 
57
  tool_mode = st.toggle("Use NASA tools when relevant", value=True)
58
  verbose_tools = st.toggle("Show tool payload snippets", value=False)
59
 
 
69
  st.rerun()
70
 
71
 
 
 
 
72
  if "chat_history" not in st.session_state:
73
  st.session_state.chat_history = [
74
  {"role": "assistant", "content": "Hello. Ask me anything about NASA missions, astronomy, Mars rovers, near-Earth objects, or APOD."}
 
96
  return None
97
 
98
 
99
+ def pretty_json_snip(obj: Any, limit: int = 700) -> str:
100
  try:
101
  s = json.dumps(obj, indent=2, ensure_ascii=False)
102
  return s[:limit] + ("..." if len(s) > limit else "")
 
105
 
106
 
107
  # ----------------------------
108
+ # NASA tools (minimal)
109
  # ----------------------------
110
  NASA_BASE = "https://api.nasa.gov"
111
 
 
114
  if date:
115
  params["date"] = date
116
  data, err = safe_get(f"{NASA_BASE}/planetary/apod", params=params)
117
+ # keep the payload small
118
+ if isinstance(data, dict):
119
+ data = {k: data.get(k) for k in ["date", "title", "explanation", "media_type", "url"]}
120
  return {"tool": "apod", "ok": bool(data), "data": data, "error": err}
121
 
122
 
 
137
  # ----------------------------
138
  @st.cache_resource(show_spinner=True)
139
  def load_llm(model_id: str):
 
140
  use_cuda = torch.cuda.is_available()
141
  torch_dtype = torch.float16 if use_cuda else torch.float32
142
  device_map = "auto" if use_cuda else None
 
153
  model=model,
154
  tokenizer=tokenizer,
155
  )
156
+ return gen
157
 
158
+ gen_pipe = load_llm(MODEL_ID)
 
159
 
160
 
161
  # ----------------------------
162
+ # Prompt
163
  # ----------------------------
164
  def build_prompt(user_text: str, history: List[Dict[str, str]], tools: List[Dict[str, Any]]) -> str:
165
+ recent = history[-4:] # shorter context = faster
 
166
  history_block = "\n".join(f"{m['role'].upper()}: {m['content']}" for m in recent)
 
167
  tools_block = json.dumps(tools, indent=2, ensure_ascii=False) if tools else "None"
168
 
169
+ return f"""
 
 
170
  SYSTEM:
171
  {AGENT_INSTRUCTIONS}
172
 
173
+ CONTEXT:
174
  {history_block}
175
 
176
  TOOL_DATA:
 
180
  {user_text}
181
 
182
  ASSISTANT:
183
+ Do not repeat the user's question. Answer directly and follow the required output format.
184
  """.strip()
185
 
 
 
186
 
187
+ def strip_prompt(full_text: str, prompt: str) -> str:
 
188
  if full_text.startswith(prompt):
189
  return full_text[len(prompt):].lstrip()
190
  return full_text.strip()
191
 
192
 
193
  # ----------------------------
194
+ # Generation (fast)
195
  # ----------------------------
196
+ def generate(prompt: str, max_new_tokens: int) -> str:
197
+ # Greedy decoding is the fastest and most stable on CPU
 
 
 
 
198
  out = gen_pipe(
199
  prompt,
200
  max_new_tokens=int(max_new_tokens),
201
+ do_sample=False,
 
 
 
202
  return_full_text=True,
203
+ repetition_penalty=1.08,
204
  )
 
205
  if not out or not isinstance(out, list):
206
  return "Model returned no output."
 
207
  text = out[0].get("generated_text", "")
208
+ ans = strip_prompt(text, prompt)
209
 
210
+ # Trim if it starts producing extra role blocks
211
+ for stop in ["\nSYSTEM:", "\nUSER:", "\nASSISTANT:", "\nCONTEXT:", "\nTOOL_DATA:"]:
212
+ if stop in ans:
213
+ ans = ans.split(stop, 1)[0].rstrip()
214
 
215
+ return ans.strip()
216
 
217
 
218
  def get_response(user_text: str) -> str:
219
  tools = plan_tools(user_text) if tool_mode else []
220
  prompt = build_prompt(user_text, st.session_state.chat_history, tools)
221
+ answer = generate(prompt, max_new_tokens=max_new_tokens)
222
 
223
  if verbose_tools and tools:
224
+ answer += "\n\n---\nTool payload snippets\n"
225
  for t in tools:
226
+ answer += f"\n{t.get('tool')} ok={t.get('ok')} error={t.get('error')}\n"
227
+ answer += pretty_json_snip(t.get("data"), limit=600) + "\n"
 
228
 
229
  return answer
230