Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,137 +1,116 @@
|
|
| 1 |
-
# hal_bot.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
import os
|
| 4 |
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import requests
|
| 6 |
-
import torch
|
| 7 |
import streamlit as st
|
| 8 |
-
from langchain_community.llms import HuggingFaceEndpoint
|
| 9 |
-
from langchain.llms import HuggingFacePipeline
|
| 10 |
-
from langchain_core.prompts import PromptTemplate
|
| 11 |
-
from langchain_core.output_parsers import StrOutputParser
|
| 12 |
-
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
| 13 |
from langdetect import detect
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
# ✅ Switched to Flan-T5 Model
|
| 16 |
-
MODEL_ID = "google/flan-t5-large"
|
| 17 |
-
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 18 |
-
model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_ID)
|
| 19 |
-
pipe = pipeline("text2text-generation", model=model, tokenizer=tokenizer, device=0 if torch.cuda.is_available() else -1)
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
# ✅ Device setup
|
| 23 |
-
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 24 |
-
print(f"✅ Using device: {device}")
|
| 25 |
-
|
| 26 |
-
# ✅ Environment Variables
|
| 27 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 28 |
-
if HF_TOKEN is None:
|
| 29 |
-
raise ValueError("HF_TOKEN is not set. Please add it to your environment variables.")
|
| 30 |
|
|
|
|
|
|
|
|
|
|
| 31 |
NASA_API_KEY = os.getenv("NASA_API_KEY")
|
| 32 |
-
if
|
| 33 |
-
raise ValueError("NASA_API_KEY is not set.
|
| 34 |
-
|
| 35 |
-
# ✅ Streamlit Setup
|
| 36 |
-
st.set_page_config(page_title="HAL - NASA ChatBot", page_icon="🚀")
|
| 37 |
-
|
| 38 |
-
if "chat_history" not in st.session_state:
|
| 39 |
-
st.session_state.chat_history = [{"role": "assistant", "content": "Hello! How can I assist you today?"}]
|
| 40 |
-
|
| 41 |
-
def load_local_llm(model_id):
|
| 42 |
-
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 43 |
-
model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
|
| 44 |
-
return pipeline("text2text-generation", model=model, tokenizer=tokenizer, device=0 if torch.cuda.is_available() else -1)
|
| 45 |
-
|
| 46 |
-
|
| 47 |
|
|
|
|
|
|
|
| 48 |
|
| 49 |
-
|
|
|
|
|
|
|
| 50 |
|
| 51 |
-
|
| 52 |
-
return HuggingFaceEndpoint(
|
| 53 |
-
repo_id=model_id,
|
| 54 |
-
max_new_tokens=max_new_tokens,
|
| 55 |
-
temperature=temperature,
|
| 56 |
-
token=HF_TOKEN,
|
| 57 |
-
task="text2text-generation",
|
| 58 |
-
device=-1 if device == "cpu" else 0
|
| 59 |
-
)
|
| 60 |
-
|
| 61 |
-
def ensure_english(text):
|
| 62 |
-
try:
|
| 63 |
-
detected_lang = detect(text)
|
| 64 |
-
if detected_lang != "en":
|
| 65 |
-
return "⚠️ Sorry, I only respond in English. Can you rephrase your question?"
|
| 66 |
-
except:
|
| 67 |
-
return "⚠️ Language detection failed. Please ask your question again."
|
| 68 |
-
return text
|
| 69 |
-
|
| 70 |
-
def get_response(system_message, chat_history, user_text, max_new_tokens=500):
|
| 71 |
-
filtered_history = "\n".join(
|
| 72 |
-
f"{msg['role'].capitalize()}: {msg['content']}" for msg in chat_history[-5:]
|
| 73 |
-
)
|
| 74 |
-
|
| 75 |
-
prompt = PromptTemplate.from_template(
|
| 76 |
-
"""
|
| 77 |
-
You are a helpful NASA AI assistant.
|
| 78 |
-
Answer concisely and clearly based on the conversation history and the user's latest message.
|
| 79 |
-
|
| 80 |
-
Conversation History:
|
| 81 |
-
{chat_history}
|
| 82 |
-
|
| 83 |
-
User: {user_text}
|
| 84 |
-
Assistant:
|
| 85 |
-
"""
|
| 86 |
-
)
|
| 87 |
-
|
| 88 |
-
hf = get_llm_hf_inference(max_new_tokens=max_new_tokens, temperature=0.3)
|
| 89 |
-
chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
|
| 90 |
|
| 91 |
-
response = chat.invoke(input=dict(system_message=system_message, user_text=user_text, chat_history=filtered_history))
|
| 92 |
-
response = response.strip()
|
| 93 |
-
response = ensure_english(response)
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
st.title("🚀 HAL - NASA AI Assistant")
|
| 104 |
-
|
| 105 |
-
st.markdown("""
|
| 106 |
<style>
|
| 107 |
.user-msg, .assistant-msg {
|
| 108 |
padding: 11px;
|
| 109 |
border-radius: 10px;
|
| 110 |
-
margin-bottom:
|
| 111 |
width: fit-content;
|
| 112 |
-
max-width:
|
| 113 |
-
text-align:
|
|
|
|
|
|
|
| 114 |
}
|
| 115 |
-
.user-msg { background-color: #
|
| 116 |
-
.assistant-msg { background-color: #
|
| 117 |
-
.container { display: flex; flex-direction: column;
|
| 118 |
-
|
| 119 |
</style>
|
| 120 |
-
""",
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
)
|
| 130 |
-
|
| 131 |
-
st.markdown("<div class='container'>", unsafe_allow_html=True)
|
| 132 |
-
for message in st.session_state.chat_history:
|
| 133 |
-
if message["role"] == "user":
|
| 134 |
-
st.markdown(f"<div class='user-msg'><strong>You:</strong> {message['content']}</div>", unsafe_allow_html=True)
|
| 135 |
-
else:
|
| 136 |
-
st.markdown(f"<div class='assistant-msg'><strong>HAL:</strong> {message['content']}</div>", unsafe_allow_html=True)
|
| 137 |
-
st.markdown("</div>", unsafe_allow_html=True)
|
|
|
|
| 1 |
+
# file: hal_bot.py
|
| 2 |
+
"""
|
| 3 |
+
🚀 HAL — NASA Chatbot (Streamlit)
|
| 4 |
+
Revised to be:
|
| 5 |
+
- Functional (no broken LangChain piping / output parsers)
|
| 6 |
+
- In-depth (tool-augmented: HAL fetches NASA data when relevant)
|
| 7 |
+
- Prompt-engineered (clear system + style + grounding + citations to NASA API payloads)
|
| 8 |
+
- Robust on CPU-only Streamlit hosting (loads model once, uses caching, handles timeouts)
|
| 9 |
+
|
| 10 |
+
✅ Setup (environment variables):
|
| 11 |
+
- NASA_API_KEY : required (get one at https://api.nasa.gov)
|
| 12 |
+
Optional:
|
| 13 |
+
- HF_TOKEN : not required in this version (we use local Flan-T5). Kept for compatibility.
|
| 14 |
+
|
| 15 |
+
Recommended requirements.txt (example):
|
| 16 |
+
streamlit
|
| 17 |
+
requests
|
| 18 |
+
transformers
|
| 19 |
+
torch
|
| 20 |
+
langdetect
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
|
| 25 |
import os
|
| 26 |
import re
|
| 27 |
+
import json
|
| 28 |
+
import time
|
| 29 |
+
import datetime as dt
|
| 30 |
+
from dataclasses import dataclass
|
| 31 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 32 |
+
|
| 33 |
import requests
|
|
|
|
| 34 |
import streamlit as st
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
from langdetect import detect
|
| 36 |
+
import torch
|
| 37 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
| 38 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
# ----------------------------
|
| 41 |
+
# Config
|
| 42 |
+
# ----------------------------
|
| 43 |
NASA_API_KEY = os.getenv("NASA_API_KEY")
|
| 44 |
+
if not NASA_API_KEY:
|
| 45 |
+
raise ValueError("NASA_API_KEY is not set. Add it as an environment variable.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
| 47 |
+
# Optional (not required in this version)
|
| 48 |
+
HF_TOKEN = os.getenv("HF_TOKEN", "")
|
| 49 |
|
| 50 |
+
MODEL_ID = os.getenv("HAL_MODEL_ID", "google/flan-t5-large")
|
| 51 |
+
MAX_NEW_TOKENS_DEFAULT = int(os.getenv("HAL_MAX_NEW_TOKENS", "420"))
|
| 52 |
+
TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.3"))
|
| 53 |
|
| 54 |
+
REQUEST_TIMEOUT_S = 20
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
+
# ----------------------------
|
| 58 |
+
# Streamlit Setup
|
| 59 |
+
# ----------------------------
|
| 60 |
+
st.set_page_config(page_title="HAL - NASA ChatBot", page_icon="🚀", layout="centered")
|
| 61 |
|
| 62 |
+
st.title("🚀 HAL — NASA AI Assistant")
|
| 63 |
+
st.caption("Tool-augmented NASA chatbot (APOD • Mars Rovers • NEOs • Earth Imagery • NASA Image Search)")
|
| 64 |
|
| 65 |
+
st.markdown(
|
| 66 |
+
"""
|
|
|
|
|
|
|
|
|
|
| 67 |
<style>
|
| 68 |
.user-msg, .assistant-msg {
|
| 69 |
padding: 11px;
|
| 70 |
border-radius: 10px;
|
| 71 |
+
margin-bottom: 8px;
|
| 72 |
width: fit-content;
|
| 73 |
+
max-width: 88%;
|
| 74 |
+
text-align: left;
|
| 75 |
+
line-height: 1.35;
|
| 76 |
+
white-space: pre-wrap;
|
| 77 |
}
|
| 78 |
+
.user-msg { background-color: #5A5A5A; color: white; align-self: flex-end; }
|
| 79 |
+
.assistant-msg { background-color: #2E2E2E; color: white; align-self: flex-start; }
|
| 80 |
+
.container { display: flex; flex-direction: column; gap: 8px; }
|
| 81 |
+
code { font-size: 0.9rem; }
|
| 82 |
</style>
|
| 83 |
+
""",
|
| 84 |
+
unsafe_allow_html=True,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
with st.sidebar:
|
| 88 |
+
st.header("⚙️ Controls")
|
| 89 |
+
max_new_tokens = st.slider("Max new tokens", 64, 900, MAX_NEW_TOKENS_DEFAULT, 16)
|
| 90 |
+
temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)
|
| 91 |
+
tool_mode = st.toggle("Use NASA tools when relevant", value=True)
|
| 92 |
+
verbose_tools = st.toggle("Show tool payload snippets", value=False)
|
| 93 |
+
st.divider()
|
| 94 |
+
st.subheader("NASA API Key")
|
| 95 |
+
st.write("Detected ✅" if bool(NASA_API_KEY) else "Missing ❌")
|
| 96 |
+
st.divider()
|
| 97 |
+
if st.button("🧹 Clear chat"):
|
| 98 |
+
st.session_state.chat_history = [{"role": "assistant", "content": "Hello! Ask me anything about NASA missions, astronomy, Mars rovers, near-Earth objects, or today's APOD."}]
|
| 99 |
+
st.rerun()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# ----------------------------
|
| 103 |
+
# Model Loading (cached)
|
| 104 |
+
# ----------------------------
|
| 105 |
+
@st.cache_resource(show_spinner=True)
|
| 106 |
+
def load_local_llm(model_id: str):
|
| 107 |
+
device = 0 if torch.cuda.is_available() else -1
|
| 108 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 109 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
|
| 110 |
+
gen = pipeline(
|
| 111 |
+
"text2text-generation",
|
| 112 |
+
model=model,
|
| 113 |
+
tokenizer=tokenizer,
|
| 114 |
+
device=device,
|
| 115 |
)
|
| 116 |
+
return gen, ("cuda" if device == 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|