Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,184 +1,121 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
)
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
#
|
| 66 |
-
|
| 67 |
-
with
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
# Event handlers
|
| 123 |
-
def respond(message, chat_history):
|
| 124 |
-
if not message.strip():
|
| 125 |
-
return chat_history, ""
|
| 126 |
-
|
| 127 |
-
# Add user message to history
|
| 128 |
-
chat_history.append([message, None])
|
| 129 |
-
|
| 130 |
-
# Get bot response
|
| 131 |
-
bot_response = chatbot.chat(message, chat_history)
|
| 132 |
-
|
| 133 |
-
# Update history with bot response
|
| 134 |
-
chat_history[-1][1] = bot_response
|
| 135 |
-
|
| 136 |
-
return chat_history, ""
|
| 137 |
-
|
| 138 |
-
def clear_chat():
|
| 139 |
-
return [], ""
|
| 140 |
-
|
| 141 |
-
# Wire up events
|
| 142 |
-
submit_btn.click(
|
| 143 |
-
respond,
|
| 144 |
-
inputs=[msg, chatbot_ui],
|
| 145 |
-
outputs=[chatbot_ui, msg]
|
| 146 |
-
)
|
| 147 |
-
|
| 148 |
-
msg.submit(
|
| 149 |
-
respond,
|
| 150 |
-
inputs=[msg, chatbot_ui],
|
| 151 |
-
outputs=[chatbot_ui, msg]
|
| 152 |
-
)
|
| 153 |
-
|
| 154 |
-
clear_btn.click(clear_chat, outputs=[chatbot_ui, msg])
|
| 155 |
-
|
| 156 |
-
# Status information
|
| 157 |
-
with gr.Accordion("ℹ️ System Information", open=False):
|
| 158 |
-
status_text = "✅ Connected to LlamaCloud pipeline" if chatbot.pipeline else "❌ Failed to connect to pipeline"
|
| 159 |
-
gr.Markdown(f"**Status:** {status_text}")
|
| 160 |
-
|
| 161 |
-
if chatbot.pipeline:
|
| 162 |
-
gr.Markdown("**Configuration:** Using LlamaCloud pipeline directly (no external LLM needed)")
|
| 163 |
-
else:
|
| 164 |
-
gr.Markdown("**Error:** Please check your environment variables and LlamaCloud configuration")
|
| 165 |
-
|
| 166 |
-
return iface
|
| 167 |
-
|
| 168 |
-
# Launch the app
|
| 169 |
-
if __name__ == "__main__":
|
| 170 |
-
# Check required environment variables
|
| 171 |
-
required_vars = ["LLAMA_CLOUD_API_KEY", "LLAMA_CLOUD_PIPELINE_ID"]
|
| 172 |
-
missing_vars = [var for var in required_vars if not os.getenv(var)]
|
| 173 |
-
|
| 174 |
-
if missing_vars:
|
| 175 |
-
print(f"❌ Missing required environment variables: {', '.join(missing_vars)}")
|
| 176 |
-
print("Please set them in your Hugging Face Space secrets or .env file")
|
| 177 |
-
|
| 178 |
-
# Create and launch interface
|
| 179 |
-
demo = create_interface()
|
| 180 |
-
demo.launch(
|
| 181 |
-
server_name="0.0.0.0",
|
| 182 |
-
server_port=7860,
|
| 183 |
-
share=False
|
| 184 |
-
)
|
|
|
|
| 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 & Secrets ----------
|
| 8 |
+
LLAMA_KEY = os.environ.get("LLAMA_CLOUD_API_KEY", "")
|
| 9 |
+
DEFAULT_PIPELINE_ID = os.environ.get("PIPELINE_ID", "")
|
| 10 |
+
|
| 11 |
+
st.set_page_config(page_title="LlamaIndex Cloud Chat", page_icon="💬")
|
| 12 |
+
st.title("💬 Chat with Your Documents (LlamaIndex SDK)")
|
| 13 |
+
|
| 14 |
+
if not LLAMA_KEY:
|
| 15 |
+
st.error("Missing LLAMA_CLOUD_API_KEY (add it in Space Settings → Secrets).")
|
| 16 |
+
st.stop()
|
| 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 |
+
# ---------- Cached loader ----------
|
| 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 |
+
# Let the SDK handle retrieval+generation; you can pass knobs here if desired
|
| 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(pipeline_id, LLAMA_KEY, top_k)
|
| 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 History ----------
|
| 62 |
+
if "messages" not in st.session_state:
|
| 63 |
+
st.session_state.messages = []
|
| 64 |
+
|
| 65 |
+
# Render previous turns
|
| 66 |
+
for m in st.session_state.messages:
|
| 67 |
+
with st.chat_message(m["role"]):
|
| 68 |
+
st.markdown(m["content"])
|
| 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 (resp.source_nodes is a list of NodeWithScore)
|
| 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.text if hasattr(sn, "text") else "")
|
| 97 |
+
meta = getattr(sn, "metadata", {}) or {}
|
| 98 |
+
except Exception:
|
| 99 |
+
# Fallback if object shape differs
|
| 100 |
+
text = ""
|
| 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")
|
| 110 |
+
header = f"[{i}] {title}" + (f" • p.{page}" if page else "")
|
| 111 |
+
with st.expander(header):
|
| 112 |
+
snippet = (text or "").strip()
|
| 113 |
+
st.write(snippet[:1200] + ("…" if len(snippet) > 1200 else ""))
|
| 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}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|