import os import streamlit as st from llama_index.indices.managed.llama_cloud import LlamaCloudIndex # ---------- Config ---------- LLAMA_KEY = os.environ.get("LLAMA_CLOUD_API_KEY", "") PIPELINE_ID = os.environ.get("PIPELINE_ID", "") TOP_K = int(os.environ.get("TOP_K", "4")) # optional env override st.set_page_config(page_title="LlamaIndex Cloud Chat", page_icon="💬") st.title("Ask Atrium Docs (public index)") st.caption("Ask questions to industry analyst reports.") # Secrets check if not LLAMA_KEY: st.error("Missing LLAMA_CLOUD_API_KEY (add in Space Settings → Secrets).") st.stop() if not PIPELINE_ID: st.error("Missing PIPELINE_ID (add in Space Settings → Secrets).") st.stop() # ---------- Chat engine (cached) ---------- @st.cache_resource(show_spinner=True) def get_chat_engine(index_id: str, api_key: str, k: int): index = LlamaCloudIndex(index_id=index_id, api_key=api_key) return index.as_chat_engine(similarity_top_k=k) try: chat_engine = get_chat_engine(PIPELINE_ID, LLAMA_KEY, TOP_K) except Exception as e: st.error(f"Failed to initialize chat engine. Check Pipeline ID and API key.\n\n{e}") st.stop() # ---------- Chat history ---------- if "messages" not in st.session_state: st.session_state.messages = [] # Render previous turns for m in st.session_state.messages: with st.chat_message(m["role"]): st.markdown(m["content"]) # ---------- Ask ---------- q = st.chat_input("Ask a question about your documents…") if q: st.session_state.messages.append({"role": "user", "content": q}) with st.chat_message("user"): st.markdown(q) with st.chat_message("assistant"): with st.spinner("Thinking…"): try: resp = chat_engine.chat(q) answer = getattr(resp, "response", None) or "No answer." st.markdown(answer) # Sources (NodeWithScore list) source_nodes = getattr(resp, "source_nodes", []) or [] if source_nodes: st.markdown("#### 📚 Sources") for i, sn in enumerate(source_nodes, start=1): # robust access to text and metadata try: text = sn.get_text() if hasattr(sn, "get_text") else getattr(sn, "text", "") or "" meta = getattr(sn, "metadata", {}) or {} except Exception: text, meta = "", {} title = ( meta.get("file_name") or meta.get("filename") or meta.get("file_path") or meta.get("source") or f"Source {i}" ) page = meta.get("page") or meta.get("page_number") or meta.get("page_label") header = f"[{i}] {title}" + (f" • p.{page}" if page else "") with st.expander(header): snippet = (text or "").strip() st.write(snippet[:1200] + ("…" if len(snippet) > 1200 else "")) if meta: st.code(meta, language="json") st.session_state.messages.append({"role": "assistant", "content": answer}) except Exception as e: st.error(f"Chat failed: {e}")