CCockrum commited on
Commit
2c1a46c
·
verified ·
1 Parent(s): d36b1f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -114
app.py CHANGED
@@ -11,7 +11,7 @@ import requests
11
  import streamlit as st
12
  import torch
13
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
14
- import markdown as md # requirements: markdown>=3.6
15
 
16
 
17
  # ----------------------------
@@ -24,40 +24,46 @@ 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", "384"))
 
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 = [
32
- "## Direct Answer",
33
- "## Key Details and Evidence",
34
- "## If You Want to Go Deeper",
35
  "## Next Steps",
36
  ]
37
 
38
  AGENT_INSTRUCTIONS = """
39
  You are HAL, a NASA-focused research assistant.
40
 
41
- Rules:
42
- - Do not invent facts. If uncertain, say what is unknown and how to verify it.
43
- - When TOOL_DATA is present and relevant, use it and reference the exact fields.
44
- - Keep "Key Details and Evidence" to at most 5 bullets.
45
  - Do not repeat the user's question.
46
- - Follow the output format exactly and do not reorder the sections.
 
 
 
 
 
 
 
 
 
 
 
47
 
48
- Output format (use these exact headings):
49
- ## Direct Answer
50
- ## Key Details and Evidence
51
- ## If You Want to Go Deeper
52
  ## Next Steps
 
53
  """.strip()
54
 
55
  NEXT_STEPS_INSTRUCTION = """
56
- After you finish the answer, add a short section titled "## Next Steps".
57
- Suggest 3 to 5 concrete follow-up questions as bullet points.
58
- Do not write placeholders like "Option 1" or "Option 2".
59
- Do not ask the user to select options before answering.
60
- Also include one bullet that offers to switch topics.
61
  """.strip()
62
 
63
 
@@ -98,8 +104,6 @@ st.markdown(
98
  padding-left: 20px;
99
  }
100
  .bubble li { margin: 2px 0; }
101
-
102
- /* Critical: paragraph margins inside list items cause "giant gaps" */
103
  .bubble li p { margin: 0; }
104
 
