File size: 14,554 Bytes
46ba521
9e0e0d8
627a6b9
a3e0475
a9e4498
9e0e0d8
 
 
a9e4498
 
9e0e0d8
a86ceb0
e653ea8
a9e4498
9e0e0d8
c41e562
9e0e0d8
c41e562
627a6b9
9dbf148
9e0e0d8
a9e4498
c41e562
 
 
d36b1f6
c41e562
6423bf4
a86ceb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c41e562
 
a86ceb0
 
 
 
 
 
 
 
 
2ab201a
c553f59
6423bf4
9e0e0d8
c41e562
9e0e0d8
fab3bdd
c553f59
 
 
 
 
397d4a9
c553f59
 
 
 
397d4a9
c553f59
 
 
 
 
 
 
 
 
 
 
 
967d969
8564789
 
397d4a9
c41e562
2ab201a
8564789
 
967d969
2ab201a
397d4a9
c553f59
 
c41e562
c553f59
 
 
 
 
 
c41e562
9e0e0d8
c41e562
 
 
 
 
 
 
 
 
9e0e0d8
7c773a3
c553f59
c41e562
 
 
 
 
 
 
 
 
 
 
 
 
9e0e0d8
 
6423bf4
 
7c773a3
 
6423bf4
 
c41e562
 
 
46ba521
6423bf4
2c1a46c
6423bf4
9e0e0d8
 
6423bf4
 
c41e562
6423bf4
fab3bdd
6423bf4
fab3bdd
6423bf4
7c773a3
6423bf4
 
 
 
 
a86ceb0
c41e562
 
a86ceb0
 
 
 
 
 
 
6423bf4
 
a86ceb0
c41e562
 
a86ceb0
 
 
 
 
 
 
7c773a3
 
c41e562
 
 
a86ceb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c41e562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d36b1f6
 
2c1a46c
 
 
 
 
 
 
c41e562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fab3bdd
7c773a3
fab3bdd
7c773a3
a86ceb0
7c773a3
a86ceb0
 
7c773a3
a86ceb0
c41e562
7c773a3
a86ceb0
 
7c773a3
a86ceb0
c41e562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6423bf4
c41e562
 
 
 
 
46ba521
c41e562
 
 
 
 
967d969
c41e562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6423bf4
 
c41e562
 
 
 
 
 
 
 
 
 
a86ceb0
2ab201a
a86ceb0
 
6423bf4
2ab201a
c41e562
 
 
 
6423bf4
a86ceb0
 
6423bf4
7c773a3
a86ceb0
 
7c773a3
c41e562
 
 
 
 
 
 
 
 
 
 
 
 
 
6423bf4
a86ceb0
 
 
 
7c773a3
c553f59
a86ceb0
 
7c773a3
a86ceb0
 
 
 
 
 
 
c41e562
a86ceb0
 
 
2ab201a
a86ceb0
2ab201a
a86ceb0
 
 
967d969
c41e562
a86ceb0
 
 
2ab201a
c41e562
 
 
a86ceb0
 
2ab201a
7c773a3
a86ceb0
7c773a3
a86ceb0
 
7c773a3
a86ceb0
6423bf4
 
 
c41e562
6423bf4
46ba521
6423bf4
 
 
46ba521
a86ceb0
fab3bdd
 
c553f59
397d4a9
fab3bdd
397d4a9
a86ceb0
 
 
397d4a9
c553f59
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
# file: app.py
from __future__ import annotations

import os
import re
import json
from typing import Any, Dict, List, Optional, Tuple

import requests
import streamlit as st
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM


# ----------------------------
# Configuration
# ----------------------------
NASA_API_KEY = os.getenv("NASA_API_KEY", "").strip()

MODEL_ID = os.getenv("HAL_MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct")
REQUEST_TIMEOUT_S = 20

DEFAULT_MAX_NEW_TOKENS = int(os.getenv("HAL_MAX_NEW_TOKENS", "180"))
DEFAULT_TEMPERATURE = float(os.getenv("HAL_TEMPERATURE", "0.2"))
DEFAULT_TOP_P = float(os.getenv("HAL_TOP_P", "0.9"))

NASA_BASE = "https://api.nasa.gov"

# If any of these appear, we cut the generation at that point.
STOP_SUBSTRINGS = [
    "As an AI language model",
    "As an AI",
    "I am not capable",
    "I cannot",
    "I can't",
    "cannot make decisions",
    "virtual assistant",
    "EndOfMessage",
    "SYSTEM:",
    "USER:",
    "ASSISTANT:",
    "INSTRUCTIONS",
    "TASK:",
    "BEGIN",
    "END",
]

