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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -262
app.py CHANGED
@@ -1,288 +1,54 @@
1
  import os
2
- import json
3
- import requests
4
  import streamlit as st
5
- from typing import List, Dict, Any, Union
 
6
 
7
- # ------------ Config ------------
8
  API_BASE = "https://api.cloud.llamaindex.ai/api/v1/pipelines"
9
  LLAMA_KEY = os.environ.get("LLAMA_CLOUD_API_KEY", "")
10
- DEFAULT_PIPELINE = os.environ.get("PIPELINE_ID", "")
11
-
12
- st.set_page_config(page_title="LlamaIndex Cloud Chat", page_icon="💬")
13
- st.title("💬 Chat with Your LlamaIndex Cloud Dataset")
14
-
15
- # ------------ Sidebar ------------
16
- with st.sidebar:
17
- st.subheader("Settings")
18
- pipeline_id = st.text_input("Pipeline ID", value=DEFAULT_PIPELINE)
19
- keep_turns = st.slider("Turns to send (history)", 1, 12, 6)
20
- show_debug = st.toggle("Show debug for next answer", value=False)
21
-
22
- st.caption(
23
- f"Key present: {'✅' if bool(LLAMA_KEY) else '❌'} • "
24
- f"Default Pipeline ID: {'✅' if bool(DEFAULT_PIPELINE) else '❌'}"
25
- )
26
-
27
- if st.button("Health check", key="health_check_btn"):
28
- try:
29
- r = requests.post(
30
- f"{API_BASE}/{(pipeline_id or DEFAULT_PIPELINE)}/chat",
31
- headers={
32
- "Authorization": f"Bearer {LLAMA_KEY}",
33
- "Content-Type": "application/json",
34
- "Accept": "application/json",
35
- },
36
- json={"messages": [{"role": "user", "content": "ping"}], "stream": False},
37
- timeout=60,
38
- )
39
- print("=== RAW BODY START ===")
40
- print(r.text[:2000]) # first 2000 chars
41
- print("=== RAW BODY END ===")
42
- r.raise_for_status()
43
- st.success(f"HTTP {r.status_code} · {r.headers.get('Content-Type','')}")
44
- except Exception as e:
45
- st.error(str(e))
46
-
47
-
48
-
49
-
50
-
51
- st.markdown("---")
52
- if st.button("Clear chat", key="clear_chat_btn"):
53
- st.session_state.messages = []
54
- st.rerun()
55
-
56
- # ------------ Utilities ------------
57
- def deep_get(d: Any, keys: List[str]) -> Union[str, None]:
58
- """Try multiple keys recursively; return first non-empty string."""
59
- if isinstance(d, dict):
60
- for k in keys:
61
- v = d.get(k)
62
- if isinstance(v, str) and v.strip():
63
- return v
64
- if isinstance(v, dict):
65
- got = deep_get(v, keys)
66
- if got:
67
- return got
68
- if isinstance(v, list):
69
- for item in v:
70
- got = deep_get(item, keys)
71
- if got:
72
- return got
73
- elif isinstance(d, list):
74
- for item in d:
75
- got = deep_get(item, keys)
76
- if got:
77
- return got
78
- return None
79
-
80
- def extract_text_from_frame(fr: Dict[str, Any]) -> List[str]:
81
- """Collect assistant text from a single frame across many shapes."""
82
- texts: List[str] = []
83
-
84
- # Direct common fields
85
- for k in ("message", "answer", "content"):
86
- v = fr.get(k)
87
- if isinstance(v, str) and v.strip():
88
- texts.append(v)
89
-
90
- # Typed frames
91
- t = fr.get("type")
92
- data = fr.get("data") or {}
93
 
94
- # Final/assistant message shapes
95
- if t in ("final_message", "assistant_message", "message"):
96
- # Try typical nesting: data.message.content
97
- got = deep_get(data, ["message", "content"])
98
- if got:
99
- texts.append(got)
100
 
101
- # Streaming deltas
102
- if t in ("delta", "assistant_delta", "message_delta"):
103
- got = deep_get(data, ["delta", "assistant_delta", "message_delta", "content"])
104
- if got:
105
- texts.append(got)
106
 
