Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,9 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import requests
|
| 3 |
import streamlit as st
|
| 4 |
|
|
|
|
| 5 |
API_BASE = "https://api.cloud.llamaindex.ai/api/v1/pipelines"
|
| 6 |
LLAMA_KEY = os.environ.get("LLAMA_CLOUD_API_KEY", "")
|
| 7 |
DEFAULT_PIPELINE = os.environ.get("PIPELINE_ID", "")
|
|
@@ -9,83 +11,127 @@ DEFAULT_PIPELINE = os.environ.get("PIPELINE_ID", "")
|
|
| 9 |
st.set_page_config(page_title="LlamaIndex Cloud Chat", page_icon="💬")
|
| 10 |
st.title("💬 Chat with Your LlamaIndex Cloud Dataset")
|
| 11 |
|
|
|
|
| 12 |
with st.sidebar:
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
try:
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
json={"messages": [{"role":"user","content":"ping"}]},
|
| 23 |
-
timeout=30,
|
| 24 |
)
|
| 25 |
-
st.success(f"OK {
|
| 26 |
except Exception as e:
|
| 27 |
-
st.error(
|
| 28 |
-
|
| 29 |
-
with st.sidebar:
|
| 30 |
-
st.markdown("### Settings")
|
| 31 |
-
pipeline_id = st.text_input("Pipeline ID", value=DEFAULT_PIPELINE, help="Find this in cloud.llamaindex.ai")
|
| 32 |
-
st.caption("Keep your API key in Space Secrets (Settings → Secrets).")
|
| 33 |
-
|
| 34 |
-
# Maintain chat history
|
| 35 |
-
if "messages" not in st.session_state:
|
| 36 |
-
st.session_state.messages = []
|
| 37 |
|
| 38 |
-
#
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
| 42 |
|
|
|
|
| 43 |
def llama_chat(pipeline: str, messages: list[dict]):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
if not LLAMA_KEY:
|
| 45 |
-
raise RuntimeError("Missing LLAMA_CLOUD_API_KEY (set it in Space Secrets).")
|
| 46 |
if not pipeline:
|
| 47 |
-
raise RuntimeError("Missing Pipeline ID.")
|
|
|
|
| 48 |
r = requests.post(
|
| 49 |
f"{API_BASE}/{pipeline}/chat",
|
| 50 |
-
headers={
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
timeout=90,
|
| 53 |
)
|
| 54 |
-
r.raise_for_status()
|
| 55 |
-
return r.json()
|
| 56 |
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
q = st.chat_input("Ask a question about your documents…")
|
| 59 |
if q:
|
|
|
|
| 60 |
st.session_state.messages.append({"role": "user", "content": q})
|
| 61 |
with st.chat_message("user"):
|
| 62 |
st.markdown(q)
|
| 63 |
|
|
|
|
| 64 |
with st.chat_message("assistant"):
|
| 65 |
with st.spinner("Thinking…"):
|
| 66 |
try:
|
| 67 |
-
data = llama_chat(pipeline_id, st.session_state.messages)
|
|
|
|
| 68 |
answer = data.get("message") or data.get("answer") or "No answer."
|
| 69 |
st.markdown(answer)
|
| 70 |
|
| 71 |
-
# Show sources if provided
|
| 72 |
sources = data.get("sources") or data.get("source_nodes") or []
|
| 73 |
-
|
| 74 |
-
st.caption("Sources")
|
| 75 |
-
for i, s in enumerate(sources, start=1):
|
| 76 |
-
meta = s.get("metadata", {}) or {}
|
| 77 |
-
fname = meta.get("file_name") or meta.get("source") or "Document"
|
| 78 |
-
page = meta.get("page") or meta.get("page_number")
|
| 79 |
-
label = f"[S{i}] {fname}" + (f" • p.{page}" if page else "")
|
| 80 |
-
with st.expander(label):
|
| 81 |
-
st.write((s.get("text") or s.get("content") or "")[:2000])
|
| 82 |
|
|
|
|
| 83 |
st.session_state.messages.append({"role": "assistant", "content": answer})
|
| 84 |
except Exception as e:
|
| 85 |
st.error(f"Chat failed: {e}")
|
| 86 |
-
|
| 87 |
-
# Optional: sidebar reset
|
| 88 |
-
with st.sidebar:
|
| 89 |
-
if st.button("Clear chat"):
|
| 90 |
-
st.session_state.messages = []
|
| 91 |
-
st.rerun()
|
|
|
|
| 1 |
import os
|
| 2 |
+
import json
|
| 3 |
import requests
|
| 4 |
import streamlit as st
|
| 5 |
|
| 6 |
+
# ------------ Config ------------
|
| 7 |
API_BASE = "https://api.cloud.llamaindex.ai/api/v1/pipelines"
|
| 8 |
LLAMA_KEY = os.environ.get("LLAMA_CLOUD_API_KEY", "")
|
| 9 |
DEFAULT_PIPELINE = os.environ.get("PIPELINE_ID", "")
|
|
|
|
| 11 |
st.set_page_config(page_title="LlamaIndex Cloud Chat", page_icon="💬")
|
| 12 |
st.title("💬 Chat with Your LlamaIndex Cloud Dataset")
|
| 13 |
|
| 14 |
+
# ------------ Sidebar ------------
|
| 15 |
with st.sidebar:
|
| 16 |
+
st.subheader("Settings")
|
| 17 |
+
pipeline_id = st.text_input(
|
| 18 |
+
"Pipeline ID",
|
| 19 |
+
value=DEFAULT_PIPELINE,
|
| 20 |
+
help="Copy the UUID from cloud.llamaindex.ai → your pipeline URL",
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
st.caption(
|
| 24 |
+
f"Key present: {'✅' if bool(LLAMA_KEY) else '❌'} • "
|
| 25 |
+
f"Default Pipeline ID: {'✅' if bool(DEFAULT_PIPELINE) else '❌'}"
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
def health_check():
|
| 29 |
+
if not pipeline_id:
|
| 30 |
+
st.error("Set a Pipeline ID first.")
|
| 31 |
+
return
|
| 32 |
try:
|
| 33 |
+
data = llama_chat(
|
| 34 |
+
pipeline=pipeline_id,
|
| 35 |
+
messages=[{"role": "user", "content": "ping"}],
|
|
|
|
|
|
|
| 36 |
)
|
| 37 |
+
st.success(f"Chat OK (got keys: {', '.join(list(data.keys())[:5])})")
|
| 38 |
except Exception as e:
|
| 39 |
+
st.error(str(e))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
+
# Placeholders; actual function defined below
|
| 42 |
+
st.button("Health check", on_click=lambda: None)
|
| 43 |
+
st.markdown("---")
|
| 44 |
+
if st.button("Clear chat"):
|
| 45 |
+
st.session_state.messages = []
|
| 46 |
+
st.rerun()
|
| 47 |
|
| 48 |
+
# ------------ Helpers ------------
|
| 49 |
def llama_chat(pipeline: str, messages: list[dict]):
|
| 50 |
+
"""
|
| 51 |
+
Calls the LlamaIndex Cloud managed /chat endpoint and forces a non-streaming JSON response.
|
| 52 |
+
Raises a RuntimeError with a helpful preview if the response isn't JSON or is an HTTP error.
|
| 53 |
+
"""
|
| 54 |
if not LLAMA_KEY:
|
| 55 |
+
raise RuntimeError("Missing LLAMA_CLOUD_API_KEY (set it in Space Settings → Secrets).")
|
| 56 |
if not pipeline:
|
| 57 |
+
raise RuntimeError("Missing Pipeline ID (enter it in the sidebar).")
|
| 58 |
+
|
| 59 |
r = requests.post(
|
| 60 |
f"{API_BASE}/{pipeline}/chat",
|
| 61 |
+
headers={
|
| 62 |
+
"Authorization": f"Bearer {LLAMA_KEY}",
|
| 63 |
+
"Content-Type": "application/json",
|
| 64 |
+
"Accept": "application/json", # ask for JSON (not SSE/NDJSON)
|
| 65 |
+
},
|
| 66 |
+
json={
|
| 67 |
+
"messages": messages, # [{role:"user"/"assistant", content:"..."}]
|
| 68 |
+
"stream": False, # force non-streaming response
|
| 69 |
+
},
|
| 70 |
timeout=90,
|
| 71 |
)
|
|
|
|
|
|
|
| 72 |
|
| 73 |
+
ct = r.headers.get("Content-Type", "")
|
| 74 |
+
preview = (r.text or "")[:400]
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
r.raise_for_status()
|
| 78 |
+
except requests.HTTPError as e:
|
| 79 |
+
raise RuntimeError(f"LlamaCloud HTTP {r.status_code} ({ct}): {preview}") from e
|
| 80 |
+
|
| 81 |
+
try:
|
| 82 |
+
return r.json()
|
| 83 |
+
except json.JSONDecodeError:
|
| 84 |
+
raise RuntimeError(f"Non-JSON response ({ct}): {preview}")
|
| 85 |
+
|
| 86 |
+
def render_sources(sources):
|
| 87 |
+
if not sources:
|
| 88 |
+
return
|
| 89 |
+
st.caption("Sources")
|
| 90 |
+
for i, s in enumerate(sources, start=1):
|
| 91 |
+
meta = s.get("metadata", {}) or {}
|
| 92 |
+
fname = meta.get("file_name") or meta.get("source") or "Document"
|
| 93 |
+
page = meta.get("page") or meta.get("page_number") or meta.get("page_label")
|
| 94 |
+
label = f"[S{i}] {fname}" + (f" • p.{page}" if page else "")
|
| 95 |
+
text = s.get("text") or s.get("content") or ""
|
| 96 |
+
with st.expander(label):
|
| 97 |
+
st.write(text[:2000] + ("…" if len(text) > 2000 else ""))
|
| 98 |
+
if meta:
|
| 99 |
+
st.code(meta, language="json")
|
| 100 |
+
|
| 101 |
+
# Re-bind the sidebar health check with the now-defined function
|
| 102 |
+
with st.sidebar:
|
| 103 |
+
st.button("Health check", on_click=lambda: health_check())
|
| 104 |
+
|
| 105 |
+
# ------------ Chat State ------------
|
| 106 |
+
if "messages" not in st.session_state:
|
| 107 |
+
st.session_state.messages = []
|
| 108 |
+
|
| 109 |
+
# Render previous turns
|
| 110 |
+
for m in st.session_state.messages:
|
| 111 |
+
with st.chat_message(m["role"]):
|
| 112 |
+
st.markdown(m["content"])
|
| 113 |
+
|
| 114 |
+
# ------------ Input + Call ------------
|
| 115 |
q = st.chat_input("Ask a question about your documents…")
|
| 116 |
if q:
|
| 117 |
+
# Add user turn
|
| 118 |
st.session_state.messages.append({"role": "user", "content": q})
|
| 119 |
with st.chat_message("user"):
|
| 120 |
st.markdown(q)
|
| 121 |
|
| 122 |
+
# Assistant turn
|
| 123 |
with st.chat_message("assistant"):
|
| 124 |
with st.spinner("Thinking…"):
|
| 125 |
try:
|
| 126 |
+
data = llama_chat(pipeline=pipeline_id or DEFAULT_PIPELINE, messages=st.session_state.messages)
|
| 127 |
+
# Common response shapes: { message, sources, ... } or { answer, source_nodes, ... }
|
| 128 |
answer = data.get("message") or data.get("answer") or "No answer."
|
| 129 |
st.markdown(answer)
|
| 130 |
|
|
|
|
| 131 |
sources = data.get("sources") or data.get("source_nodes") or []
|
| 132 |
+
render_sources(sources)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
+
# Save assistant turn to history
|
| 135 |
st.session_state.messages.append({"role": "assistant", "content": answer})
|
| 136 |
except Exception as e:
|
| 137 |
st.error(f"Chat failed: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|