jsantangelo commited on
Commit
f7e07fd
·
verified ·
1 Parent(s): 0e272f2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +166 -116
app.py CHANGED
@@ -2,6 +2,7 @@ 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"
@@ -11,112 +12,177 @@ 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
- # ------------ Helpers ------------
15
- def _extract_json_objects(mixed_text: str):
16
- """
17
- Robustly pull all JSON objects out of a mixed/streamed response body.
18
- Handles cases like SSE/NDJSON or numbered frames (e.g., '8:[{...}]').
19
- Returns a list of parsed Python dicts.
20
- """
21
- objs = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  i = 0
23
- n = len(mixed_text)
24
  while i < n:
25
- # find next '{'
26
  start = mixed_text.find("{", i)
27
  if start == -1:
28
  break
29
- # scan with brace depth
30
  depth = 0
31
  j = start
 
 
32
  while j < n:
33
  c = mixed_text[j]
34
- if c == "{":
35
- depth += 1
36
- elif c == "}":
37
- depth -= 1
38
- if depth == 0:
39
- chunk = mixed_text[start:j+1]
40
- try:
41
- obj = json.loads(chunk)
42
- objs.append(obj)
43
- except Exception:
44
- pass
45
- i = j + 1
46
- break
 
 
 
 
 
 
 
 
 
 
47
  j += 1
48
  else:
49
- # unmatched braces; stop
50
  break
51
  return objs
52
 
53
- def _stitch_frames(frames):
54
- """
55
- Combine multiple event frames into a single result with message + sources.
56
- Accepts a list of dicts (parsed frames).
57
- """
58
- message_parts = []
59
- sources_accum = []
 
 
 
 
 
 
 
 
 
 
60
 
61
  for fr in frames:
62
- # Common shapes:
63
- # 1) {"type":"message","data":{"content":"..."}} or {"message": "..."}
64
- # 2) {"type":"delta","data":{"content":"..."}} (streaming tokens)
65
- # 3) {"type":"sources","data":{"nodes":[...]}}
66
- # 4) {"answer":"...", "source_nodes":[...]}
67
- if "message" in fr and isinstance(fr["message"], str):
68
- message_parts.append(fr["message"])
69
- if "answer" in fr and isinstance(fr["answer"], str):
70
- message_parts.append(fr["answer"])
71
 
 
72
  t = fr.get("type")
