Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,64 +1,43 @@
|
|
| 1 |
import os
|
| 2 |
import streamlit as st
|
| 3 |
-
|
| 4 |
-
# Official LlamaIndex SDK
|
| 5 |
from llama_index.indices.managed.llama_cloud import LlamaCloudIndex
|
| 6 |
|
| 7 |
-
# ---------- Config
|
| 8 |
LLAMA_KEY = os.environ.get("LLAMA_CLOUD_API_KEY", "")
|
| 9 |
-
|
|
|
|
| 10 |
|
| 11 |
st.set_page_config(page_title="LlamaIndex Cloud Chat", page_icon="💬")
|
| 12 |
-
st.title("
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
# ---------- Sidebar ----------
|
| 19 |
-
with st.sidebar:
|
| 20 |
-
st.subheader("Settings")
|
| 21 |
-
pipeline_id = st.text_input(
|
| 22 |
-
"Pipeline (Index) ID",
|
| 23 |
-
value=DEFAULT_PIPELINE_ID,
|
| 24 |
-
help="Copy the UUID from your pipeline URL in cloud.llamaindex.ai",
|
| 25 |
-
)
|
| 26 |
-
top_k = st.slider("Top-K retrieval", 1, 10, 4)
|
| 27 |
-
st.caption(
|
| 28 |
-
f"API key: {'✅' if bool(LLAMA_KEY) else '❌'} · "
|
| 29 |
-
f"Pipeline ID: {'✅' if bool(pipeline_id) else '❌'}"
|
| 30 |
-
)
|
| 31 |
-
if st.button("Clear conversation"):
|
| 32 |
-
st.session_state.pop("chat_engine_keyed", None)
|
| 33 |
st.session_state.pop("messages", None)
|
| 34 |
st.rerun()
|
| 35 |
|
| 36 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
@st.cache_resource(show_spinner=True)
|
| 38 |
def get_chat_engine(index_id: str, api_key: str, k: int):
|
| 39 |
-
"""
|
| 40 |
-
Create a LlamaCloudIndex and return its chat engine.
|
| 41 |
-
Cached by (index_id, api_key, k) for this Streamlit session.
|
| 42 |
-
"""
|
| 43 |
-
# Build the managed index wrapper (no raw HTTP)
|
| 44 |
index = LlamaCloudIndex(index_id=index_id, api_key=api_key)
|
| 45 |
-
|
| 46 |
-
chat_engine = index.as_chat_engine(similarity_top_k=k)
|
| 47 |
-
return chat_engine
|
| 48 |
-
|
| 49 |
-
# Ensure we have a pipeline to talk to
|
| 50 |
-
if not pipeline_id:
|
| 51 |
-
st.info("Enter your Pipeline (Index) ID in the sidebar to begin.")
|
| 52 |
-
st.stop()
|
| 53 |
|
| 54 |
-
# Instantiate chat engine (cached)
|
| 55 |
try:
|
| 56 |
-
chat_engine = get_chat_engine(
|
| 57 |
except Exception as e:
|
| 58 |
st.error(f"Failed to initialize chat engine. Check Pipeline ID and API key.\n\n{e}")
|
| 59 |
st.stop()
|
| 60 |
|
| 61 |
-
# ---------- Chat
|
| 62 |
if "messages" not in st.session_state:
|
| 63 |
st.session_state.messages = []
|
| 64 |
|
|
@@ -69,41 +48,35 @@ for m in st.session_state.messages:
|
|
| 69 |
|
| 70 |
# ---------- Ask ----------
|
| 71 |
q = st.chat_input("Ask a question about your documents…")
|
| 72 |
-
|
| 73 |
if q:
|
| 74 |
-
# Show user turn
|
| 75 |
st.session_state.messages.append({"role": "user", "content": q})
|
| 76 |
with st.chat_message("user"):
|
| 77 |
st.markdown(q)
|
| 78 |
|
| 79 |
-
# Assistant turn
|
| 80 |
with st.chat_message("assistant"):
|
| 81 |
with st.spinner("Thinking…"):
|
| 82 |
try:
|
| 83 |
-
# This handles retrieval + generation server-side using your pipeline’s config
|
| 84 |
resp = chat_engine.chat(q)
|
| 85 |
-
|
| 86 |
-
# Final text
|
| 87 |
answer = getattr(resp, "response", None) or "No answer."
|
| 88 |
st.markdown(answer)
|
| 89 |
|
| 90 |
-
# Sources (
|
| 91 |
source_nodes = getattr(resp, "source_nodes", []) or []
|
| 92 |
if source_nodes:
|
| 93 |
st.markdown("#### 📚 Sources")
|
| 94 |
for i, sn in enumerate(source_nodes, start=1):
|
|
|
|
| 95 |
try:
|
| 96 |
-
text = sn.get_text() if hasattr(sn, "get_text") else (sn
|
| 97 |
meta = getattr(sn, "metadata", {}) or {}
|
| 98 |
except Exception:
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
meta = {}
|
| 102 |
title = (
|
| 103 |
meta.get("file_name")
|
| 104 |
-
or meta.get("source")
|
| 105 |
-
or meta.get("file_path")
|
| 106 |
or meta.get("filename")
|
|
|
|
|
|
|
| 107 |
or f"Source {i}"
|
| 108 |
)
|
| 109 |
page = meta.get("page") or meta.get("page_number") or meta.get("page_label")
|
|
@@ -114,8 +87,6 @@ if q:
|
|
| 114 |
if meta:
|
| 115 |
st.code(meta, language="json")
|
| 116 |
|
| 117 |
-
# Save assistant turn to local chat history (for the UI only)
|
| 118 |
st.session_state.messages.append({"role": "assistant", "content": answer})
|
| 119 |
-
|
| 120 |
except Exception as e:
|
| 121 |
st.error(f"Chat failed: {e}")
|
|
|
|
| 1 |
import os
|
| 2 |
import streamlit as st
|
|
|
|
|
|
|
| 3 |
from llama_index.indices.managed.llama_cloud import LlamaCloudIndex
|
| 4 |
|
| 5 |
+
# ---------- Config ----------
|
| 6 |
LLAMA_KEY = os.environ.get("LLAMA_CLOUD_API_KEY", "")
|
| 7 |
+
PIPELINE_ID = os.environ.get("PIPELINE_ID", "")
|
| 8 |
+
TOP_K = int(os.environ.get("TOP_K", "4")) # optional env override
|
| 9 |
|
| 10 |
st.set_page_config(page_title="LlamaIndex Cloud Chat", page_icon="💬")
|
| 11 |
+
st.title("Ask Atrium Docs (public index)")
|
| 12 |
|
| 13 |
+
# Small toolbar (no sidebar)
|
| 14 |
+
col1, col2 = st.columns([1, 1])
|
| 15 |
+
with col2:
|
| 16 |
+
if st.button("Clear conversation", key="clear_chat_btn"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
st.session_state.pop("messages", None)
|
| 18 |
st.rerun()
|
| 19 |
|
| 20 |
+
# Secrets check
|
| 21 |
+
if not LLAMA_KEY:
|
| 22 |
+
st.error("Missing LLAMA_CLOUD_API_KEY (add in Space Settings → Secrets).")
|
| 23 |
+
st.stop()
|
| 24 |
+
if not PIPELINE_ID:
|
| 25 |
+
st.error("Missing PIPELINE_ID (add in Space Settings → Secrets).")
|
| 26 |
+
st.stop()
|
| 27 |
+
|
| 28 |
+
# ---------- Chat engine (cached) ----------
|
| 29 |
@st.cache_resource(show_spinner=True)
|
| 30 |
def get_chat_engine(index_id: str, api_key: str, k: int):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
index = LlamaCloudIndex(index_id=index_id, api_key=api_key)
|
| 32 |
+
return index.as_chat_engine(similarity_top_k=k)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
|
|
|
| 34 |
try:
|
| 35 |
+
chat_engine = get_chat_engine(PIPELINE_ID, LLAMA_KEY, TOP_K)
|
| 36 |
except Exception as e:
|
| 37 |
st.error(f"Failed to initialize chat engine. Check Pipeline ID and API key.\n\n{e}")
|
| 38 |
st.stop()
|
| 39 |
|
| 40 |
+
# ---------- Chat history ----------
|
| 41 |
if "messages" not in st.session_state:
|
| 42 |
st.session_state.messages = []
|
| 43 |
|
|
|
|
| 48 |
|
| 49 |
# ---------- Ask ----------
|
| 50 |
q = st.chat_input("Ask a question about your documents…")
|
|
|
|
| 51 |
if q:
|
|
|
|
| 52 |
st.session_state.messages.append({"role": "user", "content": q})
|
| 53 |
with st.chat_message("user"):
|
| 54 |
st.markdown(q)
|
| 55 |
|
|
|
|
| 56 |
with st.chat_message("assistant"):
|
| 57 |
with st.spinner("Thinking…"):
|
| 58 |
try:
|
|
|
|
| 59 |
resp = chat_engine.chat(q)
|
|
|
|
|
|
|
| 60 |
answer = getattr(resp, "response", None) or "No answer."
|
| 61 |
st.markdown(answer)
|
| 62 |
|
| 63 |
+
# Sources (NodeWithScore list)
|
| 64 |
source_nodes = getattr(resp, "source_nodes", []) or []
|
| 65 |
if source_nodes:
|
| 66 |
st.markdown("#### 📚 Sources")
|
| 67 |
for i, sn in enumerate(source_nodes, start=1):
|
| 68 |
+
# robust access to text and metadata
|
| 69 |
try:
|
| 70 |
+
text = sn.get_text() if hasattr(sn, "get_text") else getattr(sn, "text", "") or ""
|
| 71 |
meta = getattr(sn, "metadata", {}) or {}
|
| 72 |
except Exception:
|
| 73 |
+
text, meta = "", {}
|
| 74 |
+
|
|
|
|
| 75 |
title = (
|
| 76 |
meta.get("file_name")
|
|
|
|
|
|
|
| 77 |
or meta.get("filename")
|
| 78 |
+
or meta.get("file_path")
|
| 79 |
+
or meta.get("source")
|
| 80 |
or f"Source {i}"
|
| 81 |
)
|
| 82 |
page = meta.get("page") or meta.get("page_number") or meta.get("page_label")
|
|
|
|
| 87 |
if meta:
|
| 88 |
st.code(meta, language="json")
|
| 89 |
|
|
|
|
| 90 |
st.session_state.messages.append({"role": "assistant", "content": answer})
|
|
|
|
| 91 |
except Exception as e:
|
| 92 |
st.error(f"Chat failed: {e}")
|