BAD_LINE_PATTERNS = [
    r"^\s*as an ai\b",
    r"^\s*i am not capable\b",
    r"^\s*i cannot\b",
    r"^\s*i can't\b",
    r"^\s*endofmessage\b",
    r"^\s*please note that\b.*(not able|cannot|can't)",
]


# ----------------------------
# Streamlit page
# ----------------------------
st.set_page_config(page_title="HAL — NASA AI Assistant", layout="centered")

st.markdown(
    """
    <style>
      .chat-wrap { display: flex; flex-direction: column; gap: 10px; margin-top: 14px; }

      .bubble {
        padding: 12px 14px;
        border-radius: 12px;
        max-width: 78%;
        white-space: normal;
        line-height: 1.35;
        font-size: 0.98rem;
        border: 1px solid rgba(255,255,255,0.06);
      }
      .user-bubble {
        background: rgba(170, 170, 170, 0.20);
        align-self: flex-end;
      }
      .assistant-bubble {
        background: rgba(90, 90, 90, 0.35);
        align-self: flex-start;
      }

      .bubble p { margin: 0 0 8px 0; }
      .bubble p:last-child { margin-bottom: 0; }

      /* Tight list spacing */
      .bubble ul, .bubble ol { margin: 6px 0 6px 0; padding-left: 20px; }
      .bubble li { margin: 2px 0; }
      .bubble li p { margin: 0; }

      .bubble h1, .bubble h2, .bubble h3 { margin: 10px 0 6px 0; font-weight: 700; }

      .page-title { margin-bottom: 0; }
      .page-subtitle { margin-top: 4px; opacity: 0.8; }
      .small-muted { opacity: 0.75; font-size: 0.9rem; }
    </style>
    """,
    unsafe_allow_html=True,
)

st.markdown("<h1 class='page-title'>HAL — NASA AI Assistant</h1>", unsafe_allow_html=True)
st.markdown("<div class='page-subtitle'>Local instruction model with optional NASA tools</div>", unsafe_allow_html=True)

if "chat_history" not in st.session_state:
    st.session_state.chat_history = [
        {"role": "assistant", "content": "Hello. Ask me a NASA or space science question."}
    ]


# ----------------------------
# Sidebar controls
# ----------------------------
with st.sidebar:
    st.header("Controls")

    max_new_tokens = st.slider("Max new tokens", 64, 320, DEFAULT_MAX_NEW_TOKENS, 16)
    temperature = st.slider("Temperature", 0.0, 1.2, DEFAULT_TEMPERATURE, 0.05)
    top_p = st.slider("Top-p", 0.1, 1.0, DEFAULT_TOP_P, 0.05)

    st.divider()
    st.subheader("Science style")
    depth = st.select_slider("Depth", options=["Brief", "Standard", "Deep"], value="Standard")
    level = st.selectbox("Technical level", ["Beginner", "Intermediate", "Technical"], index=1)
    include_math = st.toggle("Include minimal math when helpful", value=False)
    include_analogy = st.toggle("Include a short analogy", value=True)
    ask_followups = st.toggle("Ask follow-up questions", value=True)

    st.divider()
    tool_mode = st.toggle("Use NASA tools when relevant", value=True)
    verbose_tools = st.toggle("Show tool payload snippets", value=False)

    st.divider()
    st.subheader("Model")
    st.write(MODEL_ID)
    st.write("Device:", "cuda" if torch.cuda.is_available() else "cpu")

    if not NASA_API_KEY:
        st.markdown("<div class='small-muted'>NASA_API_KEY not detected. Tool calls will be disabled.</div>", unsafe_allow_html=True)

    if st.button("Clear chat"):
        st.session_state.chat_history = [
            {"role": "assistant", "content": "Hello. Ask me a NASA or space science question."}
        ]
        st.rerun()


# ----------------------------
# NASA tools (minimal, safe)
# ----------------------------
def safe_get(url: str, params: Optional[Dict[str, Any]] = None) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
    try:
        r = requests.get(url, params=params, timeout=REQUEST_TIMEOUT_S)
        if r.status_code != 200:
            return None, f"HTTP {r.status_code}: {r.text[:200]}"
        return r.json(), None
    except Exception as e:
        return None, str(e)