73
  data = fr.get("data") or {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  if t in ("message", "assistant_message", "final_message"):
75
- content = data.get("content")
76
- if isinstance(content, str):
77
- message_parts.append(content)
78
  elif t in ("delta", "assistant_delta"):
79
- delta = data.get("content")
80
- if isinstance(delta, str):
81
- message_parts.append(delta)
82
- elif t == "sources":
83
  nodes = data.get("nodes") or []
84
- # Normalize each node to {text, metadata:{...}}
85
  for n in nodes:
86
- normalized = {
87
  "text": n.get("text") or n.get("content") or "",
88
  "metadata": n.get("metadata") or {},
89
- }
90
- sources_accum.append(normalized)
91
 
92
- # Non-typed but typical shapes
93
- if "sources" in fr and isinstance(fr["sources"], list):
94
  for s in fr["sources"]:
95
- sources_accum.append({
96
  "text": s.get("text") or s.get("content") or "",
97
  "metadata": s.get("metadata") or {},
98
  })
99
- if "source_nodes" in fr and isinstance(fr["source_nodes"], list):
 
100
  for s in fr["source_nodes"]:
101
- sources_accum.append({
102
  "text": s.get("text") or s.get("content") or "",
103
  "metadata": s.get("metadata") or {},
104
  })
105
 
106
- # Join message parts (trim spaces, dedupe trivial empties)
107
- message = "".join(message_parts).strip()
108
- return {"message": message or None, "sources": sources_accum}
109
 
110
- def llama_chat(pipeline: str, messages: list[dict]):
111
- """
112
- Calls LlamaCloud /chat. Forces non-streaming; if server still streams,
113
- parse frames and stitch into one JSON.
114
- """
115
  if not LLAMA_KEY:
116
  raise RuntimeError("Missing LLAMA_CLOUD_API_KEY (set it in Space Settings → Secrets).")
117
  if not pipeline:
118
  raise RuntimeError("Missing Pipeline ID (enter it in the sidebar).")
119
 
 
 
 
120
  r = requests.post(
121
  f"{API_BASE}/{pipeline}/chat",
122
  headers={
@@ -125,38 +191,48 @@ def llama_chat(pipeline: str, messages: list[dict]):
125
  "Accept": "application/json",
126
  },
127
  json={
128
- "messages": messages, # [{role:"user"/"assistant", content:"..."}]
129
- "stream": False, # request non-streaming
130
  },
131
  timeout=120,
132
  )
133
 
134
  ct = (r.headers.get("Content-Type") or "").lower()
135
  body = r.text or ""
136
- preview = body[:400]
137
 
138
  try:
139
  r.raise_for_status()
140
  except requests.HTTPError as e:
141
  raise RuntimeError(f"LlamaCloud HTTP {r.status_code} ({ct}): {preview}") from e
142
 
143
- # Try straight JSON first
144
  try:
145
- return r.json()
 
 
 
 
146
  except json.JSONDecodeError:
147
- pass # fall through to mixed/frames parsing
148
 
149
- # If it's SSE/NDJSON/mixed, extract objects and stitch
150
  frames = _extract_json_objects(body)
 
 
 
 
151
  if frames:
152
  stitched = _stitch_frames(frames)
 
 
 
153
  if stitched.get("message") or stitched.get("sources"):
154
  return stitched
155
 
156
- # Nothing usable parsed
157
  raise RuntimeError(f"Non-JSON response ({ct}): {preview}")
158
 
159
- def render_sources(sources):
160
  if not sources:
161
  return
162
  st.caption("Sources")
@@ -171,41 +247,6 @@ def render_sources(sources):
171
  if meta:
172
  st.code(meta, language="json")
173
 
174
- def do_health_check(pipeline_id: str):
175
- if not pipeline_id:
176
- st.error("Set a Pipeline ID first (sidebar).")
177
- return
178
- try:
179
- data = llama_chat(
180
- pipeline=pipeline_id,
181
- messages=[{"role": "user", "content": "ping"}],
182
- )
183
- st.success(f"Chat OK · keys: {', '.join(list(data.keys())[:5])}")
184
- except Exception as e:
185
- st.error(str(e))
186
-
187
- # ------------ Sidebar ------------
188
- with st.sidebar:
189
- st.subheader("Settings")
190
- pipeline_id = st.text_input(
191
- "Pipeline ID",
192
- value=DEFAULT_PIPELINE,
193
- help="Copy the UUID from cloud.llamaindex.ai → your pipeline URL",
194
- )
195
-
196
- st.caption(
197
- f"Key present: {'✅' if bool(LLAMA_KEY) else '❌'} • "
198
- f"Default Pipeline ID: {'✅' if bool(DEFAULT_PIPELINE) else '❌'}"
199
- )
200
-
201
- if st.button("Health check", key="health_check_btn"):
202
- do_health_check(pipeline_id or DEFAULT_PIPELINE)
203
-
204
- st.markdown("---")
205
- if st.button("Clear chat", key="clear_chat_btn"):
206
- st.session_state.messages = []
207
- st.rerun()
208
-
209
  # ------------ Chat State ------------
210
  if "messages" not in st.session_state:
211
  st.session_state.messages = []
@@ -218,27 +259,36 @@ for m in st.session_state.messages:
218
  # ------------ Input + Call ------------
219
  q = st.chat_input("Ask a question about your documents…")
220
  if q:
221
- # Add user turn
222
  st.session_state.messages.append({"role": "user", "content": q})
223
  with st.chat_message("user"):
224
  st.markdown(q)
225
 
226
- # Assistant turn
227
  with st.chat_message("assistant"):
228
  with st.spinner("Thinking…"):
229
  try:
230
  data = llama_chat(
231
  pipeline=pipeline_id or DEFAULT_PIPELINE,
232
  messages=st.session_state.messages,
 
233
  )
234
- # Common shapes: { message, sources, ... } or { answer, source_nodes, ... }
235
- answer = data.get("message") or data.get("answer") or "No answer."
236
- st.markdown(answer)
 
 
 
 
 
 
237
 
238
  sources = data.get("sources") or data.get("source_nodes") or []
 
 
 
 
 
239
  render_sources(sources)
240
 
241
- # Save assistant turn to history
242
- st.session_state.messages.append({"role": "assistant", "content": answer})
243
  except Exception as e:
244
  st.error(f"Chat failed: {e}")
 
2
  import json
3
  import requests
4
  import streamlit as st
5
+ from typing import List, Dict, Any
6
 
7
  # ------------ Config ------------
8
  API_BASE = "https://api.cloud.llamaindex.ai/api/v1/pipelines"
 
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(
19
+ "Pipeline ID",
20
+ value=DEFAULT_PIPELINE,
21
+ help="Copy the UUID from cloud.llamaindex.ai → your pipeline URL",
22
+ )
23
+ keep_turns = st.slider("Turns to send (history)", 1, 12, 6)
24
+ show_debug = st.toggle("Show debug for next answer", value=False, help="Print parsed frames and payload keys for the next query only.")
25
+
26
+ st.caption(
27
+ f"Key present: {'✅' if bool(LLAMA_KEY) else '❌'} • "
28
+ f"Default Pipeline ID: {'✅' if bool(DEFAULT_PIPELINE) else '❌'}"
29
+ )
30
+
31
+ if st.button("Health check", key="health_check_btn"):
32
+ try:
33
+ data = None
34
+ data = requests.post(
35
+ f"{API_BASE}/{(pipeline_id or DEFAULT_PIPELINE)}/chat",
36
+ headers={
37
+ "Authorization": f"Bearer {LLAMA_KEY}",
38
+ "Content-Type": "application/json",
39
+ "Accept": "application/json",
40
+ },
41
+ json={"messages": [{"role": "user", "content": "ping"}], "stream": False},
42
+ timeout=60,
43
+ )
44
+ ct = data.headers.get("Content-Type", "")
45
+ data.raise_for_status()
46
+ st.success(f"HTTP {data.status_code} · {ct}")
47
+ except Exception as e:
48
+ st.error(str(e))
49
+
50
+ st.markdown("---")
51
+ if st.button("Clear chat", key="clear_chat_btn"):
52
+ st.session_state.messages = []
53
+ st.rerun()
54
+
55
+ # ------------ Utils for mixed/streamed frames ------------
56
+ def _extract_json_objects(mixed_text: str) -> List[Dict[str, Any]]:
57
+ """Pull JSON objects from a mixed/streaming body."""
58
+ objs: List[Dict[str, Any]] = []
59
  i = 0
60
+ n = len(mixed_text or "")
61
  while i < n:
 
62
  start = mixed_text.find("{", i)
63
  if start == -1:
64
  break
 
65
  depth = 0
66
  j = start
67
+ in_str = False
68
+ esc = False
69
  while j < n:
70
  c = mixed_text[j]
71
+ if in_str:
72
+ if esc:
73
+ esc = False
74
+ elif c == "\\":
75
+ esc = True
76
+ elif c == '"':
77
+ in_str = False
78
+ else:
79
+ if c == '"':
80
+ in_str = True
81
+ elif c == "{":
82
+ depth += 1
83
+ elif c == "}":
84
+ depth -= 1
85
+ if depth == 0:
86
+ chunk = mixed_text[start:j+1]
87
+ try:
88
+ obj = json.loads(chunk)
89
+ objs.append(obj)
90
+ except Exception:
91
+ pass
92
+ i = j + 1
93
+ break
94
  j += 1
95
  else:
 
96
  break
97
  return objs
98
 
99
+ def _maybe_get_text(x: Any) -> str:
100
+ """Extract text content from common shapes."""
101
+ if isinstance(x, str):
102
+ return x
103
+ if isinstance(x, dict):
104
+ return (
105
+ x.get("content")
106
+ or x.get("text")
107
+ or x.get("message")
108
+ or ""
109
+ )
110
+ return ""
111
+
112
+ def _stitch_frames(frames: List[Dict[str, Any]]) -> Dict[str, Any]:
113
+ """Combine multiple frames into a single result: {message, sources}."""
114
+ parts: List[str] = []
115
+ sources: List[Dict[str, Any]] = []
116
 
117
  for fr in frames:
118
+ # Direct fields
119
+ if isinstance(fr.get("message"), str):
120
+ parts.append(fr["message"])
121
+ elif isinstance(fr.get("message"), dict):
122
+ parts.append(_maybe_get_text(fr["message"]))
123
+ if isinstance(fr.get("answer"), str):
124
+ parts.append(fr["answer"])
 
 
125
 
126
+ # Typed frames
127
  t = fr.get("type")
128
  data = fr.get("data") or {}
129
+
130
+ if isinstance(data, dict):
131
+ # data.message could be str or dict
132
+ if "message" in data:
133
+ parts.append(_maybe_get_text(data["message"]))
134
+ # deltas
135
+ if "delta" in data:
136
+ parts.append(_maybe_get_text(data["delta"]))
137
+ if "assistant_delta" in data:
138
+ parts.append(_maybe_get_text(data["assistant_delta"]))
139
+ if "message_delta" in data:
140
+ parts.append(_maybe_get_text(data["message_delta"]))
141
+ if "content" in data and isinstance(data["content"], str):
142
+ parts.append(data["content"])
143
+
144
  if t in ("message", "assistant_message", "final_message"):
145
+ parts.append(_maybe_get_text(data))
 
 
146
  elif t in ("delta", "assistant_delta"):
147
+ parts.append(_maybe_get_text(data))
148
+
149
+ # Sources in various shapes
150
+ if t == "sources":
151
  nodes = data.get("nodes") or []
 
152
  for n in nodes:
153
+ sources.append({
154
  "text": n.get("text") or n.get("content") or "",
155
  "metadata": n.get("metadata") or {},
156
+ })
 
157
 
158
+ if isinstance(fr.get("sources"), list):
 
159
  for s in fr["sources"]:
160
+ sources.append({
161
  "text": s.get("text") or s.get("content") or "",
162
  "metadata": s.get("metadata") or {},
163
  })
164
+
165
+ if isinstance(fr.get("source_nodes"), list):
166
  for s in fr["source_nodes"]:
167
+ sources.append({
168
  "text": s.get("text") or s.get("content") or "",
169
  "metadata": s.get("metadata") or {},
170
  })
171
 
172
+ message = "".join([p for p in parts if isinstance(p, str)]).strip()
173
+ return {"message": message or None, "sources": sources}
 
174
 
175
+ # ------------ Core call ------------
176
+ def llama_chat(pipeline: str, messages: List[Dict[str, str]], debug: bool = False) -> Dict[str, Any]:
177
+ """Call LlamaCloud /chat; handle JSON or mixed frames."""
 
 
178
  if not LLAMA_KEY:
179
  raise RuntimeError("Missing LLAMA_CLOUD_API_KEY (set it in Space Settings → Secrets).")
180
  if not pipeline:
181
  raise RuntimeError("Missing Pipeline ID (enter it in the sidebar).")
182
 
183
+ # Send only last N turns to keep payload small
184
+ trimmed = messages[-keep_turns:]
185
+
186
  r = requests.post(
187
  f"{API_BASE}/{pipeline}/chat",
188
  headers={
 
191
  "Accept": "application/json",
192
  },
193
  json={
194
+ "messages": trimmed,
195
+ "stream": False, # request non-streaming
196
  },
197
  timeout=120,
198
  )
199
 
200
  ct = (r.headers.get("Content-Type") or "").lower()
201
  body = r.text or ""
202
+ preview = body[:500]
203
 
204
  try:
205
  r.raise_for_status()
206
  except requests.HTTPError as e:
207
  raise RuntimeError(f"LlamaCloud HTTP {r.status_code} ({ct}): {preview}") from e
208
 
209
+ # Try simple JSON first
210
  try:
211
+ data = r.json()
212
+ if debug:
213
+ with st.expander("Raw JSON response"):
214
+ st.code(json.dumps(data, indent=2))
215
+ return data
216
  except json.JSONDecodeError:
217
+ pass
218
 
219
+ # Mixed/streamed: parse frames
220
  frames = _extract_json_objects(body)
221
+ if debug:
222
+ with st.expander("Parsed frames"):
223
+ st.code(json.dumps(frames, indent=2) if frames else "(no frames)")
224
+
225
  if frames:
226
  stitched = _stitch_frames(frames)
227
+ if debug:
228
+ with st.expander("Stitched result"):
229
+ st.code(json.dumps(stitched, indent=2))
230
  if stitched.get("message") or stitched.get("sources"):
231
  return stitched
232
 
 
233
  raise RuntimeError(f"Non-JSON response ({ct}): {preview}")
234
 
235
+ def render_sources(sources: List[Dict[str, Any]]):
236
  if not sources:
237
  return
238
  st.caption("Sources")
 
247
  if meta:
248
  st.code(meta, language="json")
249
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  # ------------ Chat State ------------
251
  if "messages" not in st.session_state:
252
  st.session_state.messages = []
 
259
  # ------------ Input + Call ------------
260
  q = st.chat_input("Ask a question about your documents…")
261
  if q:
 
262
  st.session_state.messages.append({"role": "user", "content": q})
263
  with st.chat_message("user"):
264
  st.markdown(q)
265
 
 
266
  with st.chat_message("assistant"):
267
  with st.spinner("Thinking…"):
268
  try:
269
  data = llama_chat(
270
  pipeline=pipeline_id or DEFAULT_PIPELINE,
271
  messages=st.session_state.messages,
272
+ debug=show_debug,
273
  )
274
+
275
+ # Common shapes
276
+ answer = None
277
+ if isinstance(data.get("message"), str):
278
+ answer = data["message"].strip() or None
279
+ elif isinstance(data.get("message"), dict):
280
+ answer = (_maybe_get_text(data["message"]) or "").strip() or None
281
+ if not answer and isinstance(data.get("answer"), str):
282
+ answer = data["answer"].strip() or None
283
 
284
  sources = data.get("sources") or data.get("source_nodes") or []
285
+
286
+ # Fallback: if no answer but we have sources, say so and show them
287
+ if not answer and sources:
288
+ answer = "I couldn’t generate a final answer, but here are the most relevant sources."
289
+ st.markdown(answer or "No answer.")
290
  render_sources(sources)
291
 
292
+ st.session_state.messages.append({"role": "assistant", "content": answer or "No answer."})
 
293
  except Exception as e:
294
  st.error(f"Chat failed: {e}")