105
  .bubble h1, .bubble h2, .bubble h3 {
@@ -119,7 +123,9 @@ st.markdown("<div class='page-subtitle'>Local instruction model with NASA tools<
119
 
120
  with st.sidebar:
121
  st.header("Controls")
122
- max_new_tokens = st.slider("Max new tokens", 64, 1024, MAX_NEW_TOKENS_DEFAULT, 32)
 
 
123
  temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)
124
  top_p = st.slider("Top-p", 0.1, 1.0, TOP_P_DEFAULT, 0.05)
125
 
@@ -133,13 +139,13 @@ with st.sidebar:
133
 
134
  if st.button("Clear chat"):
135
  st.session_state.chat_history = [
136
- {"role": "assistant", "content": "Hello. Ask me anything about NASA missions, astronomy, Mars rovers, near-Earth objects, or APOD."}
137
  ]
138
  st.rerun()
139
 
140
  if "chat_history" not in st.session_state:
141
  st.session_state.chat_history = [
142
- {"role": "assistant", "content": "Hello. Ask me anything about NASA missions, astronomy, Mars rovers, near-Earth objects, or APOD."}
143
  ]
144
 
145
 
@@ -206,109 +212,77 @@ def has_all_sections(text: str) -> bool:
206
  return all(h in text for h in HEADINGS)
207
 
208
 
 
 
 
 
 
 
 
209
  def looks_truncated(text: str) -> bool:
210
- """
211
- Truncation heuristic:
212
- - Missing required sections, or
213
- - Ends mid-sentence
214
- """
215
  if not has_all_sections(text):
216
  return True
217
- if text and text[-1] not in ".!?)]\"'":
218
  return True
219
  return False
220
 
221
 
222
- def headings_present(text: str) -> List[str]:
223
- return [h for h in HEADINGS if h in text]
224
-
225
-
226
  def continuation_prompt(existing_answer: str) -> str:
227
- present = headings_present(existing_answer)
228
- tail = existing_answer[-1200:] # enough to anchor continuation, not too long
229
-
230
  return f"""
231
  SYSTEM:
232
- You are continuing an unfinished assistant response.
233
 
234
  Rules:
235
- - Continue from where the text ends. Do not restart the response.
236
- - Do not repeat any headings or sections that already exist.
237
- - Do not repeat any sentences already written.
238
- - Only add the missing tail content and complete any incomplete sentence.
239
- - If "## Next Steps" already exists, continue within it rather than creating a new one.
240
- - If a section is missing, add only the missing sections using the required headings.
241
-
242
- Headings already present:
243
- {present}
244
 
245
- Text to continue (tail excerpt):
246
  {tail}
247
 
248
  ASSISTANT:
249
  """.strip()
250
 
251
 
252
- def continuation_prompt_strict(existing_answer: str) -> str:
253
- """
254
- Used if the first continuation attempt restarts the answer.
255
- """
256
- tail = existing_answer[-800:]
257
  return f"""
258
  SYSTEM:
259
- Continue exactly from the last character of the provided text.
260
- Do not output any headings except those that are missing.
261
- Do not output "## Direct Answer" or "## Key Details and Evidence" if they already exist.
262
- Do not repeat any content.
263
 
264
- Text (ends at the last line):
265
  {tail}
266
 
267
  ASSISTANT:
268
  """.strip()
269
 
270
 
271
- def starts_with_repeated_heading(cont: str, existing: str) -> bool:
272
  """
273
- Detect "restart" continuations that begin by repeating earlier sections.
274
  """
275
- cont_strip = cont.lstrip()
276
  for h in HEADINGS:
277
- if cont_strip.startswith(h) and h in existing:
278
- return True
279
- return False
280
 
281
 
282
  def trim_overlap(existing: str, cont: str, max_window: int = 1200) -> str:
283
- """
284
- Remove duplicated overlap where cont starts with content that matches
285
- the end of existing.
286
- """
287
  a = existing[-max_window:]
288
  b = cont
289
-
290
- # Find the largest suffix of a that is a prefix of b
291
  max_k = 0
292
  max_len = min(len(a), len(b), max_window)
293
  for k in range(1, max_len + 1):
294
  if a[-k:] == b[:k]:
295
  max_k = k
296
-
297
  if max_k > 0:
298
  return b[max_k:].lstrip()
299
-
300
- # Also handle line-based duplication (common in markdown)
301
- a_lines = a.splitlines()
302
- b_lines = b.splitlines()
303
- max_line_k = 0
304
- max_line_len = min(len(a_lines), len(b_lines), 80)
305
- for k in range(1, max_line_len + 1):
306
- if a_lines[-k:] == b_lines[:k]:
307
- max_line_k = k
308
-
309
- if max_line_k > 0:
310
- return "\n".join(b_lines[max_line_k:]).lstrip()
311
-
312
  return cont
313
 
314
 
@@ -371,7 +345,8 @@ gen_pipe = load_llm(MODEL_ID)
371
  # Prompt
372
  # ----------------------------
373
  def build_prompt(user_text: str, history: List[Dict[str, str]], tools: List[Dict[str, Any]]) -> str:
374
- recent = history[-4:]
 
375
  history_block = "\n".join(f"{m['role'].upper()}: {m['content']}" for m in recent)
376
  tools_block = json.dumps(tools, indent=2, ensure_ascii=False) if tools else "None"
377
 
@@ -413,7 +388,7 @@ def generate(prompt: str, max_new_tokens: int, temperature: float, top_p: float)
413
  do_sample=do_sample,
414
  temperature=float(temperature) if do_sample else None,
415
  top_p=float(top_p) if do_sample else None,
416
- repetition_penalty=1.10,
417
  return_full_text=True,
418
  )
419
 
@@ -423,6 +398,7 @@ def generate(prompt: str, max_new_tokens: int, temperature: float, top_p: float)
423
  text = out[0].get("generated_text", "")
424
  ans = strip_prompt(text, prompt)
425
 
 
426
  for stop in ["\nSYSTEM:", "\nUSER:", "\nASSISTANT:", "\nCONTEXT:", "\nTOOL_DATA:"]:
427
  if stop in ans:
428
  ans = ans.split(stop, 1)[0].rstrip()
@@ -430,26 +406,6 @@ def generate(prompt: str, max_new_tokens: int, temperature: float, top_p: float)
430
  return ans.strip()
431
 
432
 
433
- def generate_continuation(existing_answer: str) -> str:
434
- """
435
- One continuation attempt with restart detection and overlap trimming.
436
- If it restarts, retry once with a stricter continuation prompt.
437
- """
438
- p1 = continuation_prompt(existing_answer)
439
- c1 = generate(p1, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p)
440
- c1 = normalize_list_spacing(c1)
441
-
442
- if starts_with_repeated_heading(c1, existing_answer):
443
- p2 = continuation_prompt_strict(existing_answer)
444
- c2 = generate(p2, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p)
445
- c2 = normalize_list_spacing(c2)
446
- c2 = trim_overlap(existing_answer, c2)
447
- return c2.strip()
448
-
449
- c1 = trim_overlap(existing_answer, c1)
450
- return c1.strip()
451
-
452
-
453
  def get_response(user_text: str) -> str:
454
  tools = plan_tools(user_text) if tool_mode else []
