Spaces:
Runtime error
Runtime error
Update app.py
Browse files12345678910111213149 unmodified lines2425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989 unmodified lines10810911011111211311411511621 unmodified lines1381391401411421431442 unmodified lines1471481491501511521532 unmodified lines15615715815916016114 unmodified lines17617717817918018118210 unmodified lines1931941951961971981992002012022032042052062072082092102112122132142152162172182192202213 unmodified lines225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287# file: app.py"""HAL — NASA Chatbot (Streamlit)Changes in this version:- Uses a stronger local instruction model: Qwen2.5 Instruct (causal LM)- Uses text-generation pipeline instead of text2text-generation- Uses an explicit chat-style prompt to reduce echoing and improve answer depth- Keeps NASA tool augmentation hooks (minimal examples included; extend as needed)"""from __future__ import annotationsimport os9 unmodified lines# ----------------------------# Environment / Config# ----------------------------NASA_API_KEY = os.getenv("NASA_API_KEY")if not NASA_API_KEY:raise ValueError("NASA_API_KEY is not set.")# Stronger local instruction model (CPU-friendly).# If CPU is too slow/heavy, try: Qwen/Qwen2.5-0.5B-InstructMODEL_ID = os.getenv("HAL_MODEL_ID", "Qwen/Qwen2.5-1.5B-Instruct")MAX_NEW_TOKENS_DEFAULT = int(os.getenv("HAL_MAX_NEW_TOKENS", "420"))TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.3"))TOP_P_DEFAULT = float(os.getenv("HAL_TOP_P", "0.9"))REQUEST_TIMEOUT_S = 20# ----------------------------# Agent Instructions# ----------------------------AGENT_INSTRUCTIONS = """You are HAL, a NASA-focused research assistant.MISSION- Provide accurate, in-depth answers about NASA science, missions, spacecraft, astronomy, planetary science, and spaceflight.- Ground claims in NASA tool data when available.TRUTHFULNESS- Do not invent facts, dates, or mission details.- If uncertain, state what is unknown and how it could be verified.- Prefer TOOL_DATA over general knowledge when relevant.EXPLANATION STYLE- Define key terms.- Explain mechanisms clearly.- Use examples only when they improve understanding.- Address multi-part questions explicitly.EVIDENCE REFERENCES- When using TOOL_DATA, reference fields explicitly:(tool=apod.date), (tool=mars_photos.sample[0].camera.full_name)OUTPUT FORMATReturn your response in exactly this structure:## Direct Answer(1–4 paragraphs)## Key Details and Evidence- Bullet points with tool field references when available## If You Want to Go Deeper- 3–6 follow-up questions or next steps""".strip()# ----------------------------# Streamlit Setup# ----------------------------st.set_page_config(page_title="HAL — NASA AI Assistant", layout="centered")st.title("HAL — NASA AI Assistant")st.caption("Tool-augmented NASA chatbot (local instruction model)")with st.sidebar:st.header("Controls")max_new_tokens = st.slider("Max new tokens", 64, 900, MAX_NEW_TOKENS_DEFAULT, 16)temperature = st.slider("Temperature", 0.0, 1.2, TEMPERATURE_DEFAULT, 0.05)top_p = st.slider("Top-p", 0.1, 1.0, TOP_P_DEFAULT, 0.05)tool_mode = st.toggle("Use NASA tools when relevant", value=True)verbose_tools = st.toggle("Show tool payload snippets", value=False)9 unmodified linesst.rerun()# ----------------------------# Chat History# ----------------------------if "chat_history" not in st.session_state:st.session_state.chat_history = [{"role": "assistant", "content": "Hello. Ask me anything about NASA missions, astronomy, Mars rovers, near-Earth objects, or APOD."}21 unmodified linesreturn Nonedef pretty_json_snip(obj: Any, limit: int = 900) -> str:try:s = json.dumps(obj, indent=2, ensure_ascii=False)return s[:limit] + ("..." if len(s) > limit else "")2 unmodified lines# ----------------------------# NASA Tools (minimal; extend as needed)# ----------------------------NASA_BASE = "https://api.nasa.gov"2 unmodified linesif date:params["date"] = datedata, err = safe_get(f"{NASA_BASE}/planetary/apod", params=params)return {"tool": "apod", "ok": bool(data), "data": data, "error": err}14 unmodified lines# ----------------------------@st.cache_resource(show_spinner=True)def load_llm(model_id: str):# For CPU Spaces, float32 is safest. If you have GPU, you can use float16.use_cuda = torch.cuda.is_available()torch_dtype = torch.float16 if use_cuda else torch.float32device_map = "auto" if use_cuda else None10 unmodified linesmodel=model,tokenizer=tokenizer,)return gen, tokenizergen_pipe, gen_tokenizer = load_llm(MODEL_ID)# ----------------------------# Prompt builder for instruct causal LMs# ----------------------------def build_prompt(user_text: str, history: List[Dict[str, str]], tools: List[Dict[str, Any]]) -> str:# Keep history short for speedrecent = history[-6:]history_block = "\n".join(f"{m['role'].upper()}: {m['content']}" for m in recent)tools_block = json.dumps(tools, indent=2, ensure_ascii=False) if tools else "None"# A simple, robust instruction/chat style prompt.# The explicit "Do not repeat the user's question" reduces echoing.prompt = f"""SYSTEM:{AGENT_INSTRUCTIONS}CONVERSATION CONTEXT:{history_block}TOOL_DATA:3 unmodified lines{user_text}ASSISTANT:Do not repeat the user's question. Follow the required output format. Write the answer now.""".strip()return promptdef extract_assistant_text(full_text: str, prompt: str) -> str:# The pipeline returns prompt + completion. Remove the prompt prefix when present.if full_text.startswith(prompt):return full_text[len(prompt):].lstrip()return full_text.strip()# ----------------------------# Generation# ----------------------------def generate(prompt: str, max_new_tokens: int, temperature: float, top_p: float) -> str:# For explainers, deterministic decoding is often best. We do:# - If temperature is 0: greedy (do_sample False)# - Else: nucleus samplingdo_sample = bool(temperature and temperature > 0.0)out = gen_pipe(prompt,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.08,return_full_text=True,)if not out or not isinstance(out, list):return "Model returned no output."text = out[0].get("generated_text", "")answer = extract_assistant_text(text, prompt)# Basic cleanup: if the model drifts into additional role tags, trim.for stop in ["\nSYSTEM:", "\nUSER:", "\nASSISTANT:", "\nCONVERSATION CONTEXT:"]:if stop in answer:answer = answer.split(stop, 1)[0].rstrip()return answer.strip()def get_response(user_text: str) -> str:tools = plan_tools(user_text) if tool_mode else []prompt = build_prompt(user_text, st.session_state.chat_history, tools)answer = generate(prompt, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p)if verbose_tools and tools:debug = "\n\n---\nTool payload snippets\n"for t in tools:debug += f"\n{t.get('tool')} ok={t.get('ok')} error={t.get('error')}\n"debug += pretty_json_snip(t.get("data"), limit=700) + "\n"answer += debugreturn answer12349 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758599 unmodified lines69707172737421 unmodified lines969798991001011022 unmodified lines1051061071081091101112 unmodified lines11411511611711811912012112214 unmodified lines13713813914014114210 unmodified lines1531541551561571581591601611621631641651661671681691701711721731741751763 unmodified lines180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230# file: app.pyfrom __future__ import annotationsimport os9 unmodified lines# ----------------------------# Config# ----------------------------NASA_API_KEY = os.getenv("NASA_API_KEY")if not NASA_API_KEY:raise ValueError("NASA_API_KEY is not set.")# Fast CPU local instruction modelMODEL_ID = os.getenv("HAL_MODEL_ID", "Qwen/Qwen2.5-0.5B-Instruct")REQUEST_TIMEOUT_S = 20MAX_NEW_TOKENS_DEFAULT = int(os.getenv("HAL_MAX_NEW_TOKENS", "192")) # lower = faster# For speed + stability we use greedy decoding, so temperature is UI-only (kept for later)TEMPERATURE_DEFAULT = float(os.getenv("HAL_TEMPERATURE", "0.0"))AGENT_INSTRUCTIONS = """You are HAL, a NASA-focused research assistant.Rules:- Do not invent facts. If uncertain, say what is unknown and how to verify it.- When TOOL_DATA is present and relevant, use it and reference the exact fields.Output format:## Direct Answer## Key Details and Evidence## If You Want to Go Deeper""".strip()# ----------------------------# Streamlit# ----------------------------st.set_page_config(page_title="HAL — NASA AI Assistant", layout="centered")st.title("HAL — NASA AI Assistant")st.caption("Local instruction model with NASA tools")with st.sidebar:st.header("Controls")max_new_tokens = st.slider("Max new tokens", 64, 512, MAX_NEW_TOKENS_DEFAULT, 16)tool_mode = st.toggle("Use NASA tools when relevant", value=True)verbose_tools = st.toggle("Show tool payload snippets", value=False)9 unmodified linesst.rerun()if "chat_history" not in st.session_state:st.session_state.chat_history = [{"role": "assistant", "content": "Hello. Ask me anything about NASA missions, astronomy, Mars rovers, near-Earth objects, or APOD."}21 unmodified linesreturn Nonedef pretty_json_snip(obj: Any, limit: int = 700) -> str:try:s = json.dumps(obj, indent=2, ensure_ascii=False)return s[:limit] + ("..." if len(s) > limit else "")2 unmodified lines# ----------------------------# NASA tools (minimal)# ----------------------------NASA_BASE = "https://api.nasa.gov"2 unmodified linesif date:params["date"] = datedata, err = safe_get(f"{NASA_BASE}/planetary/apod", params=params)# keep the payload smallif 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}14 unmodified lines# ----------------------------@st.cache_resource(show_spinner=True)def load_llm(model_id: str):use_cuda = torch.cuda.is_available()torch_dtype = torch.float16 if use_cuda else torch.float32device_map = "auto" if use_cuda else None10 unmodified linesmodel=model,tokenizer=tokenizer,)return gengen_pipe = load_llm(MODEL_ID)# ----------------------------# Prompt# ----------------------------def build_prompt(user_text: str, history: List[Dict[str, str]], tools: List[Dict[str, Any]]) -> str:recent = history[-4:] # shorter context = fasterhistory_block = "\n".join(f"{m['role'].upper()}: {m['content']}" for m in recent)tools_block = json.dumps(tools, indent=2, ensure_ascii=False) if tools else "None"return f"""SYSTEM:{AGENT_INSTRUCTIONS}CONTEXT:{history_block}TOOL_DATA:3 unmodified lines{user_text}ASSISTANT:Do not repeat the user's question. Answer directly and follow the required output format.""".strip()def strip_prompt(full_text: str, prompt: str) -> str:if full_text.startswith(prompt):return full_text[len(prompt):].lstrip()return full_text.strip()# ----------------------------# Generation (fast)# ----------------------------def generate(prompt: str, max_new_tokens: int) -> str:# Greedy decoding is the fastest and most stable on CPUout = gen_pipe(prompt,max_new_tokens=int(max_new_tokens),do_sample=False,return_full_text=True,repetition_penalty=1.08,)if not out or not isinstance(out, list):return "Model returned no output."text = out[0].get("generated_text", "")ans = strip_prompt(text, prompt)# Trim if it starts producing extra role blocksfor stop in ["\nSYSTEM:", "\nUSER:", "\nASSISTANT:", "\nCONTEXT:", "\nTOOL_DATA:"]:if stop in ans:ans = ans.split(stop, 1)[0].rstrip()return ans.strip()def get_response(user_text: str) -> str:tools = plan_tools(user_text) if tool_mode else []prompt = build_prompt(user_text, st.session_state.chat_history, tools)answer = generate(prompt, max_new_tokens=max_new_tokens)if verbose_tools and tools:answer += "\n\n---\nTool payload snippets\n"for t in tools:answer += f"\n{t.get('tool')} ok={t.get('ok')} error={t.get('error')}\n"answer += pretty_json_snip(t.get("data"), limit=600) + "\n"return answer
app.py+42-99