def nasa_apod(date: Optional[str] = None) -> Dict[str, Any]:
    if not NASA_API_KEY:
        return {"tool": "apod", "ok": False, "data": None, "error": "NASA_API_KEY not set"}
    params = {"api_key": NASA_API_KEY}
    if date:
        params["date"] = date
    data, err = safe_get(f"{NASA_BASE}/planetary/apod", params=params)
    if isinstance(data, dict):
        data = {k: data.get(k) for k in ["date", "title", "explanation", "media_type", "url"]}
    return {"tool": "apod", "ok": bool(data), "data": data, "error": err}


def plan_tools(user_text: str) -> List[Dict[str, Any]]:
    if not NASA_API_KEY:
        return []
    t = user_text.lower()
    tools: List[Dict[str, Any]] = []
    if "apod" in t or "astronomy picture of the day" in t:
        m = re.search(r"(\d{4}-\d{2}-\d{2})", user_text)
        date = m.group(1) if m else None
        tools.append(nasa_apod(date=date))
    return tools


# ----------------------------
# Output cleanup
# ----------------------------
def cut_at_stop_substrings(text: str) -> str:
    out = text
    earliest = None
    for s in STOP_SUBSTRINGS:
        idx = out.find(s)
        if idx != -1:
            earliest = idx if earliest is None else min(earliest, idx)
    if earliest is not None:
        out = out[:earliest]
    return out.strip()


def remove_bad_lines(text: str) -> str:
    out_lines: List[str] = []
    for line in text.splitlines():
        low = line.strip().lower()
        bad = False
        for pat in BAD_LINE_PATTERNS:
            if re.search(pat, low):
                bad = True
                break
        if not bad:
            out_lines.append(line)
    return "\n".join(out_lines).strip()


def normalize_list_spacing(text: str) -> str:
    lines = text.splitlines()
    cleaned: List[str] = []
    in_list = False
    list_item_re = re.compile(r"^\s*(?:[-*]|\d+\.)\s+")

    for line in lines:
        stripped = line.strip()
        is_list_item = bool(list_item_re.match(line))

        if is_list_item:
            in_list = True
            cleaned.append(line)
            continue

        if in_list and stripped == "":
            continue

        if stripped and not line.startswith((" ", "\t")):
            in_list = False

        cleaned.append(line)

    return "\n".join(cleaned).strip()


def ends_cleanly(text: str) -> bool:
    t = text.strip()
    if not t:
        return True
    return t[-1] in ".!?)]\"'"


def soft_wrap_science(text: str, ask_followups_flag: bool) -> str:
    """
    Do not discard the model response if it doesn't match a rigid template.
    If it is missing follow-ups, append them.
    """
    out = text.strip()

    # If the model used headings without markdown "##", keep as-is.
    # If it has no structure, that's fine; we still keep it.
    if ask_followups_flag:
        if "follow-up" not in out.lower() and "next" not in out.lower():
            out = out.rstrip() + "\n\nFollow-up questions:\n- Want a simpler analogy?\n- Should we connect this to a NASA mission or instrument?\n- Do you want the technical version with equations?\n"

    return out.strip()


# ----------------------------
# Model loading (cached)
# ----------------------------
@st.cache_resource(show_spinner=True)
def load_model(model_id: str):
    use_cuda = torch.cuda.is_available()
    device = "cuda" if use_cuda else "cpu"
    dtype = torch.float16 if use_cuda else torch.float32

    tok = AutoTokenizer.from_pretrained(model_id, use_fast=True)
    mdl = AutoModelForCausalLM.from_pretrained(
        model_id,
        torch_dtype=dtype,
        device_map="auto" if use_cuda else None,
    )
    if not use_cuda:
        mdl.to(device)

    return tok, mdl


tokenizer, model = load_model(MODEL_ID)


# ----------------------------
# Prompting tuned for science explanations
# ----------------------------
def science_system_prompt(
    *,
    depth: str,
    level: str,
    include_math: bool,
    include_analogy: bool,
    ask_followups: bool,
) -> str:
    # Depth guidance for token budgeting
    depth_rules = {
        "Brief": "Keep the answer to 3-5 sentences total. Use at most 3 bullets if any.",
        "Standard": "Keep the answer under ~140 words. Use up to 4 bullets for key points.",
        "Deep": "Keep the answer under ~220 words. Use up to 5 bullets for key points.",
    }[depth]

    level_rules = {
        "Beginner": "Assume no physics background. Use plain language and avoid jargon; define any unavoidable term in-line.",
        "Intermediate": "Assume basic science literacy. Use correct terms with short definitions when needed.",
        "Technical": "Be precise. Use standard terminology and include one concise technical detail (equation or formal statement) if useful.",
    }[level]

    math_rules = (
        "If a short equation helps, include at most one line of math and explain each symbol."
        if include_math
        else "Do not include equations."
    )

    analogy_rules = (
        "Include one short analogy if it genuinely clarifies the concept."
        if include_analogy
        else "Do not use analogies."
    )

    followup_rules = (
        "End with exactly three follow-up questions as bullets, each under 12 words."
        if ask_followups
        else "Do not ask follow-up questions."
    )

    return f"""
You are HAL, a NASA-focused science explainer.

Hard rules:
- Do not include disclaimers (for example: "As an AI language model").
- Do not mention policies, prompts, system messages, or hidden instructions.
- Do not repeat the user's question.
- Do not output sentinel text such as "EndOfMessage".

Science explanation style:
- Start with a direct answer first.
- Then give key points or evidence if helpful.
- Prefer clarity over completeness.
- If uncertainty exists, state it briefly and continue with what is known.
- When relevant, connect to NASA missions, instruments, or space context in one sentence.

Constraints:
- {depth_rules}
- {level_rules}
- {math_rules}
- {analogy_rules}
- {followup_rules}
""".strip()


