Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
575 lines (512 loc) · 19.5 KB
/
Copy pathapp.py
File metadata and controls
575 lines (512 loc) · 19.5 KB
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
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
"""Dominic's Chat — Google sign-in, Telegram approval, memory, files, and web search."""
from __future__ import annotations
import html
import logging
import os
from pathlib import Path
from urllib.parse import unquote
import streamlit as st
import streamlit.components.v1 as components
from dotenv import load_dotenv
from backend import auth, llm, rag, registration, store, telegram
ROOT = Path(__file__).resolve().parent
load_dotenv(ROOT / ".env")
USER_AVATAR = str(ROOT / "asset" / "human-user-icon.png")
AGENT_AVATAR = str(ROOT / "asset" / "ai-agent-robot-icon.png")
TITLE = "Dominic's Chat"
TAGLINE = "A simple chat app with memory, file upload, and web search."
UPLOAD_TYPES = ["txt", "md", "pdf", "csv", "xlsx", "xls", "json", "log"]
MAX_UPLOAD_BYTES = 15 * 1024 * 1024
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
logger = logging.getLogger("dominic_chat")
SESSION_BAR = components.declare_component(
"session_bar",
path=str(ROOT / "components" / "session_bar"),
)
def main() -> None:
st.set_page_config(
page_title=TITLE,
page_icon=AGENT_AVATAR,
layout="centered",
initial_sidebar_state="expanded",
)
store.init()
missing = auth.missing_settings()
if missing:
st.title(TITLE)
st.error("Missing environment variables: " + ", ".join(missing))
st.stop()
telegram.ensure_poller()
_css()
if _query("code") or _query("error"):
_handle_oauth()
st.rerun()
wiping = bool(st.session_state.get("wipe_cookie"))
if wiping:
st.session_state["wipe_cookie"] = False
user = None
else:
user = _restore_user()
token = "" if wiping or not user else st.session_state.get("session_token") or ""
SESSION_BAR(token=token, wipe=wiping, key="session_bar", default=None)
_sidebar(user)
if user:
_chat(user)
else:
_gate()
def _handle_oauth() -> None:
error = _query("error")
if error:
description = _query("error_description") or error
st.session_state["auth_error"] = description
st.session_state["notice"] = "auth_error"
_clear_query()
return
code = _query("code") or ""
state = _query("state")
_clear_query()
if not code or store.code_used(code):
return
store.mark_code(code)
intent = store.consume_state(state)
if intent not in {"signin", "apply"}:
st.session_state["auth_error"] = "That sign-in link expired. Try again."
st.session_state["notice"] = "auth_error"
return
try:
profile = auth.exchange_code(code)
except Exception as exc:
st.session_state["auth_error"] = str(exc)
st.session_state["notice"] = "auth_error"
return
email = profile["email"]
name = profile["name"]
if registration.can_enter(email):
_start_session(email, name)
st.session_state.pop("notice", None)
return
if intent == "apply":
timezone_name = _client_timezone()
location = telegram.lookup_location(_client_ip())
requested_at = telegram.format_timestamp(timezone_name)
registration.upsert_pending(email, name, location, timezone_name, requested_at)
try:
message_id = telegram.send_access_request(name, email, location, timezone_name, requested_at)
registration.set_telegram_message(email, int(os.environ["ADMIN_TELEGRAM_CHAT_ID"]), message_id)
st.session_state["notice"] = "pending"
except Exception:
logger.warning("Access request was saved but Telegram could not be notified")
st.session_state["notice"] = "telegram_failed"
return
current = registration.status(email)
if current == "denied":
st.session_state["notice"] = "denied"
elif current == "pending":
st.session_state["notice"] = "waiting"
else:
st.session_state["notice"] = "need_apply"
def _start_session(email: str, name: str) -> None:
token = store.create_session(email, name)
st.session_state["session_token"] = token
st.session_state["user"] = {"email": email, "name": name}
def _restore_user() -> dict | None:
token = st.session_state.get("session_token") or _request_cookie()
session = store.get_session(token)
if not session or not registration.can_enter(session["email"]):
if session and not registration.can_enter(session["email"]):
store.delete_session(token)
st.session_state.pop("user", None)
st.session_state.pop("session_token", None)
return None
user = {"email": session["email"], "name": session["name"]}
st.session_state["user"] = user
st.session_state["session_token"] = token
return user
def _request_cookie() -> str | None:
try:
cookies = st.context.cookies
except Exception:
return None
if not cookies:
return None
raw = cookies.get("dvc_session") if hasattr(cookies, "get") else None
if not raw:
return None
return unquote(str(raw))
def _gate() -> None:
_clear_query()
signin = _auth_link("signin")
apply = _auth_link("apply")
notice = st.session_state.pop("notice", None)
auth_error = st.session_state.pop("auth_error", None)
_, mid, _ = st.columns([1, 1.15, 1])
with mid:
st.markdown(f"## {TITLE}")
st.caption(TAGLINE)
if notice == "pending":
st.info(
"Request sent. Dominic will approve or deny it on Telegram. "
"Stay here, then sign in again after you are approved."
)
elif notice == "waiting":
st.info("Your access request is waiting for Dominic's decision.")
elif notice == "denied":
st.error("Dominic denied this Google account.")
elif notice == "need_apply":
st.warning("This account does not have access yet. Use Apply for access.")
elif notice == "telegram_failed":
st.error(
"Google returned your name and email, but Telegram could not be notified. "
"Use Apply for access to try again."
)
elif notice == "auth_error":
st.error(auth_error or "Sign-in failed. Try again.")
st.markdown(
f'<a class="dc-auth dc-auth-primary" href="{html.escape(signin, quote=True)}" target="_self">Sign in with Google</a>'
f'<a class="dc-auth" href="{html.escape(apply, quote=True)}" target="_self">Apply for access</a>',
unsafe_allow_html=True,
)
def _auth_link(intent: str) -> str:
state = auth.new_state()
store.save_state(state, intent)
return auth.authorize_url(state)
def _sidebar(user: dict | None) -> None:
with st.sidebar:
st.markdown(f"### {TITLE}")
st.caption(TAGLINE)
if not user:
return
st.divider()
if st.button("New conversation", width="stretch"):
st.session_state["conversation_id"] = None
st.session_state["draft_web_search"] = False
st.session_state["generating"] = None
st.rerun()
current = st.session_state.get("conversation_id")
for convo in store.list_con
8000
versations(user["email"]):
label = convo["title"] or "New conversation"
selected = convo["id"] == current
if st.button(
label,
key=f"convo-{convo['id']}",
width="stretch",
type="primary" if selected else "secondary",
):
st.session_state["conversation_id"] = convo["id"]
st.session_state["generating"] = None
st.rerun()
st.divider()
st.caption(user["email"])
if st.button("Sign out", width="stretch"):
store.delete_session(st.session_state.get("session_token"))
st.session_state.clear()
st.session_state["wipe_cookie"] = True
st.rerun()
def _chat(user: dict) -> None:
st.markdown(f"## {TITLE}")
st.caption(TAGLINE)
upload_error = st.session_state.pop("upload_error", None)
if upload_error:
st.error(upload_error)
cid = st.session_state.get("conversation_id")
convo = store.get_conversation(cid, user["email"]) if cid else None
if cid and convo is None:
st.session_state["conversation_id"] = None
cid = None
messages = store.get_messages(cid) if convo else []
if not messages:
st.caption("Send a message to start.")
for message in messages:
avatar = USER_AVATAR if message["role"] == "user" else AGENT_AVATAR
with st.chat_message(message["role"], avatar=avatar):
st.markdown(message["content"])
files = store.list_files(cid) if convo else []
remove_id = None
if files:
columns = st.columns(len(files))
for column, item in zip(columns, files):
with column:
st.caption(item["filename"])
if st.button("✕", key=f"rmfile-{item['id']}", help=f"Remove {item['filename']}"):
remove_id = item["id"]
uploads, globe_clicked, web_on = _toolbar(convo, bool(files))
prompt = st.chat_input("Message")
if remove_id and cid:
store.delete_file(remove_id, cid, user["email"])
st.rerun()
if globe_clicked:
web_on = not web_on
if convo:
store.set_web_search(convo["id"], user["email"], web_on)
else:
st.session_state["draft_web_search"] = web_on
st.rerun()
if uploads:
_ingest(user, uploads)
if prompt and prompt.strip():
cid = _ensure_conversation(user)
store.add_message(cid, "user", prompt.strip())
store.set_title_if_new(cid, user["email"], prompt)
st.session_state["generating"] = cid
st.rerun()
if st.session_state.get("generating") and st.session_state.get("generating") == st.session_state.get("conversation_id"):
_answer(user)
def _toolbar(convo: dict | None, files_on: bool):
web_on = bool(convo["web_search"]) if convo else bool(st.session_state.get("draft_web_search"))
paper_class = "is-on" if files_on else "is-off"
globe_color = "#1a7f37" if web_on else "#d1242f"
st.markdown(
f"""
<style>
div[class*="st-key-globe"] button {{
background: {globe_color};
color: white;
border: none;
border-radius: 999px;
width: 44px;
height: 44px;
min-height: 44px;
padding: 0;
font-size: 18px;
}}
div[class*="st-key-globe"] button:hover,
div[class*="st-key-globe"] button:focus {{
background: {globe_color};
color: white;
border: none;
}}
</style>
<div class="dc-paperclip-slot">
<div class="dc-paperclip {paper_class}" title="Attach a file">📎</div>
</div>
""",
unsafe_allow_html=True,
)
nonce = st.session_state.get("upl_nonce", 0)
uploads = st.file_uploader(
"Attach a file",
type=UPLOAD_TYPES,
accept_multiple_files=True,
key=f"paperclip_uploader_{nonce}",
label_visibility="collapsed",
)
globe_clicked = st.button("🌐", key="globe", help="Web search")
return uploads, globe_clicked, web_on
def _ingest(user: dict, uploads) -> None:
cid = _ensure_conversation(user)
errors = []
for upload in uploads:
filename = Path(upload.name).name
data = upload.getvalue()
if len(data) > MAX_UPLOAD_BYTES:
errors.append(f"{filename} is larger than 15 MB.")
continue
try:
with st.spinner(f"Embedding {filename}…"):
text = rag.extract_text(filename, data)
chunks = rag.chunk_text(text)
embedded = rag.embed_chunks(chunks)
store.add_file(cid, user["email"], filename, text, embedded)
except Exception as exc:
errors.append(f"{filename}: {exc}")
st.session_state["upl_nonce"] = int(st.session_state.get("upl_nonce", 0)) + 1
if errors:
st.session_state["upload_error"] = " ".join(errors)
st.rerun()
def _ensure_conversation(user: dict) -> int:
cid = st.session_state.get("conversation_id")
if cid and store.get_conversation(cid, user["email"]):
return cid
cid = store.create_conversation(
user["email"],
web_search=bool(st.session_state.get("draft_web_search")),
)
st.session_state["conversation_id"] = cid
st.session_state["draft_web_search"] = False
return cid
def _answer(user: dict) -> None:
cid = st.session_state.get("conversation_id")
convo = store.get_conversation(cid, user["email"]) if cid else None
messages = store.get_messages(cid) if convo else []
if not convo or not messages or messages[-1]["role"] != "user":
st.session_state["generating"] = None
return
latest = messages[-1]["content"]
try:
summary, history = _memory_and_history(convo, messages)
file_context = ""
if store.list_files(cid):
file_context = rag.retrieve(latest, store.conversation_chunks(cid))
search_results = []
searched = False
search_failed = False
if llm.should_search(bool(convo["web_search"]), latest):
searched = True
try:
search_results = llm.web_search(latest, enabled=True)
except Exception:
logger.warning("Web search failed")
search_failed = True
payload = llm.build_messages(
summary=summary,
history=history,
file_context=file_context,
search_results=search_results,
language=llm.detect_language(latest),
)
with st.chat_message("assistant", avatar=AGENT_AVATAR):
if search_failed:
st.caption("Web search failed. Answering without it.")
elif searched and search_results:
st.caption("Using web search")
elif searched:
st.caption("Web search returned nothing. Answering without it.")
box = st.empty()
parts: list[str] = []
for piece in llm.stream_chat(payload):
parts.append(piece)
box.markdown("".join(parts))
reply = "".join(parts).strip() or "I couldn't produce a reply."
store.add_message(cid, "assistant", reply)
except Exception as exc:
logger.warning("Reply failed: %s", exc.__class__.__name__)
st.session_state["generating"] = None
st.error(str(exc) or "The reply failed.")
st.stop()
st.session_state["generating"] = None
st.rerun()
def _memory_and_history(convo: dict, messages: list[dict]) -> tuple[str, list[dict]]:
tail = store.TAIL_MESSAGES
summarized = int(convo.get("summarized_count") or 0)
summary = convo.get("summary") or ""
if len(messages) - tail - summarized >= 4:
pending = messages[summarized : len(messages) - tail]
sample = "\n".join(item["content"] for item in pending if item["role"] == "user")
try:
summary = llm.summarize(summary, pending, llm.detect_language(sample))
summarized += len(pending)
store.update_summary(convo["id"], summary, summarized)
except Exception:
logger.warning("Summary update failed")
summary = convo.get("summary") or ""
summarized = int(convo.get("summarized_count") or 0)
if len(messages) - summarized <= tail + 3:
history = messages[summarized:]
else:
history = messages[-tail:]
return summary, [{"role": item["role"], "content": item["content"]} for item in history]
def _client_timezone() -> str:
try:
value = getattr(st.context, "timezone", None)
except Exception:
return "Unknown"
return str(value) if value else "Unknown"
def _client_ip() -> str | None:
try:
value = getattr(st.context, "ip_address", None)
except Exception:
return None
return str(value) if value else None
def _query(name: str) -> str | None:
try:
value = st.query_params.get(name)
except Exception:
return None
if value is None:
return None
if isinstance(value, list):
return str(value[0]) if value else None
text = str(value).strip()
return text or None
def _clear_query() -> None:
try:
st.query_params.clear()
except Exception:
for key in list(st.query_params.keys()):
del st.query_params[key]
def _css() -> None:
st.markdown(
"""
<style>
div[data-testid="stElementContainer"]:has(.dc-paperclip-slot),
div[class*="st-key-globe"],
div[class*="st-key-paperclip_uploader"] {
position: fixed;
bottom: 14px;
margin: 0 !important;
padding: 0 !important;
width: 44px !important;
height: 44px !important;
min-height: 0 !important;
z-index: 1000002;
}
div[data-testid="stElementContainer"]:has(.dc-paperclip-slot) { left: 21rem; }
div[class*="st-key-globe"] { left: calc(21rem + 52px); }
div[class*="st-key-paperclip_uploader"] {
left: 21rem;
opacity: 0.012;
overflow: hidden;
z-index: 1000003;
}
[data-testid="stSidebar"][aria-expanded="false"] ~ section.main
div[data-testid="stElementContainer"]:has(.dc-paperclip-slot),
[data-testid="stSidebar"][aria-expanded="false"] ~ section.main
div[class*="st-key-paperclip_uploader"] {
left: 1.5rem;
}
[data-testid="stSidebar"][aria-expanded="false"] ~ section.main div[class*="st-key-globe"] {
left: calc(1.5rem + 52px);
}
.dc-paperclip {
width: 44px;
height: 44px;
border-radius: 999px;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 18px;
pointer-events: none;
box-shadow: none;
}
.dc-paperclip.is-off { background: #d1242f; }
.dc-paperclip.is-on { background: #1a7f37; }
div[class*="st-key-paperclip_uploader"] [data-testid="stFileUploader"],
div[class*="st-key-paperclip_uploader"] section,
div[class*="st-key-paperclip_uploader"] [data-testid="stFileUploaderDropzone"] {
min-height: 44px !important;
height: 44px !important;
padding: 0 !important;
margin: 0 !important;
border: 0 !important;
}
[data-testid="stBottom"] { padding-bottom: 58px !important; }
a.dc-auth,
a.dc-auth:visited,
a.dc-auth:hover {
display: block;
text-align: center;
text-decoration: none !important;
border-radius: 0.5rem;
padding: 0.55rem 0.75rem;
margin: 0.45rem 0;
border: 1px solid rgba(250, 250, 250, 0.25);
color: inherit !important;
font-weight: 600;
}
a.dc-auth-primary,
a.dc-auth-primary:visited,
a.dc-auth-primary:hover {
background: #ff4b4b;
color: #ffffff !important;
border-color: #ff4b4b;
}
footer { visibility: hidden; }
</style>
""",
unsafe_allow_html=True,
)
if __name__ == "__main__":
main()