-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
1056 lines (922 loc) · 36.5 KB
/
Copy pathbot.py
File metadata and controls
1056 lines (922 loc) · 36.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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import sqlite3
import asyncio
import base64
import logging
import mimetypes
import threading
from urllib.parse import urlparse
from datetime import datetime, timedelta
from texts import make_t
from telegram import (
Update,
ReplyKeyboardMarkup,
KeyboardButton,
InlineKeyboardMarkup,
InlineKeyboardButton,
)
from telegram.ext import (
ApplicationBuilder, CommandHandler,
MessageHandler, CallbackQueryHandler, ContextTypes, filters
)
def _load_dotenv(path: str = ".env") -> None:
"""
Minimal .env loader (no external deps).
- Ignores comments/blank lines
- Supports optional "export KEY=VALUE"
- Does not override already-set environment variables
"""
try:
with open(path, "r", encoding="utf-8") as f:
for raw_line in f:
line = raw_line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("export "):
line = line[len("export ") :].lstrip()
if "=" not in line:
continue
key, value = line.split("=", 1)
key = key.strip()
value = value.strip()
if not key:
continue
if value and len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
value = value[1:-1]
if key not in os.environ:
os.environ[key] = value
except FileNotFoundError:
return
def _env_bool(name: str, default: bool) -> bool:
v = os.getenv(name)
if v is None:
return default
return v.strip() not in ("0", "false", "False", "no", "NO", "")
def _env_int(name: str, default: int) -> int:
v = os.getenv(name)
if v is None or not v.strip():
return default
try:
return int(v.strip())
except ValueError:
raise SystemExit(tr("ERR_ENV_INT", name=name, value=v))
def _require_env(name: str) -> str:
v = os.getenv(name, "").strip()
if not v:
raise SystemExit(tr("ERR_ENV_REQUIRED", name=name))
return v
def _parse_int_list(raw: str) -> list[int]:
s = (raw or "").strip()
if not s:
return []
out: list[int] = []
for part in re.split(r"[,\s]+", s):
p = part.strip()
if not p:
continue
try:
out.append(int(p))
except ValueError:
raise SystemExit(tr("ERR_ALLOWED_USER_ID", value=p))
return out
# Load .env early so config below can read it.
_load_dotenv()
BOT_LANG = os.getenv("BOT_LANG", "ru")
tr = make_t(BOT_LANG)
# LangChain imports are intentionally inside a try/except to keep the error message clear
# for first-time setup (installing requirements).
try:
from langchain_openai import ChatOpenAI
try:
# LangChain >= 1.x
from langchain.agents import create_agent # type: ignore
_LC_HAS_GRAPH_AGENT = True
except Exception:
# LangChain < 1.x (legacy)
from langchain.agents import AgentType, initialize_agent # type: ignore
_LC_HAS_GRAPH_AGENT = False
try:
from langchain_community.utilities import SQLDatabase
from langchain_community.agent_toolkits.sql.toolkit import SQLDatabaseToolkit
except ImportError: # older layouts
from langchain.utilities import SQLDatabase # type: ignore
from langchain.agents.agent_toolkits.sql.toolkit import SQLDatabaseToolkit # type: ignore
try:
from langchain_core.tools import tool
except ImportError:
from langchain.tools import tool # type: ignore
try:
from langchain_core.messages import HumanMessage, AIMessage
except ImportError:
from langchain.schema import HumanMessage, AIMessage # type: ignore
except Exception as e: # pragma: no cover
raise SystemExit(
tr("ERR_LANGCHAIN_DEPS", error=e)
)
# ==========================
# CONFIG
# ==========================
LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO").strip().upper() or "INFO"
logging.basicConfig(level=getattr(logging, LOG_LEVEL, logging.INFO))
TELEGRAM_TOKEN = _require_env("TELEGRAM_TOKEN")
OPENAI_API_KEY = _require_env("OPENAI_API_KEY")
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-5.2").strip() or "gpt-5.2"
OPENAI_VISION_MODEL = os.getenv("OPENAI_VISION_MODEL", OPENAI_MODEL).strip() or OPENAI_MODEL
OPENAI_WEB_SEARCH_MODEL = os.getenv("OPENAI_WEB_SEARCH_MODEL", OPENAI_MODEL).strip() or OPENAI_MODEL
WEB_SEARCH_ENABLED = _env_bool("WEB_SEARCH_ENABLED", True)
DB_PATH = os.getenv("BOT_DB_PATH", "diary.db").strip() or "diary.db"
DB_URI = f"sqlite:///{DB_PATH}"
# ==========================
# ACCESS CONTROL
# ==========================
# Укажи Telegram user_id пользователей, которым разрешён доступ.
# Пользователи не из списка не получают ответов и их сообщения не сохраняются.
_allowed_raw = os.getenv("ALLOWED_USER_IDS")
if _allowed_raw is None:
raise SystemExit(tr("ERR_ALLOWED_USER_IDS_MISSING"))
ALLOWED_USER_IDS: list[int] = _parse_int_list(_allowed_raw)
_ALLOWED_USER_IDS_SET = set(ALLOWED_USER_IDS)
def _is_allowed(update: Update) -> bool:
if not _ALLOWED_USER_IDS_SET:
return True # список пуст => доступ открыт (удобно для разработки)
user = update.effective_user
return bool(user and user.id in _ALLOWED_USER_IDS_SET)
SUMMARY_DAY_LABEL = tr("SUMMARY_DAY")
SUMMARY_WEEK_LABEL = tr("SUMMARY_WEEK")
SUMMARY_MONTH_LABEL = tr("SUMMARY_MONTH")
BTN_DIARY = tr("BTN_DIARY")
BTN_CHAT = tr("BTN_CHAT")
BTN_LIST = tr("BTN_LIST")
BTN_SHOW = tr("BTN_SHOW")
BTN_PAUSE = tr("BTN_PAUSE")
BTN_RESUME = tr("BTN_RESUME")
BTN_HELP = tr("BTN_HELP")
MAIN_KEYBOARD = ReplyKeyboardMarkup(
[
[KeyboardButton(BTN_DIARY), KeyboardButton(BTN_CHAT), KeyboardButton(BTN_LIST)],
[KeyboardButton(BTN_SHOW)],
[KeyboardButton(SUMMARY_DAY_LABEL), KeyboardButton(SUMMARY_WEEK_LABEL), KeyboardButton(SUMMARY_MONTH_LABEL)],
[KeyboardButton(BTN_PAUSE), KeyboardButton(BTN_RESUME), KeyboardButton(BTN_HELP)],
],
resize_keyboard=True,
)
PHOTO_DIR = os.getenv("PHOTO_DIR", "diary_photos").strip() or "diary_photos"
os.makedirs(PHOTO_DIR, exist_ok=True)
# ==========================
# DATABASE
# ==========================
# autocommit: every write is committed immediately (unless you explicitly BEGIN a transaction)
conn = sqlite3.connect(DB_PATH, check_same_thread=False, timeout=30, isolation_level=None)
c = conn.cursor()
db_lock = threading.Lock()
with db_lock:
# Improve concurrency between multiple connections (LangChain/SQLAlchemy + this sqlite3 connection)
# and reduce "database is locked" errors under bursts.
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA busy_timeout=5000")
c.execute("""
CREATE TABLE IF NOT EXISTS diary (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
date TEXT,
text TEXT,
photo_path TEXT
)
""")
c.execute("""
CREATE TABLE IF NOT EXISTS tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE
)
""")
c.execute("""
CREATE TABLE IF NOT EXISTS diary_tags (
diary_id INTEGER,
tag_id INTEGER
)
""")
c.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_diary_tags_unique ON diary_tags(diary_id, tag_id)")
c.execute("""
CREATE TABLE IF NOT EXISTS assistant_memory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
UNIQUE(user_id, key)
)
""")
conn.commit()
# ==========================
# STATE
# ==========================
user_modes = {} # diary | chat
browse_offsets = {} # diary browsing
# ==========================
# LIST / PAGINATION
# ==========================
DIARY_PAGE_SIZE = _env_int("DIARY_PAGE_SIZE", 5)
def _format_preview(text: str, max_len: int = 80) -> str:
t = (text or "").replace("\n", " ").strip()
t = re.sub(r"\s+", " ", t)
if len(t) <= max_len:
return t
return t[: max_len - 1] + "…"
def _diary_page_keyboard(uid: int, page: int, total_pages: int) -> InlineKeyboardMarkup | None:
if total_pages <= 1:
return None
prev_page = max(0, page - 1)
next_page = min(total_pages - 1, page + 1)
buttons: list[InlineKeyboardButton] = []
if page > 0:
buttons.append(InlineKeyboardButton(tr("NAV_PREV"), callback_data=f"diary_page:{uid}:{prev_page}"))
if page < total_pages - 1:
buttons.append(InlineKeyboardButton(tr("NAV_NEXT"), callback_data=f"diary_page:{uid}:{next_page}"))
return InlineKeyboardMarkup([buttons]) if buttons else None
def _render_diary_page(uid: int, page: int) -> tuple[str, InlineKeyboardMarkup | None]:
page = max(0, int(page))
offset = page * DIARY_PAGE_SIZE
with db_lock:
total = c.execute("SELECT COUNT(*) FROM diary WHERE user_id=?", (uid,)).fetchone()[0]
rows = c.execute(
"SELECT id, date, text, photo_path FROM diary WHERE user_id=? ORDER BY date DESC LIMIT ? OFFSET ?",
(uid, DIARY_PAGE_SIZE, offset),
).fetchall()
if not total:
return tr("DIARY_EMPTY"), None
total_pages = max(1, (total + DIARY_PAGE_SIZE - 1) // DIARY_PAGE_SIZE)
page = min(page, total_pages - 1)
header = tr("DIARY_LIST_HEADER", page=page + 1, total_pages=total_pages, total=total)
parts: list[str] = [header]
open_rows: list[list[InlineKeyboardButton]] = []
for diary_id, d, t, photo_path in rows:
marker = "📸 " if photo_path else ""
parts.append(f"{marker}#{diary_id} · {d}\n{_format_preview(t)}\n")
open_rows.append([InlineKeyboardButton(tr("DIARY_OPEN_BTN", diary_id=diary_id), callback_data=f"diary_open:{uid}:{diary_id}:{page}")])
nav = _diary_page_keyboard(uid, page, total_pages)
if nav:
open_rows.extend(nav.inline_keyboard)
keyboard = InlineKeyboardMarkup(open_rows)
else:
keyboard = InlineKeyboardMarkup(open_rows) if open_rows else None
return "\n".join(parts).strip(), keyboard
# ==========================
# UTILS
# ==========================
def extract_user_tags(text: str):
if not text:
return []
return list(set(t.lower() for t in re.findall(r"#(\w+)", text)))
def save_tags(diary_id, tags):
if not tags:
return
with db_lock:
for tag in tags:
c.execute("INSERT OR IGNORE INTO tags (name) VALUES (?)", (tag,))
c.execute("SELECT id FROM tags WHERE name=?", (tag,))
row = c.fetchone()
if not row:
continue
tag_id = row[0]
c.execute(
"INSERT OR IGNORE INTO diary_tags (diary_id, tag_id) VALUES (?,?)",
(diary_id, tag_id)
)
conn.commit()
def get_diary_tags(diary_id: int) -> list[str]:
with db_lock:
rows = c.execute(
"""
SELECT tags.name
FROM tags
JOIN diary_tags ON diary_tags.tag_id = tags.id
WHERE diary_tags.diary_id=?
ORDER BY tags.name
""",
(diary_id,),
).fetchall()
return [r[0] for r in rows]
# ==========================
# LANGCHAIN AGENT
# ==========================
class AssistantAgentManager:
def __init__(self):
self._executors: dict[int, object] = {}
self._histories: dict[int, list[object]] = {}
self._lock = threading.Lock()
self._max_messages = 24
def _make_llm(self):
try:
return ChatOpenAI(model=OPENAI_MODEL, api_key=OPENAI_API_KEY, temperature=0)
except TypeError:
return ChatOpenAI(model=OPENAI_MODEL, openai_api_key=OPENAI_API_KEY, temperature=0)
def _make_executor(self, uid: int):
llm = self._make_llm()
# Using from_uri keeps compatibility across LangChain versions.
try:
db = SQLDatabase.from_uri(
DB_URI,
include_tables=[
"diary",
"tags",
"diary_tags",
"assistant_memory",
],
)
except TypeError:
db = SQLDatabase.from_uri(DB_URI)
toolkit = SQLDatabaseToolkit(db=db, llm=llm)
system_rules = tr("AGENT_SYSTEM_PROMPT", uid=uid)
def _normalize_tag(tag: str) -> str:
tag = (tag or "").strip().lower()
tag = re.sub(r"[^0-9a-zа-яё_]+", "", tag, flags=re.IGNORECASE)
return tag[:32]
def _normalize_domain(raw: str) -> str | None:
s = (raw or "").strip()
if not s:
return None
if "://" not in s:
s = "https://" + s
try:
host = (urlparse(s).netloc or "").strip().lower()
except Exception:
return None
host = host.split("@")[-1] # strip userinfo
host = host.split(":")[0] # strip port
host = host.strip(".")
return host or None
@tool
def web_search(query: str, domains_csv: str = "", external_web_access: bool = True) -> str:
if not WEB_SEARCH_ENABLED:
return tr("WEB_SEARCH_DISABLED")
q = (query or "").strip()
if not q:
return tr("WEB_SEARCH_EMPTY_QUERY")
allowed_domains: list[str] = []
if domains_csv:
for part in re.split(r"[,\s]+", domains_csv):
d = _normalize_domain(part)
if d:
allowed_domains.append(d)
seen: set[str] = set()
allowed_domains = [d for d in allowed_domains if not (d in seen or seen.add(d))]
allowed_domains = allowed_domains[:100]
# Optional location hints (set via env vars if you want localized results).
loc: dict[str, str] = {}
for env_key, loc_key in (
("WEB_SEARCH_COUNTRY", "country"),
("WEB_SEARCH_REGION", "region"),
("WEB_SEARCH_CITY", "city"),
("WEB_SEARCH_TIMEZONE", "timezone"),
):
v = os.getenv(env_key, "").strip()
if v:
loc[loc_key] = v
tool_cfg: dict = {
"type": "web_search",
"search_context_size": "medium",
"external_web_access": bool(external_web_access),
}
if allowed_domains:
tool_cfg["filters"] = {"allowed_domains": allowed_domains}
if loc:
tool_cfg["user_location"] = loc
from openai import OpenAI
client = OpenAI(api_key=OPENAI_API_KEY)
resp = client.responses.create(
model=OPENAI_WEB_SEARCH_MODEL,
input=q,
tools=[tool_cfg],
)
text = getattr(resp, "output_text", None)
if text:
return str(text).strip()
return str(resp)
web_search.__doc__ = tr("WEB_SEARCH_DOC")
@tool
def describe_photo(photo_path: str) -> str:
path = (photo_path or "").strip()
if not path or not os.path.exists(path):
return tr("FILE_NOT_FOUND")
try:
size = os.path.getsize(path)
except OSError:
size = 0
if size and size > 12 * 1024 * 1024:
return tr("PHOTO_TOO_BIG")
mime, _ = mimetypes.guess_type(path)
mime = mime or "image/jpeg"
with open(path, "rb") as f:
b64 = base64.b64encode(f.read()).decode("utf-8")
data_url = f"data:{mime};base64,{b64}"
try:
vision_llm = ChatOpenAI(model=OPENAI_VISION_MODEL, api_key=OPENAI_API_KEY, temperature=0)
except TypeError:
vision_llm = ChatOpenAI(model=OPENAI_VISION_MODEL, openai_api_key=OPENAI_API_KEY, temperature=0)
msg = HumanMessage(
content=[
{"type": "text", "text": tr("VISION_PROMPT")},
{"type": "image_url", "image_url": {"url": data_url}},
]
)
out = vision_llm.invoke([msg])
return (getattr(out, "content", None) or str(out)).strip()
describe_photo.__doc__ = tr("DESCRIBE_PHOTO_DOC")
@tool
def update_diary_text(diary_id: int, new_text: str) -> str:
text_n = (new_text or "").strip()
if not text_n:
return tr("EMPTY_NEW_TEXT")
text_n = text_n[:8000]
with db_lock:
row = c.execute(
"SELECT id FROM diary WHERE id=? AND user_id=?",
(int(diary_id), uid),
).fetchone()
if not row:
return tr("ENTRY_NOT_FOUND")
c.execute(
"UPDATE diary SET text=? WHERE id=? AND user_id=?",
(text_n, int(diary_id), uid),
)
conn.commit()
return tr("DIARY_TEXT_UPDATED")
update_diary_text.__doc__ = tr("UPDATE_DIARY_DOC")
@tool
def remember(key: str, value: str) -> str:
key_n = (key or "").strip().lower()[:64]
value_n = (value or "").strip()[:2000]
if not key_n or not value_n:
return tr("NEED_KEY_VALUE")
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with db_lock:
c.execute(
"""
INSERT INTO assistant_memory (user_id, key, value, created_at, updated_at)
VALUES (?,?,?,?,?)
ON CONFLICT(user_id, key) DO UPDATE SET
value=excluded.value,
updated_at=excluded.updated_at
""",
(uid, key_n, value_n, now, now),
)
conn.commit()
return tr("SAVED_KEY", key=key_n)
remember.__doc__ = tr("REMEMBER_DOC")
@tool
def forget(key: str) -> str:
key_n = (key or "").strip().lower()[:64]
if not key_n:
return tr("NEED_KEY")
with db_lock:
c.execute("DELETE FROM assistant_memory WHERE user_id=? AND key=?", (uid, key_n))
conn.commit()
return tr("DELETED_KEY", key=key_n)
forget.__doc__ = tr("FORGET_DOC")
@tool
def add_tags_to_diary(diary_id: int, tags_csv: str) -> str:
tags = []
for raw in (tags_csv or "").split(","):
t = _normalize_tag(raw)
if t:
tags.append(t)
tags = sorted(set(tags))
if not tags:
return tr("NO_VALID_TAGS")
with db_lock:
row = c.execute(
"SELECT id FROM diary WHERE id=? AND user_id=?",
(int(diary_id), uid),
).fetchone()
if not row:
return tr("ENTRY_NOT_FOUND")
save_tags(int(diary_id), tags)
return tr("TAGS_ADDED", tags=", ".join(f"#{t}" for t in tags))
add_tags_to_diary.__doc__ = tr("ADD_TAGS_DOC")
tools = toolkit.get_tools() + [web_search, describe_photo, update_diary_text, remember, forget, add_tags_to_diary]
if _LC_HAS_GRAPH_AGENT:
agent_graph = create_agent(llm, tools=tools, system_prompt=system_rules, debug=False)
return agent_graph
# Legacy (LangChain < 1.x)
agent_type = AgentType.OPENAI_FUNCTIONS if hasattr(AgentType, "OPENAI_FUNCTIONS") else AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION
try:
agent_executor = initialize_agent(
tools=tools,
llm=llm,
agent=agent_type,
verbose=False,
handle_parsing_errors=True,
agent_kwargs={"system_message": system_rules},
)
except TypeError:
agent_executor = initialize_agent(
tools=tools,
llm=llm,
agent=agent_type,
verbose=False,
handle_parsing_errors=True,
agent_kwargs={"prefix": system_rules},
)
return agent_executor
def reset_user(self, uid: int):
with self._lock:
self._executors.pop(uid, None)
self._histories.pop(uid, None)
async def run(self, uid: int, mode: str, user_text: str) -> str:
with self._lock:
executor = self._executors.get(uid)
if executor is None:
executor = self._make_executor(uid)
self._executors[uid] = executor
prompt = (
f"mode={mode}\n"
f"user_id={uid}\n"
f"message:\n{user_text}"
)
def _invoke():
if _LC_HAS_GRAPH_AGENT and hasattr(executor, "invoke"):
with self._lock:
history = list(self._histories.get(uid, []))
messages = history + [HumanMessage(content=prompt)]
out = executor.invoke({"messages": messages})
msg_list = out.get("messages") if isinstance(out, dict) else None
if isinstance(msg_list, list) and msg_list:
# keep last N messages as in-memory context
with self._lock:
self._histories[uid] = msg_list[-self._max_messages :]
# extract last AI message text
for m in reversed(msg_list):
content = getattr(m, "content", None)
mtype = getattr(m, "type", None)
if mtype == "ai" and content:
return str(content)
if isinstance(m, dict) and m.get("role") == "assistant" and m.get("content"):
return str(m["content"])
return str(out)
# Legacy AgentExecutor surface
if hasattr(executor, "invoke"):
out = executor.invoke({"input": prompt})
if isinstance(out, dict):
return out.get("output") or out.get("result") or str(out)
return str(out)
if hasattr(executor, "run"):
return executor.run(prompt)
return str(executor(prompt))
return (await asyncio.to_thread(_invoke)).strip()
agent_manager = AssistantAgentManager()
# ==========================
# COMMANDS
# ==========================
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not _is_allowed(update):
return
await update.message.reply_text(
tr("START_TEXT"),
reply_markup=MAIN_KEYBOARD,
)
async def menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not _is_allowed(update):
return
await update.message.reply_text(tr("MENU"), reply_markup=MAIN_KEYBOARD)
async def diary_mode(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not _is_allowed(update):
return
user_modes[update.message.from_user.id] = "diary"
await update.message.reply_text(tr("DIARY_MODE_ON"))
async def pause_diary(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not _is_allowed(update):
return
uid = update.message.from_user.id
user_modes[uid] = "paused"
await update.message.reply_text(tr("DIARY_PAUSED"))
async def resume_diary(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not _is_allowed(update):
return
uid = update.message.from_user.id
user_modes[uid] = "diary"
await update.message.reply_text(tr("DIARY_RESUMED"))
async def help_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not _is_allowed(update):
return
await update.message.reply_text(tr("HELP_TEXT"))
def _period_bounds_yesterday():
now = datetime.now()
yesterday = (now - timedelta(days=1)).date()
start = datetime(yesterday.year, yesterday.month, yesterday.day, 0, 0, 0)
end = datetime(yesterday.year, yesterday.month, yesterday.day, 23, 59, 59)
return start, end
def _period_bounds_days_ending_yesterday(days: int):
if days < 1:
days = 1
_, end = _period_bounds_yesterday()
start_date = (end - timedelta(days=days - 1)).date()
start = datetime(start_date.year, start_date.month, start_date.day, 0, 0, 0)
return start, end
async def _summary_for_period(update: Update, context: ContextTypes.DEFAULT_TYPE, label: str, start_dt: datetime, end_dt: datetime):
if not _is_allowed(update):
return
uid = update.message.from_user.id
start_s = start_dt.strftime("%Y-%m-%d %H:%M:%S")
end_s = end_dt.strftime("%Y-%m-%d %H:%M:%S")
await update.message.reply_text(tr("SUMMARY_PREPARING", label=label, start=start_s, end=end_s))
try:
answer = await agent_manager.run(
uid,
mode="summary",
user_text=tr("SUMMARY_AGENT_PROMPT", label=label, start=start_s, end=end_s),
)
except Exception as e:
logging.exception("Agent summary failed: %s", e)
answer = tr("ERR_SUMMARY_FAILED")
await update.message.reply_text(answer)
async def summary_day(update: Update, context: ContextTypes.DEFAULT_TYPE):
start_dt, end_dt = _period_bounds_yesterday()
await _summary_for_period(update, context, SUMMARY_DAY_LABEL, start_dt, end_dt)
async def summary_week(update: Update, context: ContextTypes.DEFAULT_TYPE):
start_dt, end_dt = _period_bounds_days_ending_yesterday(7)
await _summary_for_period(update, context, SUMMARY_WEEK_LABEL, start_dt, end_dt)
async def summary_month(update: Update, context: ContextTypes.DEFAULT_TYPE):
start_dt, end_dt = _period_bounds_days_ending_yesterday(30)
await _summary_for_period(update, context, SUMMARY_MONTH_LABEL, start_dt, end_dt)
async def _run_show_question(update: Update, question: str) -> None:
uid = update.message.from_user.id
now = datetime.now()
now_s = now.strftime("%Y-%m-%d %H:%M:%S")
extra_instructions = ""
if re.search(tr("EVENING_REGEX"), (question or "").lower()):
evening_start_hour = 18
evening_end_hour = 23
target = now.date()
if now.hour >= evening_end_hour:
target = (now + timedelta(days=1)).date()
start_dt = datetime(target.year, target.month, target.day, evening_start_hour, 0, 0)
end_dt = datetime(target.year, target.month, target.day, evening_end_hour, 59, 59)
extra_instructions = tr(
"SHOW_CONTEXT",
now=now_s,
start=start_dt.strftime("%Y-%m-%d %H:%M:%S"),
end=end_dt.strftime("%Y-%m-%d %H:%M:%S"),
)
try:
answer = await agent_manager.run(uid, mode="show", user_text=tr("SHOW_AGENT_INPUT", question=question, extra=extra_instructions))
except Exception as e:
logging.exception("Agent /show failed: %s", e)
answer = tr("ERR_SHOW_FAILED")
await update.message.reply_text(answer)
async def enter_chat(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not _is_allowed(update):
return
uid = update.message.from_user.id
user_modes[uid] = "chat"
await update.message.reply_text(tr("CHAT_ON"))
async def exit_chat(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not _is_allowed(update):
return
uid = update.message.from_user.id
user_modes[uid] = "diary"
agent_manager.reset_user(uid)
await update.message.reply_text(tr("CHAT_OFF"))
# ==========================
# TEXT HANDLER
# ==========================
async def handle_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not _is_allowed(update):
return
uid = update.message.from_user.id
text = update.message.text
mode = user_modes.get(uid, "diary")
# Reply-keyboard "buttons" come as plain text messages.
if text == BTN_HELP:
await help_text(update, context)
return
if text == BTN_DIARY:
await diary_mode(update, context)
return
if text == BTN_CHAT:
await enter_chat(update, context)
return
if text == BTN_LIST:
await list_diary(update, context)
return
if text == BTN_PAUSE:
await pause_diary(update, context)
return
if text == BTN_RESUME:
await resume_diary(update, context)
return
if text == BTN_SHOW:
context.user_data["after_show_mode"] = mode
user_modes[uid] = "show_wait"
await update.message.reply_text(tr("SHOW_ASK"))
return
if text == SUMMARY_DAY_LABEL:
await summary_day(update, context)
return
if text == SUMMARY_WEEK_LABEL:
await summary_week(update, context)
return
if text == SUMMARY_MONTH_LABEL:
await summary_month(update, context)
return
if mode == "show_wait":
question = (text or "").strip()
if not question:
await update.message.reply_text(tr("SHOW_ASK_TEXT"))
return
after_mode = context.user_data.get("after_show_mode") or "diary"
user_modes[uid] = after_mode if after_mode in ("diary", "chat", "paused") else "diary"
await _run_show_question(update, question)
return
if mode == "paused":
return
if mode == "diary":
date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
user_tags = extract_user_tags(text)
tags = sorted(set(user_tags))
with db_lock:
c.execute(
"INSERT INTO diary (user_id, date, text, photo_path) VALUES (?,?,?,?)",
(uid, date, text, None),
)
diary_id = int(c.lastrowid)
conn.commit()
save_tags(diary_id, tags)
# Let the agent add extra tags and store long-term memory if it makes sense.
try:
await agent_manager.run(
uid,
mode="diary_postprocess",
user_text=tr("DIARY_AGENT_POSTPROCESS", diary_id=diary_id, body=text),
)
except Exception as e:
logging.exception("Agent diary_postprocess failed: %s", e)
final_tags = get_diary_tags(diary_id)
tag_line = ", ".join(f"#{t}" for t in final_tags) if final_tags else tr("DASH")
await update.message.reply_text(tr("DIARY_SAVED", tags=tag_line))
else:
try:
answer = await agent_manager.run(uid, mode="chat", user_text=text)
except Exception as e:
logging.exception("Agent chat failed: %s", e)
answer = tr("ERR_CHAT_FAILED")
await update.message.reply_text(answer)
# ==========================
# PHOTO HANDLER
# ==========================
async def handle_photo(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not _is_allowed(update):
return
uid = update.message.from_user.id
if user_modes.get(uid, "diary") == "paused":
return
if user_modes.get(uid, "diary") != "diary":
await update.message.reply_text(tr("PHOTO_ONLY_IN_DIARY"))
return
photo = await update.message.photo[-1].get_file()
name = f"{PHOTO_DIR}/{uid}_{datetime.now().timestamp()}.jpg"
await photo.download_to_drive(name)
caption = (update.message.caption or "").strip()
description = tr("PHOTO_DEFAULT_DESC")
if caption:
description += f": {caption}"
with db_lock:
c.execute(
"INSERT INTO diary (user_id, date, text, photo_path) VALUES (?,?,?,?)",
(uid, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), description, name),
)
diary_id = int(c.lastrowid)
conn.commit()
# Agent распознаёт фото (vision), обновляет текст записи и ставит теги/память.
try:
await agent_manager.run(
uid,
mode="photo_postprocess",
user_text=tr("PHOTO_AGENT_POSTPROCESS", diary_id=diary_id, photo_path=name, body=description),
)
except Exception as e:
logging.exception("Agent photo_postprocess failed: %s", e)
final_tags = get_diary_tags(diary_id)
tag_line = ", ".join(f"#{t}" for t in final_tags) if final_tags else tr("DASH")
await update.message.reply_text(tr("PHOTO_SAVED", tags=tag_line))
# ==========================
# LIST DIARY
# ==========================
async def list_diary(update: Update, context: ContextTypes.DEFAULT_TYPE):
if not _is_allowed(update):
return
uid = update.message.from_user.id
page = 0
browse_offsets[uid] = page
text, keyboard = _render_diary_page(uid, page)
await update.message.reply_text(text, reply_markup=keyboard)
async def handle_diary_pagination(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
if not query:
return
if not _is_allowed(update):
return
await query.answer()
data = query.data or ""
# callback_data format: diary_page:<uid>:<page>
try:
_, uid_str, page_str = data.split(":", 2)
target_uid = int(uid_str)
page = int(page_str)
except Exception:
return
uid = update.effective_user.id if update.effective_user else None
if uid is None or uid != target_uid:
# Don't allow paging someone else's diary.
return
browse_offsets[uid] = page
text, keyboard = _render_diary_page(uid, page)
try:
await query.edit_message_text(text, reply_markup=keyboard)
except Exception:
# If message can't be edited (e.g., too old), just send a new one.
await query.message.reply_text(text, reply_markup=keyboard)
async def handle_diary_open(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
if not query:
return
if not _is_allowed(update):
return
await query.answer()
data = query.data or ""
# callback_data format: diary_open:<uid>:<diary_id>:<page>
try:
_, uid_str, diary_id_str, page_str = data.split(":", 3)
target_uid = int(uid_str)
diary_id = int(diary_id_str)
page = int(page_str)
except Exception:
return
uid = update.effective_user.id if update.effective_user else None
if uid is None or uid != target_uid:
return
with db_lock:
row = c.execute(
"SELECT id, date, text, photo_path FROM diary WHERE id=? AND user_id=?",
(diary_id, uid),
).fetchone()
if not row:
await query.message.reply_text(tr("DIARY_NOT_FOUND"))
return
_, d, t, photo_path = row
tags = get_diary_tags(diary_id)
tag_line = ", ".join(f"#{x}" for x in tags) if tags else tr("DASH")
full_text = (t or "").strip()
msg = tr(
"DIARY_OPEN_MSG",
date=d,