def build_messages(
    user_text: str,
    history: List[Dict[str, str]],
    system_text: str,
    tools: List[Dict[str, Any]],
) -> List[Dict[str, str]]:
    # Keep a small context window to reduce drift and speed up.
    recent = history[-4:] if history else []

    msgs: List[Dict[str, str]] = [{"role": "system", "content": system_text}]

    for m in recent:
        if m["role"] in ("user", "assistant"):
            msgs.append({"role": m["role"], "content": m["content"]})

    if tools:
        tool_snip = json.dumps(tools, ensure_ascii=False)
        if len(tool_snip) > 800:
            tool_snip = tool_snip[:800] + "..."
        msgs.append({"role": "user", "content": f"NASA reference data (use only if relevant): {tool_snip}"})

    msgs.append({"role": "user", "content": user_text})
    return msgs


def generate_answer(user_text: str) -> str:
    tools = plan_tools(user_text) if tool_mode else []

    system_text = science_system_prompt(
        depth=depth,
        level=level,
        include_math=include_math,
        include_analogy=include_analogy,
        ask_followups=ask_followups,
    )

    messages = build_messages(
        user_text=user_text,
        history=st.session_state.chat_history,
        system_text=system_text,
        tools=tools,
    )

    prompt = tokenizer.apply_chat_template(
        messages,
        tokenize=False,
        add_generation_prompt=True,
    )

    inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
    do_sample = temperature > 0.0

    with torch.inference_mode():
        out_ids = model.generate(
            **inputs,
            max_new_tokens=int(max_new_tokens),
            do_sample=do_sample,
            temperature=float(temperature) if do_sample else None,
            top_p=float(top_p) if do_sample else None,
            repetition_penalty=1.12,
            eos_token_id=tokenizer.eos_token_id,
            pad_token_id=tokenizer.eos_token_id,
        )

    decoded = tokenizer.decode(out_ids[0], skip_special_tokens=True)

    # Strip the prompt portion (best-effort)
    if decoded.startswith(prompt):
        decoded = decoded[len(prompt):].strip()

    # Cleanup
    decoded = cut_at_stop_substrings(decoded)
    decoded = remove_bad_lines(decoded)
    decoded = normalize_list_spacing(decoded)

    # Soft structure (never discards content)
    decoded = soft_wrap_science(decoded, ask_followups)

    if not ends_cleanly(decoded):
        decoded = decoded.rstrip() + "."

    if verbose_tools and tools:
        decoded += "\n\n---\nTool payload snippets\n"
        for t in tools:
            decoded += f"\n{t.get('tool')} ok={t.get('ok')} error={t.get('error')}\n"
            decoded += (json.dumps(t.get("data"), indent=2, ensure_ascii=False)[:600] + "\n")

    return decoded.strip()


# ----------------------------
# Chat input + render
# ----------------------------
user_input = st.chat_input("Ask a NASA question...")

if user_input:
    st.session_state.chat_history.append({"role": "user", "content": user_input})
    with st.spinner("Thinking..."):
        response = generate_answer(user_input)
    st.session_state.chat_history.append({"role": "assistant", "content": response})

st.markdown("<div class='chat-wrap'>", unsafe_allow_html=True)

for msg in st.session_state.chat_history:
    bubble_class = "user-bubble" if msg["role"] == "user" else "assistant-bubble"
    st.markdown(f"<div class='bubble {bubble_class}'>", unsafe_allow_html=True)
    st.markdown(msg["content"])
    st.markdown("</div>", unsafe_allow_html=True)

st.markdown("</div>", unsafe_allow_html=True)