CCockrum commited on
Commit
a86ceb0
·
verified ·
1 Parent(s): 2ab201a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +162 -191
app.py CHANGED
@@ -4,14 +4,12 @@ from __future__ import annotations
4
  import os
5
  import re
6
  import json
7
- import datetime as dt
8
  from typing import Any, Dict, List, Optional, Tuple
9
 
10
  import requests
11
  import streamlit as st
12
  import torch
13
- from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
14
- import markdown as md
15
 
16
 
17
  # ----------------------------
@@ -24,44 +22,62 @@ if not NASA_API_KEY:
24
  MODEL_ID = os.getenv("HAL_MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct")
25
  REQUEST_TIMEOUT_S = 20
26
 
27
- MAX_NEW_TOKENS_DEFAULT = int(os.getenv("HAL_MAX_NEW_TOKENS", "180"))
28
  TOP_P_DEFAULT = float(os.getenv("HAL_TOP_P", "0.9"))
29
- TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.0"))
30
-
31
- HEADINGS = ["## Answer", "## Key Points", "## Next Steps"]
32
 
33
  SYSTEM_RULES = """
34
  You are HAL, a NASA-focused assistant.
35
 
36
- Hard rules:
37
- - Never mention instructions, prompts, policies, or that you are following a task.
38
- - Never say "the assistant" or describe what you are doing.
 
39
  - Do not repeat the user's question.
40
- - Keep the response short and complete.
41
- - If you are uncertain: say so in one sentence and suggest how to verify.
42
 
43
- Format (use these exact headings):
44
  ## Answer
45
- (2 to 4 sentences)
46
 
47
  ## Key Points
48
- (2 to 4 bullet points)
49
 
50
  ## Next Steps
51
- (exactly 3 short follow-up questions as bullets, under 12 words each)
52
  """.strip()
53
 
54
- STOP_STRINGS = [
55
- "\nSYSTEM:",
56
- "\nUSER:",
57
- "\nASSISTANT:",
58
- "\nINSTRUCTIONS:",
59
- "\nTASK:",
60
- "\nThe assistant",
61
- "\nAs an AI",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  ]
63
 
64
 
 
 
 
65
  # ----------------------------
66
  # Streamlit UI
67
  # ----------------------------
@@ -111,7 +127,7 @@ st.markdown("<div class='page-subtitle'>Local instruction model with NASA tools<
111
 
112
  with st.sidebar:
113
  st.header("Controls")
114
- max_new_tokens = st.slider("Max new tokens", 64, 384, MAX_NEW_TOKENS_DEFAULT, 16)
115
  temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)
116
  top_p = st.slider("Top-p", 0.1, 1.0, TOP_P_DEFAULT, 0.05)
117
 
