Spaces:
Runtime error
Runtime error
Update app.py
Browse files
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 #
|
| 15 |
|
| 16 |
|
| 17 |
# ----------------------------
|
|
@@ -24,7 +24,7 @@ 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", "
|
| 28 |
TOP_P_DEFAULT = float(os.getenv("HAL_TOP_P", "0.9"))
|
| 29 |
TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.0"))
|
| 30 |
|
|
@@ -34,25 +34,22 @@ You are HAL, a NASA-focused research assistant.
|
|
| 34 |
Rules:
|
| 35 |
- Do not invent facts. If uncertain, say what is unknown and how to verify it.
|
| 36 |
- When TOOL_DATA is present and relevant, use it and reference the exact fields.
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
Output format:
|
| 39 |
## Direct Answer
|
| 40 |
## Key Details and Evidence
|
| 41 |
## If You Want to Go Deeper
|
|
|
|
| 42 |
""".strip()
|
| 43 |
|
| 44 |
NEXT_STEPS_INSTRUCTION = """
|
| 45 |
-
After
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
## Next Steps
|
| 51 |
-
Would you like to go deeper on one of these, or explore something else?
|
| 52 |
-
- Option 1
|
| 53 |
-
- Option 2
|
| 54 |
-
- Option 3
|
| 55 |
-
- Option 4
|
| 56 |
""".strip()
|
| 57 |
|
| 58 |
|
|
@@ -84,27 +81,18 @@ st.markdown(
|
|
| 84 |
align-self: flex-start;
|
| 85 |
}
|
| 86 |
|
| 87 |
-
/*
|
| 88 |
-
.bubble p {
|
| 89 |
-
|
| 90 |
-
}
|
| 91 |
-
.bubble p:last-child {
|
| 92 |
-
margin-bottom: 0;
|
| 93 |
-
}
|
| 94 |
|
| 95 |
.bubble ul, .bubble ol {
|
| 96 |
margin: 6px 0 6px 0;
|
| 97 |
padding-left: 20px;
|
| 98 |
}
|
|
|
|
| 99 |
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
}
|
| 103 |
-
|
| 104 |
-
/* Critical: kill paragraph margins inside list items (this is the big gap source) */
|
| 105 |
-
.bubble li p {
|
| 106 |
-
margin: 0;
|
| 107 |
-
}
|
| 108 |
|
| 109 |
.bubble h1, .bubble h2, .bubble h3 {
|
| 110 |
margin: 10px 0 6px 0;
|
|
@@ -123,7 +111,9 @@ st.markdown("<div class='page-subtitle'>Local instruction model with NASA tools<
|
|
| 123 |
|
| 124 |
with st.sidebar:
|
| 125 |
st.header("Controls")
|
| 126 |
-
|
|
|
|
|
|
|
| 127 |
temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)
|
| 128 |
top_p = st.slider("Top-p", 0.1, 1.0, TOP_P_DEFAULT, 0.05)
|
| 129 |
|
|
@@ -141,7 +131,6 @@ with st.sidebar:
|
|
| 141 |
]
|
| 142 |
st.rerun()
|
| 143 |
|
| 144 |
-
|
| 145 |
if "chat_history" not in st.session_state:
|
| 146 |
st.session_state.chat_history = [
|
| 147 |
{"role": "assistant", "content": "Hello. Ask me anything about NASA missions, astronomy, Mars rovers, near-Earth objects, or APOD."}
|
|
@@ -187,7 +176,6 @@ def normalize_list_spacing(text: str) -> str:
|
|
| 187 |
lines = text.splitlines()
|
| 188 |
cleaned: List[str] = []
|
| 189 |
in_list = False
|
| 190 |
-
|
| 191 |
list_item_re = re.compile(r"^\s*(?:[-*]|\d+\.)\s+")
|
| 192 |
|
| 193 |
for line in lines:
|
|
@@ -200,10 +188,8 @@ def normalize_list_spacing(text: str) -> str:
|
|
| 200 |
continue
|
| 201 |
|
| 202 |
if in_list and stripped == "":
|
| 203 |
-
# Skip blank lines inside a list block
|
| 204 |
continue
|
| 205 |
|
| 206 |
-
# If we hit a non-indented non-empty line, we are likely out of a list block
|
| 207 |
if stripped and not line.startswith((" ", "\t")):
|
| 208 |
in_list = False
|
| 209 |
|
|
@@ -213,11 +199,35 @@ def normalize_list_spacing(text: str) -> str:
|
|
| 213 |
|
| 214 |
|
| 215 |
def markdown_to_html(text: str) -> str:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
"""
|
| 217 |
-
|
|
|
|
|
|
|
| 218 |
"""
|
| 219 |
-
#
|
| 220 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
|
| 222 |
|
| 223 |
# ----------------------------
|
|
@@ -279,7 +289,7 @@ gen_pipe = load_llm(MODEL_ID)
|
|
| 279 |
# Prompt
|
| 280 |
# ----------------------------
|
| 281 |
def build_prompt(user_text: str, history: List[Dict[str, str]], tools: List[Dict[str, Any]]) -> str:
|
| 282 |
-
recent = history[-4:]
|
| 283 |
history_block = "\n".join(f"{m['role'].upper()}: {m['content']}" for m in recent)
|
| 284 |
tools_block = json.dumps(tools, indent=2, ensure_ascii=False) if tools else "None"
|
| 285 |
|
|
@@ -300,7 +310,6 @@ USER:
|
|
| 300 |
{user_text}
|
| 301 |
|
| 302 |
ASSISTANT:
|
| 303 |
-
Do not repeat the user's question. Answer directly, follow the required output format, and include the Next Steps section.
|
| 304 |
""".strip()
|
| 305 |
|
| 306 |
|
|
@@ -332,6 +341,7 @@ def generate(prompt: str, max_new_tokens: int, temperature: float, top_p: float)
|
|
| 332 |
text = out[0].get("generated_text", "")
|
| 333 |
ans = strip_prompt(text, prompt)
|
| 334 |
|
|
|
|
| 335 |
for stop in ["\nSYSTEM:", "\nUSER:", "\nASSISTANT:", "\nCONTEXT:", "\nTOOL_DATA:"]:
|
| 336 |
if stop in ans:
|
| 337 |
ans = ans.split(stop, 1)[0].rstrip()
|
|
@@ -342,11 +352,42 @@ def generate(prompt: str, max_new_tokens: int, temperature: float, top_p: float)
|
|
| 342 |
def get_response(user_text: str) -> str:
|
| 343 |
tools = plan_tools(user_text) if tool_mode else []
|
| 344 |
prompt = build_prompt(user_text, st.session_state.chat_history, tools)
|
| 345 |
-
answer = generate(prompt, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p)
|
| 346 |
|
| 347 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
answer = normalize_list_spacing(answer)
|
| 349 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
if verbose_tools and tools:
|
| 351 |
answer += "\n\n---\nTool payload snippets\n"
|
| 352 |
for t in tools:
|
|
@@ -371,8 +412,6 @@ st.markdown("<div class='chat-wrap'>", unsafe_allow_html=True)
|
|
| 371 |
|
| 372 |
for msg in st.session_state.chat_history:
|
| 373 |
bubble_class = "user-bubble" if msg["role"] == "user" else "assistant-bubble"
|
| 374 |
-
|
| 375 |
-
# Convert the message markdown to HTML ourselves so list spacing CSS applies reliably
|
| 376 |
html_body = markdown_to_html(msg["content"])
|
| 377 |
|
| 378 |
st.markdown(
|
|
|
|
| 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 |
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 |
|
|
|
|
| 34 |
Rules:
|
| 35 |
- Do not invent facts. If uncertain, say what is unknown and how to verify it.
|
| 36 |
- When TOOL_DATA is present and relevant, use it and reference the exact fields.
|
| 37 |
+
- Keep "Key Details and Evidence" to at most 5 bullets.
|
| 38 |
+
- Do not repeat the user's question.
|
| 39 |
|
| 40 |
+
Output format (use these exact headings):
|
| 41 |
## Direct Answer
|
| 42 |
## Key Details and Evidence
|
| 43 |
## If You Want to Go Deeper
|
| 44 |
+
## Next Steps
|
| 45 |
""".strip()
|
| 46 |
|
| 47 |
NEXT_STEPS_INSTRUCTION = """
|
| 48 |
+
After you finish the answer, add a short section titled "## Next Steps".
|
| 49 |
+
Suggest 3 to 5 concrete follow-up questions as bullet points.
|
| 50 |
+
Do not write placeholders like "Option 1" or "Option 2".
|
| 51 |
+
Do not ask the user to select options before answering.
|
| 52 |
+
Also include one bullet that offers to switch topics.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
""".strip()
|
| 54 |
|
| 55 |
|
|
|
|
| 81 |
align-self: flex-start;
|
| 82 |
}
|
| 83 |
|
| 84 |
+
/* Compact markdown inside bubbles */
|
| 85 |
+
.bubble p { margin: 0 0 8px 0; }
|
| 86 |
+
.bubble p:last-child { margin-bottom: 0; }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
.bubble ul, .bubble ol {
|
| 89 |
margin: 6px 0 6px 0;
|
| 90 |
padding-left: 20px;
|
| 91 |
}
|
| 92 |
+
.bubble li { margin: 2px 0; }
|
| 93 |
|
| 94 |
+
/* Critical: paragraph margins inside list items cause "giant gaps" */
|
| 95 |
+
.bubble li p { margin: 0; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
.bubble h1, .bubble h2, .bubble h3 {
|
| 98 |
margin: 10px 0 6px 0;
|
|
|
|
| 111 |
|
| 112 |
with st.sidebar:
|
| 113 |
st.header("Controls")
|
| 114 |
+
|
| 115 |
+
# Increase ceiling to allow deeper answers
|
| 116 |
+
max_new_tokens = st.slider("Max new tokens", 64, 1024, MAX_NEW_TOKENS_DEFAULT, 32)
|
| 117 |
temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)
|
| 118 |
top_p = st.slider("Top-p", 0.1, 1.0, TOP_P_DEFAULT, 0.05)
|
| 119 |
|
|
|
|
| 131 |
]
|
| 132 |
st.rerun()
|
| 133 |
|
|
|
|
| 134 |
if "chat_history" not in st.session_state:
|
| 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."}
|
|
|
|
| 176 |
lines = text.splitlines()
|
| 177 |
cleaned: List[str] = []
|
| 178 |
in_list = False
|
|
|
|
| 179 |
list_item_re = re.compile(r"^\s*(?:[-*]|\d+\.)\s+")
|
| 180 |
|
| 181 |
for line in lines:
|
|
|
|
| 188 |
continue
|
| 189 |
|
| 190 |
if in_list and stripped == "":
|
|
|
|
| 191 |
continue
|
| 192 |
|
|
|
|
| 193 |
if stripped and not line.startswith((" ", "\t")):
|
| 194 |
in_list = False
|
| 195 |
|
|
|
|
| 199 |
|
| 200 |
|
| 201 |
def markdown_to_html(text: str) -> str:
|
| 202 |
+
return md.markdown(text, extensions=["extra"])
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def looks_truncated(text: str) -> bool:
|
| 206 |
"""
|
| 207 |
+
Heuristic truncation detector:
|
| 208 |
+
- Missing '## Next Steps' section, or
|
| 209 |
+
- Ends without a likely sentence terminator
|
| 210 |
"""
|
| 211 |
+
if "## Next Steps" not in text:
|
| 212 |
+
return True
|
| 213 |
+
if text and text[-1] not in ".!?)]\"'":
|
| 214 |
+
return True
|
| 215 |
+
return False
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def continuation_prompt(previous_answer: str) -> str:
|
| 219 |
+
return f"""
|
| 220 |
+
SYSTEM:
|
| 221 |
+
Continue the assistant response exactly where it left off.
|
| 222 |
+
Do not repeat any text already written.
|
| 223 |
+
Finish any incomplete sentence and complete any missing sections.
|
| 224 |
+
Ensure the response includes the exact heading "## Next Steps" at the end.
|
| 225 |
+
|
| 226 |
+
ASSISTANT (previous, do not repeat):
|
| 227 |
+
{previous_answer}
|
| 228 |
+
|
| 229 |
+
ASSISTANT:
|
| 230 |
+
""".strip()
|
| 231 |
|
| 232 |
|
| 233 |
# ----------------------------
|
|
|
|
| 289 |
# Prompt
|
| 290 |
# ----------------------------
|
| 291 |
def build_prompt(user_text: str, history: List[Dict[str, str]], tools: List[Dict[str, Any]]) -> str:
|
| 292 |
+
recent = history[-4:]
|
| 293 |
history_block = "\n".join(f"{m['role'].upper()}: {m['content']}" for m in recent)
|
| 294 |
tools_block = json.dumps(tools, indent=2, ensure_ascii=False) if tools else "None"
|
| 295 |
|
|
|
|
| 310 |
{user_text}
|
| 311 |
|
| 312 |
ASSISTANT:
|
|
|
|
| 313 |
""".strip()
|
| 314 |
|
| 315 |
|
|
|
|
| 341 |
text = out[0].get("generated_text", "")
|
| 342 |
ans = strip_prompt(text, prompt)
|
| 343 |
|
| 344 |
+
# Trim if the model starts another internal block
|
| 345 |
for stop in ["\nSYSTEM:", "\nUSER:", "\nASSISTANT:", "\nCONTEXT:", "\nTOOL_DATA:"]:
|
| 346 |
if stop in ans:
|
| 347 |
ans = ans.split(stop, 1)[0].rstrip()
|
|
|
|
| 352 |
def get_response(user_text: str) -> str:
|
| 353 |
tools = plan_tools(user_text) if tool_mode else []
|
| 354 |
prompt = build_prompt(user_text, st.session_state.chat_history, tools)
|
|
|
|
| 355 |
|
| 356 |
+
answer = generate(
|
| 357 |
+
prompt,
|
| 358 |
+
max_new_tokens=max_new_tokens,
|
| 359 |
+
temperature=temperature,
|
| 360 |
+
top_p=top_p,
|
| 361 |
+
)
|
| 362 |
answer = normalize_list_spacing(answer)
|
| 363 |
|
| 364 |
+
# If truncated, do a continuation pass and append
|
| 365 |
+
if looks_truncated(answer):
|
| 366 |
+
prompt2 = continuation_prompt(answer)
|
| 367 |
+
cont = generate(
|
| 368 |
+
prompt2,
|
| 369 |
+
max_new_tokens=max_new_tokens,
|
| 370 |
+
temperature=temperature,
|
| 371 |
+
top_p=top_p,
|
| 372 |
+
)
|
| 373 |
+
cont = normalize_list_spacing(cont)
|
| 374 |
+
|
| 375 |
+
merged = (answer.rstrip() + "\n" + cont.lstrip()).strip()
|
| 376 |
+
|
| 377 |
+
# If still truncated, one more continuation pass (cap at 2 extra passes)
|
| 378 |
+
if looks_truncated(merged):
|
| 379 |
+
prompt3 = continuation_prompt(merged)
|
| 380 |
+
cont2 = generate(
|
| 381 |
+
prompt3,
|
| 382 |
+
max_new_tokens=max_new_tokens,
|
| 383 |
+
temperature=temperature,
|
| 384 |
+
top_p=top_p,
|
| 385 |
+
)
|
| 386 |
+
cont2 = normalize_list_spacing(cont2)
|
| 387 |
+
merged = (merged.rstrip() + "\n" + cont2.lstrip()).strip()
|
| 388 |
+
|
| 389 |
+
answer = merged
|
| 390 |
+
|
| 391 |
if verbose_tools and tools:
|
| 392 |
answer += "\n\n---\nTool payload snippets\n"
|
| 393 |
for t in tools:
|
|
|
|
| 412 |
|
| 413 |
for msg in st.session_state.chat_history:
|
| 414 |
bubble_class = "user-bubble" if msg["role"] == "user" else "assistant-bubble"
|
|
|
|
|
|
|
| 415 |
html_body = markdown_to_html(msg["content"])
|
| 416 |
|
| 417 |
st.markdown(
|