455
  prompt = build_prompt(user_text, st.session_state.chat_history, tools)
@@ -457,16 +413,26 @@ def get_response(user_text: str) -> str:
457
  answer = generate(prompt, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p)
458
  answer = normalize_list_spacing(answer)
459
 
460
- # Continuation passes (up to 2), guarded against restarts and overlap duplicates
461
  if looks_truncated(answer):
462
- cont = generate_continuation(answer)
 
 
 
 
463
  if cont:
464
- answer = (answer.rstrip() + "\n" + cont.lstrip()).strip()
465
-
466
- if looks_truncated(answer):
467
- cont2 = generate_continuation(answer)
468
- if cont2:
469
- answer = (answer.rstrip() + "\n" + cont2.lstrip()).strip()
 
 
 
 
 
 
470
 
471
  if verbose_tools and tools:
472
  answer += "\n\n---\nTool payload snippets\n"
 
11
  import streamlit as st
12
  import torch
13
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
14
+ import markdown as md
15
 
16
 
17
  # ----------------------------
 
24
  MODEL_ID = os.getenv("HAL_MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct")
25
  REQUEST_TIMEOUT_S = 20
26
 
27
+ # Keep defaults short to avoid truncation on CPU
28
+ MAX_NEW_TOKENS_DEFAULT = int(os.getenv("HAL_MAX_NEW_TOKENS", "180"))
29
  TOP_P_DEFAULT = float(os.getenv("HAL_TOP_P", "0.9"))
30
  TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.0"))
31
 
32
+ # Compact headings: fewer sections = fewer tokens = fewer truncations
33
  HEADINGS = [
34
+ "## Answer",
35
+ "## Key Points",
 
36
  "## Next Steps",
37
  ]
38
 
39
  AGENT_INSTRUCTIONS = """
40
  You are HAL, a NASA-focused research assistant.
41
 
42
+ Hard constraints:
43
+ - Be concise. The entire response must be short and complete.
 
 
44
  - Do not repeat the user's question.
45
+ - Do not include filler, disclaimers, or meta commentary.
46
+ - If you are uncertain, state it in one short sentence and suggest how to verify.
47
+
48
+ If TOOL_DATA is present and relevant:
49
+ - Use it and reference exact fields from TOOL_DATA.
50
+
51
+ Output format (use these exact headings and in this order):
52
+ ## Answer
53
+ (2 to 4 sentences)
54
+
55
+ ## Key Points
56
+ (2 to 4 bullet points max)
57
 
 
 
 
 
58
  ## Next Steps
59
+ (3 short follow-up questions as bullets)
60
  """.strip()
61
 
62
  NEXT_STEPS_INSTRUCTION = """
63
+ In "## Next Steps", list exactly 3 follow-up questions as bullet points.
64
+ Do not write placeholders (no "Option 1").
65
+ Do not ask the user to choose options before answering.
66
+ Keep each follow-up question under 12 words.
 
67
  """.strip()
68
 
69
 
 
104
  padding-left: 20px;
105
  }
106
  .bubble li { margin: 2px 0; }
 
 
107
  .bubble li p { margin: 0; }
108
 
109
  .bubble h1, .bubble h2, .bubble h3 {
 
123
 
124
  with st.sidebar:
125
  st.header("Controls")
126
+
127
+ # Keep the UI capped lower to encourage short completions
128
+ max_new_tokens = st.slider("Max new tokens", 64, 384, MAX_NEW_TOKENS_DEFAULT, 16)
129
  temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)
130
  top_p = st.slider("Top-p", 0.1, 1.0, TOP_P_DEFAULT, 0.05)
131
 
 
139
 
140
  if st.button("Clear chat"):
141
  st.session_state.chat_history = [
142
+ {"role": "assistant", "content": "Hello. Ask me a NASA or space science question."}
143
  ]
144
  st.rerun()
145
 
146
  if "chat_history" not in st.session_state:
147
  st.session_state.chat_history = [
148
+ {"role": "assistant", "content": "Hello. Ask me a NASA or space science question."}
149
  ]
150
 
151
 
 
212
  return all(h in text for h in HEADINGS)
213
 
214
 
215
+ def ends_cleanly(text: str) -> bool:
216
+ t = text.strip()
217
+ if not t:
218
+ return True
219
+ return t[-1] in ".!?)]\"'"
220
+
221
+
222
  def looks_truncated(text: str) -> bool:
223
+ # Missing structure OR ends mid-sentence
 
 
 
 
224
  if not has_all_sections(text):
225
  return True
226
+ if not ends_cleanly(text):
227
  return True
228
  return False
229
 
230
 
 
 
 
 
231
  def continuation_prompt(existing_answer: str) -> str:
232
+ tail = existing_answer[-900:]
 
 
233
  return f"""
234
  SYSTEM:
235
+ Continue only the unfinished ending of the assistant response.
236
 
237
  Rules:
238
+ - Do not repeat any headings already present.
239
+ - Do not restart sections.
240
+ - Write only what is needed to finish the last incomplete sentence and, if missing,
241
+ finish missing bullets in "## Next Steps".
242
+ - Keep it short.
 
 
 
 
243
 
244
+ Text to continue (tail):
245
  {tail}
246
 
247
  ASSISTANT:
248
  """.strip()
249
 
250
 
251
+ def finish_last_sentence_prompt(existing_answer: str) -> str:
252
+ tail = existing_answer[-600:]
 
 
 
253
  return f"""
254
  SYSTEM:
255
+ Finish the last sentence only. Output one short completion fragment.
256
+ Do not add headings. Do not add new paragraphs. Do not repeat any text.
 
 
257
 
258
+ Text (tail):
259
  {tail}
260
 
261
  ASSISTANT:
262
  """.strip()
263
 
264
 
265
+ def trim_restart_sections(existing: str, cont: str) -> str:
266
  """
267
+ If the continuation restarts at a heading, cut it from that point.
268
  """
269
+ cont_l = cont.lstrip()
270
  for h in HEADINGS:
271
+ if h in existing and cont_l.startswith(h):
272
+ return ""
273
+ return cont
274
 
275
 
276
  def trim_overlap(existing: str, cont: str, max_window: int = 1200) -> str:
 
 
 
 
277
  a = existing[-max_window:]
278
  b = cont
 
 
279
  max_k = 0
280
  max_len = min(len(a), len(b), max_window)
281
  for k in range(1, max_len + 1):
282
  if a[-k:] == b[:k]:
283
  max_k = k
 
284
  if max_k > 0:
285
  return b[max_k:].lstrip()
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  return cont
287
 
288
 
 
345
  # Prompt
346
  # ----------------------------
347
  def build_prompt(user_text: str, history: List[Dict[str, str]], tools: List[Dict[str, Any]]) -> str:
348
+ # Keep history small to reduce verbosity
349
+ recent = history[-2:]
350
  history_block = "\n".join(f"{m['role'].upper()}: {m['content']}" for m in recent)
351
  tools_block = json.dumps(tools, indent=2, ensure_ascii=False) if tools else "None"
352
 
 
388
  do_sample=do_sample,
389
  temperature=float(temperature) if do_sample else None,
390
  top_p=float(top_p) if do_sample else None,
391
+ repetition_penalty=1.12,
392
  return_full_text=True,
393
  )
394
 
 
398
  text = out[0].get("generated_text", "")
399
  ans = strip_prompt(text, prompt)
400
 
401
+ # Stop if model starts emitting another role block
402
  for stop in ["\nSYSTEM:", "\nUSER:", "\nASSISTANT:", "\nCONTEXT:", "\nTOOL_DATA:"]:
403
  if stop in ans:
404
  ans = ans.split(stop, 1)[0].rstrip()
 
406
  return ans.strip()
407
 
408
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
409
  def get_response(user_text: str) -> str:
410
  tools = plan_tools(user_text) if tool_mode else []
411
  prompt = build_prompt(user_text, st.session_state.chat_history, tools)
 
413
  answer = generate(prompt, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p)
414
  answer = normalize_list_spacing(answer)
415
 
416
+ # One short continuation attempt if needed
417
  if looks_truncated(answer):
418
+ p2 = continuation_prompt(answer)
419
+ cont = generate(p2, max_new_tokens=min(max_new_tokens, 128), temperature=temperature, top_p=top_p)
420
+ cont = normalize_list_spacing(cont)
421
+ cont = trim_restart_sections(answer, cont)
422
+ cont = trim_overlap(answer, cont)
423
  if cont:
424
+ answer = (answer.rstrip() + " " + cont.lstrip()).strip()
425
+
426
+ # If still mid-sentence, do a tiny "finish the last sentence" pass
427
+ if not ends_cleanly(answer):
428
+ p3 = finish_last_sentence_prompt(answer)
429
+ frag = generate(p3, max_new_tokens=40, temperature=temperature, top_p=top_p)
430
+ frag = frag.strip()
431
+ frag = trim_restart_sections(answer, frag)
432
+ frag = trim_overlap(answer, frag)
433
+ if frag:
434
+ # Avoid adding a new paragraph; just finish the sentence
435
+ answer = (answer.rstrip() + " " + frag.lstrip()).strip()
436
 
437
  if verbose_tools and tools:
438
  answer += "\n\n---\nTool payload snippets\n"