@@ -148,20 +164,24 @@ def safe_get(url: str, params: Optional[Dict[str, Any]] = None) -> Tuple[Optiona
148
  return None, str(e)
149
 
150
 
151
- def iso_date(s: str) -> Optional[str]:
152
- try:
153
- dt.datetime.strptime(s, "%Y-%m-%d")
154
- return s
155
- except Exception:
156
- return None
 
 
157
 
158
 
159
- def pretty_json_snip(obj: Any, limit: int = 700) -> str:
160
- try:
161
- s = json.dumps(obj, indent=2, ensure_ascii=False)
162
- return s[:limit] + ("..." if len(s) > limit else "")
163
- except Exception:
164
- return str(obj)[:limit] + "..."
 
 
165
 
166
 
167
  def normalize_list_spacing(text: str) -> str:
@@ -190,12 +210,48 @@ def normalize_list_spacing(text: str) -> str:
190
  return "\n".join(cleaned).strip()
191
 
192
 
193
- def markdown_to_html(text: str) -> str:
194
- return md.markdown(text, extensions=["extra"])
195
-
196
-
197
- def has_all_sections(text: str) -> bool:
198
- return all(h in text for h in HEADINGS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
 
200
 
201
  def ends_cleanly(text: str) -> bool:
@@ -205,182 +261,98 @@ def ends_cleanly(text: str) -> bool:
205
  return t[-1] in ".!?)]\"'"
206
 
207
 
208
- def looks_truncated(text: str) -> bool:
209
- if not has_all_sections(text):
210
- return True
211
- if not ends_cleanly(text):
212
- return True
213
- return False
214
-
215
-
216
- def apply_stop_strings(text: str) -> str:
217
- out = text
218
- for s in STOP_STRINGS:
219
- if s in out:
220
- out = out.split(s, 1)[0].rstrip()
221
- return out
222
-
223
-
224
- # ----------------------------
225
- # NASA tools (minimal)
226
- # ----------------------------
227
- NASA_BASE = "https://api.nasa.gov"
228
-
229
-
230
- def nasa_apod(date: Optional[str] = None) -> Dict[str, Any]:
231
- params = {"api_key": NASA_API_KEY}
232
- if date:
233
- params["date"] = date
234
- data, err = safe_get(f"{NASA_BASE}/planetary/apod", params=params)
235
- if isinstance(data, dict):
236
- data = {k: data.get(k) for k in ["date", "title", "explanation", "media_type", "url"]}
237
- return {"tool": "apod", "ok": bool(data), "data": data, "error": err}
238
-
239
-
240
- def plan_tools(user_text: str) -> List[Dict[str, Any]]:
241
- t = user_text.lower()
242
- tools: List[Dict[str, Any]] = []
243
-
244
- if "apod" in t or "astronomy picture of the day" in t:
245
- m = re.search(r"(\d{4}-\d{2}-\d{2})", user_text)
246
- date = iso_date(m.group(1)) if m else None
247
- tools.append(nasa_apod(date=date))
248
-
249
- return tools
250
-
251
-
252
  # ----------------------------
253
  # Model loading (cached)
254
  # ----------------------------
255
  @st.cache_resource(show_spinner=True)
256
- def load_llm(model_id: str):
257
  use_cuda = torch.cuda.is_available()
258
- torch_dtype = torch.float16 if use_cuda else torch.float32
259
- device_map = "auto" if use_cuda else None
260
 
261
- tokenizer = AutoTokenizer.from_pretrained(model_id)
262
  model = AutoModelForCausalLM.from_pretrained(
263
  model_id,
264
- torch_dtype=torch_dtype,
265
- device_map=device_map,
266
  )
 
 
267
 
268
- gen = pipeline("text-generation", model=model, tokenizer=tokenizer)
269
- return gen
270
 
271
 
272
- gen_pipe = load_llm(MODEL_ID)
273
 
274
 
275
- # ----------------------------
276
- # Prompt building (chat-style; avoids meta triggers)
277
- # ----------------------------
278
- def build_prompt(user_text: str, history: List[Dict[str, str]], tools: List[Dict[str, Any]]) -> str:
279
- # Keep history small for speed and to reduce drift
280
- recent = history[-2:]
281
- history_lines = []
282
  for m in recent:
283
- role = "User" if m["role"] == "user" else "Assistant"
284
- history_lines.append(f"{role}: {m['content']}")
285
- history_block = "\n".join(history_lines)
286
 
287
- tool_block = ""
288
  if tools:
289
- # Provide tool results without labeling it "TOOL_DATA"
290
- tool_block = "\n\nNASA Data:\n" + json.dumps(tools, indent=2, ensure_ascii=False)
291
-
292
- # Note: we do not use sections named "CONTEXT" or "INSTRUCTIONS"
293
- return f"""System: {SYSTEM_RULES}
294
-
295
- {history_block}{tool_block}
296
 
297
- User: {user_text}
298
- Assistant:
299
- """.strip()
300
 
301
 
302
- def strip_prompt(full_text: str, prompt: str) -> str:
303
- if full_text.startswith(prompt):
304
- return full_text[len(prompt):].lstrip()
305
- return full_text.strip()
306
 
 
307
 
308
- # ----------------------------
309
- # Generation
310
- # ----------------------------
311
- def generate(prompt: str, max_new_tokens: int, temperature: float, top_p: float) -> str:
312
- do_sample = bool(temperature and temperature > 0.0)
313
-
314
- out = gen_pipe(
315
- prompt,
316
- max_new_tokens=int(max_new_tokens),
317
- do_sample=do_sample,
318
- temperature=float(temperature) if do_sample else None,
319
- top_p=float(top_p) if do_sample else None,
320
- repetition_penalty=1.12,
321
- return_full_text=True,
322
  )
323
 
324
- if not out or not isinstance(out, list):
325
- return "Model returned no output."
326
-
327
- text = out[0].get("generated_text", "")
328
- ans = strip_prompt(text, prompt)
329
- ans = apply_stop_strings(ans)
330
- return ans.strip()
331
 
 
332
 
333
- def finish_last_sentence(existing_answer: str) -> str:
334
- tail = existing_answer[-500:]
335
- prompt = f"""System: Finish the last sentence only. Output a short fragment. Do not add headings.
 
 
 
 
 
 
 
 
336
 
337
- Text:
338
- {tail}
339
 
340
- Continuation:
341
- """.strip()
342
- frag = generate(prompt, max_new_tokens=40, temperature=temperature, top_p=top_p)
343
- frag = apply_stop_strings(frag).strip()
344
- return frag
345
-
346
-
347
- def get_response(user_text: str) -> str:
348
- tools = plan_tools(user_text) if tool_mode else []
349
- prompt = build_prompt(user_text, st.session_state.chat_history, tools)
350
-
351
- answer = generate(prompt, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p)
352
- answer = normalize_list_spacing(answer)
353
 
354
- # If structure missing, do a short repair pass
355
- if not has_all_sections(answer):
356
- repair_prompt = f"""System: Rewrite the following into the required format exactly.
357
- {SYSTEM_RULES}
 
358
 
359
- Draft:
360
- {answer}
361
-
362
- Rewrite:
363
- """.strip()
364
- answer = generate(repair_prompt, max_new_tokens=min(max_new_tokens, 180), temperature=temperature, top_p=top_p)
365
- answer = normalize_list_spacing(answer)
366
-
367
- # If still mid-sentence, do a tiny finish pass
368
- if not ends_cleanly(answer):
369
- frag = finish_last_sentence(answer)
370
- if frag:
371
- answer = (answer.rstrip() + " " + frag.lstrip()).strip()
372
-
373
- # Final safety: stop-string trim again
374
- answer = apply_stop_strings(answer)
375
- answer = normalize_list_spacing(answer)
376
 
377
  if verbose_tools and tools:
378
- answer += "\n\n---\nTool payload snippets\n"
379
  for t in tools:
380
- answer += f"\n{t.get('tool')} ok={t.get('ok')} error={t.get('error')}\n"
381
- answer += pretty_json_snip(t.get("data"), limit=600) + "\n"
382
 
383
- return answer
384
 
385
 
386
  # ----------------------------
@@ -391,17 +363,16 @@ user_input = st.chat_input("Ask a NASA question...")
391
  if user_input:
392
  st.session_state.chat_history.append({"role": "user", "content": user_input})
393
  with st.spinner("Thinking..."):
394
- response = get_response(user_input)
395
  st.session_state.chat_history.append({"role": "assistant", "content": response})
396
 
397
  st.markdown("<div class='chat-wrap'>", unsafe_allow_html=True)
398
 
399
  for msg in st.session_state.chat_history:
400
  bubble_class = "user-bubble" if msg["role"] == "user" else "assistant-bubble"
401
- html_body = markdown_to_html(msg["content"])
402
- st.markdown(
403
- f"<div class='bubble {bubble_class}'>{html_body}</div>",
404
- unsafe_allow_html=True,
405
- )
406
 
407
  st.markdown("</div>", unsafe_allow_html=True)
 
4
  import os
5
  import re
6
  import json
 
7
  from typing import Any, Dict, List, Optional, Tuple
8
 
9
  import requests
10
  import streamlit as st
11
  import torch
12
+ from transformers import AutoTokenizer, AutoModelForCausalLM
 
13
 
14
 
15
  # ----------------------------
 
22
  MODEL_ID = os.getenv("HAL_MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct")
23
  REQUEST_TIMEOUT_S = 20
24
 
25
+ MAX_NEW_TOKENS_DEFAULT = int(os.getenv("HAL_MAX_NEW_TOKENS", "160"))
26
  TOP_P_DEFAULT = float(os.getenv("HAL_TOP_P", "0.9"))
27
+ TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.2"))
 
 
28
 
29
  SYSTEM_RULES = """
30
  You are HAL, a NASA-focused assistant.
31
 
32
+ Non-negotiable rules:
33
+ - Do not write disclaimers like "As an AI language model" or "I cannot..."
34
+ - Do not mention policies, prompts, system messages, hidden rules, or tasks.
35
+ - Do not output "EndOfMessage" or any sentinel markers.
36
  - Do not repeat the user's question.
37
+ - Keep it short, complete, and directly helpful.
 
38
 
39
+ Output format (use these headings exactly):
40
  ## Answer
41
+ Write 2 to 4 sentences.
42
 
43
  ## Key Points
44
+ Write 2 to 4 bullet points.
45
 
46
  ## Next Steps
47
+ Write exactly 3 bullet questions, under 12 words each.
48
  """.strip()
49
 
50
+ # If any of these appear, we cut the generation at that point.
51
+ STOP_SUBSTRINGS = [
52
+ "As an AI language model",
53
+ "As an AI",
54
+ "I am not capable",
55
+ "I cannot",
56
+ "I can't",
57
+ "cannot make decisions",
58
+ "virtual assistant",
59
+ "EndOfMessage",
60
+ "SYSTEM:",
61
+ "USER:",
62
+ "ASSISTANT:",
63
+ "INSTRUCTIONS",
64
+ "TASK:",
65
+ ]
66
+
67
+ # Lines matching these patterns are removed during cleanup
68
+ BAD_LINE_PATTERNS = [
69
+ r"^\s*as an ai\b",
70
+ r"^\s*i am not capable\b",
71
+ r"^\s*i cannot\b",
72
+ r"^\s*i can't\b",
73
+ r"^\s*endofmessage\b",
74
+ r"^\s*please note that\b.*(not able|cannot|can't)",
75
  ]
76
 
77
 
78
+ NASA_BASE = "https://api.nasa.gov"
79
+
80
+
81
  # ----------------------------
82
  # Streamlit UI
83
  # ----------------------------
 
127
 
128
  with st.sidebar:
129
  st.header("Controls")
130
+ max_new_tokens = st.slider("Max new tokens", 64, 320, MAX_NEW_TOKENS_DEFAULT, 16)
131
  temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)
132
  top_p = st.slider("Top-p", 0.1, 1.0, TOP_P_DEFAULT, 0.05)
133
 
 
164
  return None, str(e)
165
 
166
 
167
+ def nasa_apod(date: Optional[str] = None) -> Dict[str, Any]:
168
+ params = {"api_key": NASA_API_KEY}
169
+ if date:
170
+ params["date"] = date
171
+ data, err = safe_get(f"{NASA_BASE}/planetary/apod", params=params)
172
+ if isinstance(data, dict):
173
+ data = {k: data.get(k) for k in ["date", "title", "explanation", "media_type", "url"]}
174
+ return {"tool": "apod", "ok": bool(data), "data": data, "error": err}
175
 
176
 
177
+ def plan_tools(user_text: str) -> List[Dict[str, Any]]:
178
+ t = user_text.lower()
179
+ tools: List[Dict[str, Any]] = []
180
+ if "apod" in t or "astronomy picture of the day" in t:
181
+ m = re.search(r"(\d{4}-\d{2}-\d{2})", user_text)
182
+ date = m.group(1) if m else None
183
+ tools.append(nasa_apod(date=date))
184
+ return tools
185
 
186
 
187
  def normalize_list_spacing(text: str) -> str:
 
210
  return "\n".join(cleaned).strip()
211
 
212
 
213
+ def cut_at_stop_substrings(text: str) -> str:
214
+ out = text
215
+ earliest = None
216
+ for s in STOP_SUBSTRINGS:
217
+ idx = out.find(s)
218
+ if idx != -1:
219
+ earliest = idx if earliest is None else min(earliest, idx)
220
+ if earliest is not None:
221
+ out = out[:earliest]
222
+ return out.strip()
223
+
224
+
225
+ def remove_bad_lines(text: str) -> str:
226
+ out_lines: List[str] = []
227
+ for line in text.splitlines():
228
+ low = line.strip().lower()
229
+ bad = False
230
+ for pat in BAD_LINE_PATTERNS:
231
+ if re.search(pat, low):
232
+ bad = True
233
+ break
234
+ if not bad:
235
+ out_lines.append(line)
236
+ return "\n".join(out_lines).strip()
237
+
238
+
239
+ def ensure_sections(text: str) -> str:
240
+ # If model fails to comply, we force a compact fallback.
241
+ if "## Answer" in text and "## Key Points" in text and "## Next Steps" in text:
242
+ return text
243
+ # Minimal fallback, keeps app usable.
244
+ return (
245
+ "## Answer\n"
246
+ "I can help, but I need you to re-ask that in one clear sentence.\n\n"
247
+ "## Key Points\n"
248
+ "- Tell me what you want to focus on.\n"
249
+ "- Include any constraints (level, length, mission, date).\n\n"
250
+ "## Next Steps\n"
251
+ "- Do you want a beginner or technical explanation?\n"
252
+ "- Is there a specific NASA mission you mean?\n"
253
+ "- Should I include equations or keep it conceptual?\n"
254
+ )
255
 
256
 
257
  def ends_cleanly(text: str) -> bool:
 
261
  return t[-1] in ".!?)]\"'"
262
 
263
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
264
  # ----------------------------
265
  # Model loading (cached)
266
  # ----------------------------
267
  @st.cache_resource(show_spinner=True)
268
+ def load_model(model_id: str):
269
  use_cuda = torch.cuda.is_available()
270
+ device = "cuda" if use_cuda else "cpu"
271
+ dtype = torch.float16 if use_cuda else torch.float32
272
 
273
+ tok = AutoTokenizer.from_pretrained(model_id, use_fast=True)
274
  model = AutoModelForCausalLM.from_pretrained(
275
  model_id,
276
+ torch_dtype=dtype,
277
+ device_map="auto" if use_cuda else None,
278
  )
279
+ if not use_cuda:
280
+ model.to(device)
281
 
282
+ return tok, model, device
 
283
 
284
 
285
+ tokenizer, model, device = load_model(MODEL_ID)
286
 
287
 
288
+ def build_messages(user_text: str, history: List[Dict[str, str]], tools: List[Dict[str, Any]]) -> List[Dict[str, str]]:
289
+ # Keep a small window to reduce drift and speed up
290
+ recent = history[-3:] if history else []
291
+ msgs: List[Dict[str, str]] = [{"role": "system", "content": SYSTEM_RULES}]
292
+
 
 
293
  for m in recent:
294
+ if m["role"] in ("user", "assistant"):
295
+ msgs.append({"role": m["role"], "content": m["content"]})
 
296
 
 
297
  if tools:
298
+ # Keep tool info short and plain; avoid "TOOL" labels that trigger templates
299
+ tool_snip = json.dumps(tools, ensure_ascii=False)[:900]
300
+ msgs.append({"role": "user", "content": f"NASA data (if relevant): {tool_snip}"})
 
 
 
 
301
 
302
+ msgs.append({"role": "user", "content": user_text})
303
+ return msgs
 
304
 
305
 
306
+ def generate_answer(user_text: str) -> str:
307
+ tools = plan_tools(user_text) if tool_mode else []
 
 
308
 
309
+ messages = build_messages(user_text, st.session_state.chat_history, tools)
310
 
311
+ prompt = tokenizer.apply_chat_template(
312
+ messages,
313
+ tokenize=False,
314
+ add_generation_prompt=True,
 
 
 
 
 
 
 
 
 
 
315
  )
316
 
317
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
 
 
 
 
 
 
318
 
319
+ do_sample = temperature > 0.0
320
 
321
+ with torch.inference_mode():
322
+ out_ids = model.generate(
323
+ **inputs,
324
+ max_new_tokens=int(max_new_tokens),
325
+ do_sample=do_sample,
326
+ temperature=float(temperature) if do_sample else None,
327
+ top_p=float(top_p) if do_sample else None,
328
+ repetition_penalty=1.15,
329
+ eos_token_id=tokenizer.eos_token_id,
330
+ pad_token_id=tokenizer.eos_token_id,
331
+ )
332
 
333
+ decoded = tokenizer.decode(out_ids[0], skip_special_tokens=True)
 
334
 
335
+ # Strip the prompt portion (best-effort)
336
+ if decoded.startswith(prompt):
337
+ decoded = decoded[len(prompt):].strip()
 
 
 
 
 
 
 
 
 
 
338
 
339
+ # Hard-stop and cleanup
340
+ decoded = cut_at_stop_substrings(decoded)
341
+ decoded = remove_bad_lines(decoded)
342
+ decoded = normalize_list_spacing(decoded)
343
+ decoded = ensure_sections(decoded)
344
 
345
+ # Optional: small completion attempt if it ends mid-sentence
346
+ if not ends_cleanly(decoded):
347
+ decoded = decoded.rstrip() + "."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348
 
349
  if verbose_tools and tools:
350
+ decoded += "\n\n---\nTool payload snippets\n"
351
  for t in tools:
352
+ decoded += f"\n{t.get('tool')} ok={t.get('ok')} error={t.get('error')}\n"
353
+ decoded += (json.dumps(t.get("data"), indent=2, ensure_ascii=False)[:600] + "\n")
354
 
355
+ return decoded.strip()
356
 
357
 
358
  # ----------------------------
 
363
  if user_input:
364
  st.session_state.chat_history.append({"role": "user", "content": user_input})
365
  with st.spinner("Thinking..."):
366
+ response = generate_answer(user_input)
367
  st.session_state.chat_history.append({"role": "assistant", "content": response})
368
 
369
  st.markdown("<div class='chat-wrap'>", unsafe_allow_html=True)
370
 
371
  for msg in st.session_state.chat_history:
372
  bubble_class = "user-bubble" if msg["role"] == "user" else "assistant-bubble"
373
+ # Streamlit markdown is fine here; our CSS fixes list spacing
374
+ st.markdown(f"<div class='bubble {bubble_class}'>", unsafe_allow_html=True)
375
+ st.markdown(msg["content"])
376
+ st.markdown("</div>", unsafe_allow_html=True)
 
377
 
378
  st.markdown("</div>", unsafe_allow_html=True)