107
- # Generic fallbacks
108
- got = deep_get(data, ["content", "text", "message"])
109
- if got:
110
- texts.append(got)
111
-
112
- return [t for t in texts if isinstance(t, str) and t.strip()]
113
-
114
- def normalize_sources(fr: Dict[str, Any]) -> List[Dict[str, Any]]:
115
- out: List[Dict[str, Any]] = []
116
- if fr.get("type") == "sources":
117
- nodes = (fr.get("data") or {}).get("nodes") or []
118
- for n in nodes:
119
- out.append({"text": n.get("text") or n.get("content") or "", "metadata": n.get("metadata") or {}})
120
- # Alternate shapes
121
- for key in ("sources", "source_nodes", "nodes"):
122
- if isinstance(fr.get(key), list):
123
- for n in fr[key]:
124
- out.append({"text": n.get("text") or n.get("content") or "", "metadata": n.get("metadata") or {}})
125
- return out
126
-
127
- def extract_all_json_objects(mixed_text: str) -> List[Dict[str, Any]]:
128
- """Pull JSON objects out of a mixed or SSE-like body by brace matching."""
129
- objs: List[Dict[str, Any]] = []
130
- s = mixed_text or ""
131
- i, n = 0, len(s)
132
- while i < n:
133
- start = s.find("{", i)
134
- if start < 0:
135
- break
136
- depth, j, in_str, esc = 0, start, False, False
137
- while j < n:
138
- c = s[j]
139
- if in_str:
140
- if esc:
141
- esc = False
142
- elif c == "\\":
143
- esc = True
144
- elif c == '"':
145
- in_str = False
146
- else:
147
- if c == '"':
148
- in_str = True
149
- elif c == "{":
150
- depth += 1
151
- elif c == "}":
152
- depth -= 1
153
- if depth == 0:
154
- chunk = s[start : j + 1]
155
- try:
156
- objs.append(json.loads(chunk))
157
- except Exception:
158
- pass
159
- i = j + 1
160
- break
161
- j += 1
162
- else:
163
- break
164
- return objs
165
-
166
- def stitch(frames: List[Dict[str, Any]]) -> Dict[str, Any]:
167
- msg_parts: List[str] = []
168
- sources: List[Dict[str, Any]] = []
169
- for fr in frames:
170
- msg_parts += extract_text_from_frame(fr)
171
- sources += normalize_sources(fr)
172
- message = " ".join([p.strip() for p in msg_parts]).strip()
173
- return {"message": message or None, "sources": sources}
174
-
175
- def llama_chat(pipeline: str, messages: List[Dict[str, str]], debug: bool = False) -> Dict[str, Any]:
176
- if not LLAMA_KEY:
177
- raise RuntimeError("Missing LLAMA_CLOUD_API_KEY (Space Settings → Secrets).")
178
- if not pipeline:
179
- raise RuntimeError("Missing Pipeline ID (enter it in the sidebar).")
180
-
181
- trimmed = messages[-keep_turns:]
182
-
183
- r = requests.post(
184
- f"{API_BASE}/{pipeline}/chat",
185
- headers={
186
- "Authorization": f"Bearer {LLAMA_KEY}",
187
- "Content-Type": "application/json",
188
- "Accept": "application/json",
189
- },
190
- json={"messages": trimmed, "stream": False},
191
- timeout=120,
192
- )
193
- ct = (r.headers.get("Content-Type") or "").lower()
194
- body = r.text or ""
195
-
196
- try:
197
- r.raise_for_status()
198
- except requests.HTTPError as e:
199
- raise RuntimeError(f"LlamaCloud HTTP {r.status_code} ({ct}): {body[:500]}") from e
200
-
201
- # 1) Try simple JSON
202
- try:
203
- data = r.json()
204
- if debug:
205
- with st.expander("Raw JSON response"):
206
- st.code(json.dumps(data, indent=2))
207
- # If JSON already includes message, return as-is
208
- msg = deep_get(data, ["message", "answer", "content"])
209
- if msg and msg.strip():
210
- return {"message": msg.strip(), "sources": data.get("sources") or data.get("source_nodes") or []}
211
- # If not, try frames-style from JSON (some backends wrap frames)
212
- if isinstance(data, list):
213
- res = stitch(data)
214
- if debug:
215
- with st.expander("Stitched from JSON list"):
216
- st.code(json.dumps(res, indent=2))
217
- if res.get("message") or res.get("sources"):
218
- return res
219
- # Fall through to mixed parsing
220
- except json.JSONDecodeError:
221
- pass
222
-
223
- # 2) Mixed/SSE-style: extract objects and stitch
224
- frames = extract_all_json_objects(body)
225
- if debug:
226
- with st.expander("Parsed frames"):
227
- st.code(json.dumps(frames[:10], indent=2) if frames else "(no frames)")
228
- if frames:
229
- res = stitch(frames)
230
- if debug:
231
- with st.expander("Stitched result"):
232
- st.code(json.dumps(res, indent=2))
233
- if res.get("message") or res.get("sources"):
234
- return res
235
-
236
- # 3) Nothing usable
237
- raise RuntimeError(f"Unparseable response ({ct}): {body[:500]}")
238
-
239
- def render_sources(sources: List[Dict[str, Any]]):
240
- if not sources:
241
- return
242
- st.caption("Sources")
243
- for i, s in enumerate(sources, start=1):
244
- meta = s.get("metadata", {}) or {}
245
- fname = meta.get("file_name") or meta.get("source") or meta.get("file_path") or "Document"
246
- page = meta.get("page") or meta.get("page_number") or meta.get("page_label")
247
- label = f"[S{i}] {fname}" + (f" • p.{page}" if page else "")
248
- text = s.get("text") or s.get("content") or ""
249
- with st.expander(label):
250
- st.write(text[:2000] + ("…" if len(text) > 2000 else ""))
251
- if meta:
252
- st.code(meta, language="json")
253
-
254
- # ------------ Chat state ------------
255
  if "messages" not in st.session_state:
256
  st.session_state.messages = []
257
 
 
258
  for m in st.session_state.messages:
259
  with st.chat_message(m["role"]):
260
  st.markdown(m["content"])
261
 
262
- # ------------ Input ------------
263
  q = st.chat_input("Ask a question about your documents…")
 
264
  if q:
265
  st.session_state.messages.append({"role": "user", "content": q})
266
  with st.chat_message("user"):
267
  st.markdown(q)
268
 
269
  with st.chat_message("assistant"):
270
- with st.spinner("Thinking…"):
271
  try:
272
- data = llama_chat(
273
- pipeline=pipeline_id or DEFAULT_PIPELINE,
274
- messages=st.session_state.messages,
275
- debug=show_debug,
 
 
 
 
 
 
 
 
276
  )
277
- answer = data.get("message") or data.get("answer") or ""
278
- sources = data.get("sources") or data.get("source_nodes") or []
279
-
280
- if not answer and sources:
281
- answer = "I couldn’t generate a final answer, but here are the most relevant sources."
282
-
283
- st.markdown(answer or "No answer.")
284
- render_sources(sources)
285
-
286
- st.session_state.messages.append({"role": "assistant", "content": answer or "No answer."})
287
  except Exception as e:
288
  st.error(f"Chat failed: {e}")
 
1
  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}")