jsantangelo commited on
Commit
3941904
·
verified ·
1 Parent(s): bb97634

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -17
app.py CHANGED
@@ -2,53 +2,98 @@ import os
2
  import streamlit as st
3
  import requests
4
  import json
 
5
 
6
- API_BASE = "https://api.cloud.llamaindex.ai/api/v1/pipelines"
7
  LLAMA_KEY = os.environ.get("LLAMA_CLOUD_API_KEY", "")
8
  PIPELINE_ID = os.environ.get("PIPELINE_ID", "")
 
9
 
10
  st.set_page_config(page_title="LlamaIndex Chat", page_icon="💬")
11
  st.title("💬 Chat with Your Documents")
12
 
 
13
  if not LLAMA_KEY or not PIPELINE_ID:
14
- st.error("Missing API key or pipeline ID. Set in Space Secrets.")
15
  st.stop()
16
 
 
17
  if "messages" not in st.session_state:
18
  st.session_state.messages = []
19
 
20
- # Show past messages
21
- for m in st.session_state.messages:
22
- with st.chat_message(m["role"]):
23
- st.markdown(m["content"])
24
 
25
- q = st.chat_input("Ask a question about your documents…")
 
 
 
 
 
 
 
 
 
 
26
 
27
- if q:
28
- st.session_state.messages.append({"role": "user", "content": q})
 
 
 
29
  with st.chat_message("user"):
30
- st.markdown(q)
31
 
32
  with st.chat_message("assistant"):
33
- with st.spinner("Calling LlamaIndex Cloud..."):
34
  try:
 
35
  r = requests.post(
36
- f"{API_BASE}/{PIPELINE_ID}/chat",
37
  headers={
38
  "Authorization": f"Bearer {LLAMA_KEY}",
39
  "Content-Type": "application/json",
40
- "Accept": "application/json"
41
  },
42
  json={
43
- "messages": [{"role": "user", "content": q}],
44
- "stream": False
45
  },
46
  timeout=60
47
  )
 
48
  r.raise_for_status()
49
- data = r.json()
50
- answer = data.get("message") or data.get("answer") or "No answer."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  st.markdown(answer)
 
 
52
  st.session_state.messages.append({"role": "assistant", "content": answer})
 
53
  except Exception as e:
54
  st.error(f"Chat failed: {e}")
 
2
  import streamlit as st
3
  import requests
4
  import json
5
+ import re
6
 
7
+ # Load secrets
8
  LLAMA_KEY = os.environ.get("LLAMA_CLOUD_API_KEY", "")
9
  PIPELINE_ID = os.environ.get("PIPELINE_ID", "")
10
+ API_URL = f"https://api.cloud.llamaindex.ai/api/v1/pipelines/{PIPELINE_ID}/chat"
11
 
12
  st.set_page_config(page_title="LlamaIndex Chat", page_icon="💬")
13
  st.title("💬 Chat with Your Documents")
14
 
15
+ # Check secrets
16
  if not LLAMA_KEY or not PIPELINE_ID:
17
+ st.error("Missing API key or pipeline ID. Set these in your Space's Secrets tab.")
18
  st.stop()
19
 
20
+ # Set up history
21
  if "messages" not in st.session_state:
22
  st.session_state.messages = []
23
 
24
+ # Show prior messages
25
+ for msg in st.session_state.messages:
26
+ with st.chat_message(msg["role"]):
27
+ st.markdown(msg["content"])
28
 
29
+ # Helper to display sources
30
+ def render_sources(sources: list[dict]):
31
+ if not sources:
32
+ return
33
+ st.markdown("#### 📚 Sources")
34
+ for i, src in enumerate(sources, 1):
35
+ meta = src.get("metadata", {}) or {}
36
+ title = meta.get("file_name") or meta.get("source") or meta.get("file_path") or f"Source {i}"
37
+ content = src.get("text") or src.get("content") or ""
38
+ with st.expander(f"[{i}] {title}"):
39
+ st.write(content.strip()[:1000] + ("..." if len(content.strip()) > 1000 else ""))
40
 
41
+ # Chat input
42
+ question = st.chat_input("Ask a question...")
43
+
44
+ if question:
45
+ st.session_state.messages.append({"role": "user", "content": question})
46
  with st.chat_message("user"):
47
+ st.markdown(question)
48
 
49
  with st.chat_message("assistant"):
50
+ with st.spinner("Thinking..."):
51
  try:
52
+ # Send to LlamaIndex Cloud
53
  r = requests.post(
54
+ API_URL,
55
  headers={
56
  "Authorization": f"Bearer {LLAMA_KEY}",
57
  "Content-Type": "application/json",
58
+ "Accept": "application/json",
59
  },
60
  json={
61
+ "messages": [{"role": "user", "content": question}],
62
+ "stream": False,
63
  },
64
  timeout=60
65
  )
66
+
67
  r.raise_for_status()
68
+ body = r.text.strip()
69
+
70
+ # Handle multi-JSON response
71
+ json_blobs = re.findall(r'\{.*?\}(?=\s*[{[]|\s*$)', body, re.DOTALL)
72
+ frames = [json.loads(blob) for blob in json_blobs if blob.strip().startswith("{")]
73
+
74
+ # Extract answer + sources
75
+ answer = None
76
+ sources = []
77
+ for fr in frames:
78
+ if fr.get("type") in ("final_message", "assistant_message"):
79
+ answer = (
80
+ fr.get("data", {}).get("message", {}).get("content") or
81
+ fr.get("message") or
82
+ fr.get("answer")
83
+ )
84
+ if fr.get("type") == "sources":
85
+ nodes = fr.get("data", {}).get("nodes", [])
86
+ for n in nodes:
87
+ sources.append({
88
+ "text": n.get("text") or n.get("content"),
89
+ "metadata": n.get("metadata") or {}
90
+ })
91
+
92
+ answer = answer or "No answer."
93
  st.markdown(answer)
94
+ render_sources(sources)
95
+
96
  st.session_state.messages.append({"role": "assistant", "content": answer})
97
+
98
  except Exception as e:
99
  st.error(f"Chat failed: {e}")