File size: 3,490 Bytes
54fb4ed
97b8dae
 
 
3f3f190
97b8dae
3f3f190
 
97b8dae
 
3f3f190
94f9b7b
 
97b8dae
3f3f190
 
 
 
 
 
 
 
 
97b8dae
 
 
3f3f190
97b8dae
 
3f3f190
97b8dae
 
 
 
3f3f190
97b8dae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f3f190
97b8dae
 
 
 
3f3f190
97b8dae
3f3f190
97b8dae
 
3f3f190
 
97b8dae
 
 
3f3f190
 
97b8dae
 
 
 
 
 
 
 
 
 
 
 
 
1
2
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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}")