chats.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. import json
  2. import time
  3. import uuid
  4. from typing import Optional
  5. from open_webui.apps.webui.internal.db import Base, get_db
  6. from open_webui.apps.webui.models.tags import TagModel, Tag, Tags
  7. from pydantic import BaseModel, ConfigDict
  8. from sqlalchemy import BigInteger, Boolean, Column, String, Text, JSON
  9. from sqlalchemy import or_, func, select, and_, text
  10. from sqlalchemy.sql import exists
  11. ####################
  12. # Chat DB Schema
  13. ####################
  14. class Chat(Base):
  15. __tablename__ = "chat"
  16. id = Column(String, primary_key=True)
  17. user_id = Column(String)
  18. title = Column(Text)
  19. chat = Column(JSON)
  20. created_at = Column(BigInteger)
  21. updated_at = Column(BigInteger)
  22. share_id = Column(Text, unique=True, nullable=True)
  23. archived = Column(Boolean, default=False)
  24. pinned = Column(Boolean, default=False, nullable=True)
  25. meta = Column(JSON, server_default="{}")
  26. folder_id = Column(Text, nullable=True)
  27. class ChatModel(BaseModel):
  28. model_config = ConfigDict(from_attributes=True)
  29. id: str
  30. user_id: str
  31. title: str
  32. chat: dict
  33. created_at: int # timestamp in epoch
  34. updated_at: int # timestamp in epoch
  35. share_id: Optional[str] = None
  36. archived: bool = False
  37. pinned: Optional[bool] = False
  38. meta: dict = {}
  39. folder_id: Optional[str] = None
  40. ####################
  41. # Forms
  42. ####################
  43. class ChatForm(BaseModel):
  44. chat: dict
  45. class ChatTitleMessagesForm(BaseModel):
  46. title: str
  47. messages: list[dict]
  48. class ChatTitleForm(BaseModel):
  49. title: str
  50. class ChatResponse(BaseModel):
  51. id: str
  52. user_id: str
  53. title: str
  54. chat: dict
  55. updated_at: int # timestamp in epoch
  56. created_at: int # timestamp in epoch
  57. share_id: Optional[str] = None # id of the chat to be shared
  58. archived: bool
  59. pinned: Optional[bool] = False
  60. meta: dict = {}
  61. folder_id: Optional[str] = None
  62. class ChatTitleIdResponse(BaseModel):
  63. id: str
  64. title: str
  65. updated_at: int
  66. created_at: int
  67. class ChatTable:
  68. def insert_new_chat(self, user_id: str, form_data: ChatForm) -> Optional[ChatModel]:
  69. with get_db() as db:
  70. id = str(uuid.uuid4())
  71. chat = ChatModel(
  72. **{
  73. "id": id,
  74. "user_id": user_id,
  75. "title": (
  76. form_data.chat["title"]
  77. if "title" in form_data.chat
  78. else "New Chat"
  79. ),
  80. "chat": form_data.chat,
  81. "created_at": int(time.time()),
  82. "updated_at": int(time.time()),
  83. }
  84. )
  85. result = Chat(**chat.model_dump())
  86. db.add(result)
  87. db.commit()
  88. db.refresh(result)
  89. return ChatModel.model_validate(result) if result else None
  90. def update_chat_by_id(self, id: str, chat: dict) -> Optional[ChatModel]:
  91. try:
  92. with get_db() as db:
  93. chat_item = db.get(Chat, id)
  94. chat_item.chat = chat
  95. chat_item.title = chat["title"] if "title" in chat else "New Chat"
  96. chat_item.updated_at = int(time.time())
  97. db.commit()
  98. db.refresh(chat_item)
  99. return ChatModel.model_validate(chat_item)
  100. except Exception:
  101. return None
  102. def insert_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  103. with get_db() as db:
  104. # Get the existing chat to share
  105. chat = db.get(Chat, chat_id)
  106. # Check if the chat is already shared
  107. if chat.share_id:
  108. return self.get_chat_by_id_and_user_id(chat.share_id, "shared")
  109. # Create a new chat with the same data, but with a new ID
  110. shared_chat = ChatModel(
  111. **{
  112. "id": str(uuid.uuid4()),
  113. "user_id": f"shared-{chat_id}",
  114. "title": chat.title,
  115. "chat": chat.chat,
  116. "created_at": chat.created_at,
  117. "updated_at": int(time.time()),
  118. }
  119. )
  120. shared_result = Chat(**shared_chat.model_dump())
  121. db.add(shared_result)
  122. db.commit()
  123. db.refresh(shared_result)
  124. # Update the original chat with the share_id
  125. result = (
  126. db.query(Chat)
  127. .filter_by(id=chat_id)
  128. .update({"share_id": shared_chat.id})
  129. )
  130. db.commit()
  131. return shared_chat if (shared_result and result) else None
  132. def update_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
  133. try:
  134. with get_db() as db:
  135. print("update_shared_chat_by_id")
  136. chat = db.get(Chat, chat_id)
  137. print(chat)
  138. chat.title = chat.title
  139. chat.chat = chat.chat
  140. db.commit()
  141. db.refresh(chat)
  142. return self.get_chat_by_id(chat.share_id)
  143. except Exception:
  144. return None
  145. def delete_shared_chat_by_chat_id(self, chat_id: str) -> bool:
  146. try:
  147. with get_db() as db:
  148. db.query(Chat).filter_by(user_id=f"shared-{chat_id}").delete()
  149. db.commit()
  150. return True
  151. except Exception:
  152. return False
  153. def update_chat_share_id_by_id(
  154. self, id: str, share_id: Optional[str]
  155. ) -> Optional[ChatModel]:
  156. try:
  157. with get_db() as db:
  158. chat = db.get(Chat, id)
  159. chat.share_id = share_id
  160. db.commit()
  161. db.refresh(chat)
  162. return ChatModel.model_validate(chat)
  163. except Exception:
  164. return None
  165. def toggle_chat_pinned_by_id(self, id: str) -> Optional[ChatModel]:
  166. try:
  167. with get_db() as db:
  168. chat = db.get(Chat, id)
  169. chat.pinned = not chat.pinned
  170. chat.updated_at = int(time.time())
  171. db.commit()
  172. db.refresh(chat)
  173. return ChatModel.model_validate(chat)
  174. except Exception:
  175. return None
  176. def toggle_chat_archive_by_id(self, id: str) -> Optional[ChatModel]:
  177. try:
  178. with get_db() as db:
  179. chat = db.get(Chat, id)
  180. chat.archived = not chat.archived
  181. chat.updated_at = int(time.time())
  182. db.commit()
  183. db.refresh(chat)
  184. return ChatModel.model_validate(chat)
  185. except Exception:
  186. return None
  187. def archive_all_chats_by_user_id(self, user_id: str) -> bool:
  188. try:
  189. with get_db() as db:
  190. db.query(Chat).filter_by(user_id=user_id).update({"archived": True})
  191. db.commit()
  192. return True
  193. except Exception:
  194. return False
  195. def get_archived_chat_list_by_user_id(
  196. self, user_id: str, skip: int = 0, limit: int = 50
  197. ) -> list[ChatModel]:
  198. with get_db() as db:
  199. all_chats = (
  200. db.query(Chat)
  201. .filter_by(user_id=user_id, archived=True)
  202. .order_by(Chat.updated_at.desc())
  203. # .limit(limit).offset(skip)
  204. .all()
  205. )
  206. return [ChatModel.model_validate(chat) for chat in all_chats]
  207. def get_chat_list_by_user_id(
  208. self,
  209. user_id: str,
  210. include_archived: bool = False,
  211. skip: int = 0,
  212. limit: int = 50,
  213. ) -> list[ChatModel]:
  214. with get_db() as db:
  215. query = db.query(Chat).filter_by(user_id=user_id).filter_by(folder_id=None)
  216. if not include_archived:
  217. query = query.filter_by(archived=False)
  218. query = query.order_by(Chat.updated_at.desc())
  219. if skip:
  220. query = query.offset(skip)
  221. if limit:
  222. query = query.limit(limit)
  223. all_chats = query.all()
  224. return [ChatModel.model_validate(chat) for chat in all_chats]
  225. def get_chat_title_id_list_by_user_id(
  226. self,
  227. user_id: str,
  228. include_archived: bool = False,
  229. skip: Optional[int] = None,
  230. limit: Optional[int] = None,
  231. ) -> list[ChatTitleIdResponse]:
  232. with get_db() as db:
  233. query = db.query(Chat).filter_by(user_id=user_id).filter_by(folder_id=None)
  234. query = query.filter(or_(Chat.pinned == False, Chat.pinned == None))
  235. if not include_archived:
  236. query = query.filter_by(archived=False)
  237. query = query.order_by(Chat.updated_at.desc()).with_entities(
  238. Chat.id, Chat.title, Chat.updated_at, Chat.created_at
  239. )
  240. if skip:
  241. query = query.offset(skip)
  242. if limit:
  243. query = query.limit(limit)
  244. all_chats = query.all()
  245. # result has to be destrctured from sqlalchemy `row` and mapped to a dict since the `ChatModel`is not the returned dataclass.
  246. return [
  247. ChatTitleIdResponse.model_validate(
  248. {
  249. "id": chat[0],
  250. "title": chat[1],
  251. "updated_at": chat[2],
  252. "created_at": chat[3],
  253. }
  254. )
  255. for chat in all_chats
  256. ]
  257. def get_chat_list_by_chat_ids(
  258. self, chat_ids: list[str], skip: int = 0, limit: int = 50
  259. ) -> list[ChatModel]:
  260. with get_db() as db:
  261. all_chats = (
  262. db.query(Chat)
  263. .filter(Chat.id.in_(chat_ids))
  264. .filter_by(archived=False)
  265. .order_by(Chat.updated_at.desc())
  266. .all()
  267. )
  268. return [ChatModel.model_validate(chat) for chat in all_chats]
  269. def get_chat_by_id(self, id: str) -> Optional[ChatModel]:
  270. try:
  271. with get_db() as db:
  272. chat = db.get(Chat, id)
  273. return ChatModel.model_validate(chat)
  274. except Exception:
  275. return None
  276. def get_chat_by_share_id(self, id: str) -> Optional[ChatModel]:
  277. try:
  278. with get_db() as db:
  279. chat = db.query(Chat).filter_by(share_id=id).first()
  280. if chat:
  281. return self.get_chat_by_id(id)
  282. else:
  283. return None
  284. except Exception:
  285. return None
  286. def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]:
  287. try:
  288. with get_db() as db:
  289. chat = db.query(Chat).filter_by(id=id, user_id=user_id).first()
  290. return ChatModel.model_validate(chat)
  291. except Exception:
  292. return None
  293. def get_chats(self, skip: int = 0, limit: int = 50) -> list[ChatModel]:
  294. with get_db() as db:
  295. all_chats = (
  296. db.query(Chat)
  297. # .limit(limit).offset(skip)
  298. .order_by(Chat.updated_at.desc())
  299. )
  300. return [ChatModel.model_validate(chat) for chat in all_chats]
  301. def get_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  302. with get_db() as db:
  303. all_chats = (
  304. db.query(Chat)
  305. .filter_by(user_id=user_id)
  306. .order_by(Chat.updated_at.desc())
  307. )
  308. return [ChatModel.model_validate(chat) for chat in all_chats]
  309. def get_pinned_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  310. with get_db() as db:
  311. all_chats = (
  312. db.query(Chat)
  313. .filter_by(user_id=user_id, pinned=True, archived=False)
  314. .order_by(Chat.updated_at.desc())
  315. )
  316. return [ChatModel.model_validate(chat) for chat in all_chats]
  317. def get_archived_chats_by_user_id(self, user_id: str) -> list[ChatModel]:
  318. with get_db() as db:
  319. all_chats = (
  320. db.query(Chat)
  321. .filter_by(user_id=user_id, archived=True)
  322. .order_by(Chat.updated_at.desc())
  323. )
  324. return [ChatModel.model_validate(chat) for chat in all_chats]
  325. def get_chats_by_user_id_and_search_text(
  326. self,
  327. user_id: str,
  328. search_text: str,
  329. include_archived: bool = False,
  330. skip: int = 0,
  331. limit: int = 60,
  332. ) -> list[ChatModel]:
  333. """
  334. Filters chats based on a search query using Python, allowing pagination using skip and limit.
  335. """
  336. search_text = search_text.lower().strip()
  337. if not search_text:
  338. return self.get_chat_list_by_user_id(user_id, include_archived, skip, limit)
  339. search_text_words = search_text.split(" ")
  340. # search_text might contain 'tag:tag_name' format so we need to extract the tag_name, split the search_text and remove the tags
  341. tag_ids = [
  342. word.replace("tag:", "").replace(" ", "_").lower()
  343. for word in search_text_words
  344. if word.startswith("tag:")
  345. ]
  346. search_text_words = [
  347. word for word in search_text_words if not word.startswith("tag:")
  348. ]
  349. search_text = " ".join(search_text_words)
  350. with get_db() as db:
  351. query = db.query(Chat).filter(Chat.user_id == user_id)
  352. if not include_archived:
  353. query = query.filter(Chat.archived == False)
  354. query = query.order_by(Chat.updated_at.desc())
  355. # Check if the database dialect is either 'sqlite' or 'postgresql'
  356. dialect_name = db.bind.dialect.name
  357. if dialect_name == "sqlite":
  358. # SQLite case: using JSON1 extension for JSON searching
  359. query = query.filter(
  360. (
  361. Chat.title.ilike(
  362. f"%{search_text}%"
  363. ) # Case-insensitive search in title
  364. | text(
  365. """
  366. EXISTS (
  367. SELECT 1
  368. FROM json_each(Chat.chat, '$.messages') AS message
  369. WHERE LOWER(message.value->>'content') LIKE '%' || :search_text || '%'
  370. )
  371. """
  372. )
  373. ).params(search_text=search_text)
  374. )
  375. # Check if there are any tags to filter, it should have all the tags
  376. if tag_ids:
  377. query = query.filter(
  378. and_(
  379. *[
  380. text(
  381. f"""
  382. EXISTS (
  383. SELECT 1
  384. FROM json_each(Chat.meta, '$.tags') AS tag
  385. WHERE tag.value = :tag_id_{tag_idx}
  386. )
  387. """
  388. ).params(**{f"tag_id_{tag_idx}": tag_id})
  389. for tag_idx, tag_id in enumerate(tag_ids)
  390. ]
  391. )
  392. )
  393. elif dialect_name == "postgresql":
  394. # PostgreSQL relies on proper JSON query for search
  395. query = query.filter(
  396. (
  397. Chat.title.ilike(
  398. f"%{search_text}%"
  399. ) # Case-insensitive search in title
  400. | text(
  401. """
  402. EXISTS (
  403. SELECT 1
  404. FROM json_array_elements(Chat.chat->'messages') AS message
  405. WHERE LOWER(message->>'content') LIKE '%' || :search_text || '%'
  406. )
  407. """
  408. )
  409. ).params(search_text=search_text)
  410. )
  411. # Check if there are any tags to filter, it should have all the tags
  412. if tag_ids:
  413. query = query.filter(
  414. and_(
  415. *[
  416. text(
  417. f"""
  418. EXISTS (
  419. SELECT 1
  420. FROM json_array_elements_text(Chat.meta->'tags') AS tag
  421. WHERE tag = :tag_id_{tag_idx}
  422. )
  423. """
  424. ).params(**{f"tag_id_{tag_idx}": tag_id})
  425. for tag_idx, tag_id in enumerate(tag_ids)
  426. ]
  427. )
  428. )
  429. else:
  430. raise NotImplementedError(
  431. f"Unsupported dialect: {db.bind.dialect.name}"
  432. )
  433. # Perform pagination at the SQL level
  434. all_chats = query.offset(skip).limit(limit).all()
  435. print(len(all_chats))
  436. # Validate and return chats
  437. return [ChatModel.model_validate(chat) for chat in all_chats]
  438. def get_chats_by_folder_id_and_user_id(
  439. self, folder_id: str, user_id: str
  440. ) -> list[ChatModel]:
  441. with get_db() as db:
  442. all_chats = (
  443. db.query(Chat).filter_by(folder_id=folder_id, user_id=user_id).all()
  444. )
  445. return [ChatModel.model_validate(chat) for chat in all_chats]
  446. def update_chat_folder_id_by_id_and_user_id(
  447. self, id: str, user_id: str, folder_id: str
  448. ) -> Optional[ChatModel]:
  449. try:
  450. with get_db() as db:
  451. chat = db.get(Chat, id)
  452. chat.folder_id = folder_id
  453. chat.updated_at = int(time.time())
  454. db.commit()
  455. db.refresh(chat)
  456. return ChatModel.model_validate(chat)
  457. except Exception:
  458. return None
  459. def get_chat_tags_by_id_and_user_id(self, id: str, user_id: str) -> list[TagModel]:
  460. with get_db() as db:
  461. chat = db.get(Chat, id)
  462. tags = chat.meta.get("tags", [])
  463. return [Tags.get_tag_by_name_and_user_id(tag, user_id) for tag in tags]
  464. def get_chat_list_by_user_id_and_tag_name(
  465. self, user_id: str, tag_name: str, skip: int = 0, limit: int = 50
  466. ) -> list[ChatModel]:
  467. with get_db() as db:
  468. query = db.query(Chat).filter_by(user_id=user_id)
  469. tag_id = tag_name.replace(" ", "_").lower()
  470. print(db.bind.dialect.name)
  471. if db.bind.dialect.name == "sqlite":
  472. # SQLite JSON1 querying for tags within the meta JSON field
  473. query = query.filter(
  474. text(
  475. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  476. )
  477. ).params(tag_id=tag_id)
  478. elif db.bind.dialect.name == "postgresql":
  479. # PostgreSQL JSON query for tags within the meta JSON field (for `json` type)
  480. query = query.filter(
  481. text(
  482. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  483. )
  484. ).params(tag_id=tag_id)
  485. else:
  486. raise NotImplementedError(
  487. f"Unsupported dialect: {db.bind.dialect.name}"
  488. )
  489. all_chats = query.all()
  490. print("all_chats", all_chats)
  491. return [ChatModel.model_validate(chat) for chat in all_chats]
  492. def add_chat_tag_by_id_and_user_id_and_tag_name(
  493. self, id: str, user_id: str, tag_name: str
  494. ) -> Optional[ChatModel]:
  495. tag = Tags.get_tag_by_name_and_user_id(tag_name, user_id)
  496. if tag is None:
  497. tag = Tags.insert_new_tag(tag_name, user_id)
  498. try:
  499. with get_db() as db:
  500. chat = db.get(Chat, id)
  501. tag_id = tag.id
  502. if tag_id not in chat.meta.get("tags", []):
  503. chat.meta = {
  504. **chat.meta,
  505. "tags": list(set(chat.meta.get("tags", []) + [tag_id])),
  506. }
  507. db.commit()
  508. db.refresh(chat)
  509. return ChatModel.model_validate(chat)
  510. except Exception:
  511. return None
  512. def count_chats_by_tag_name_and_user_id(self, tag_name: str, user_id: str) -> int:
  513. with get_db() as db: # Assuming `get_db()` returns a session object
  514. query = db.query(Chat).filter_by(user_id=user_id, archived=False)
  515. # Normalize the tag_name for consistency
  516. tag_id = tag_name.replace(" ", "_").lower()
  517. if db.bind.dialect.name == "sqlite":
  518. # SQLite JSON1 support for querying the tags inside the `meta` JSON field
  519. query = query.filter(
  520. text(
  521. f"EXISTS (SELECT 1 FROM json_each(Chat.meta, '$.tags') WHERE json_each.value = :tag_id)"
  522. )
  523. ).params(tag_id=tag_id)
  524. elif db.bind.dialect.name == "postgresql":
  525. # PostgreSQL JSONB support for querying the tags inside the `meta` JSON field
  526. query = query.filter(
  527. text(
  528. "EXISTS (SELECT 1 FROM json_array_elements_text(Chat.meta->'tags') elem WHERE elem = :tag_id)"
  529. )
  530. ).params(tag_id=tag_id)
  531. else:
  532. raise NotImplementedError(
  533. f"Unsupported dialect: {db.bind.dialect.name}"
  534. )
  535. # Get the count of matching records
  536. count = query.count()
  537. # Debugging output for inspection
  538. print(f"Count of chats for tag '{tag_name}':", count)
  539. return count
  540. def delete_tag_by_id_and_user_id_and_tag_name(
  541. self, id: str, user_id: str, tag_name: str
  542. ) -> bool:
  543. try:
  544. with get_db() as db:
  545. chat = db.get(Chat, id)
  546. tags = chat.meta.get("tags", [])
  547. tag_id = tag_name.replace(" ", "_").lower()
  548. tags = [tag for tag in tags if tag != tag_id]
  549. chat.meta = {
  550. **chat.meta,
  551. "tags": list(set(tags)),
  552. }
  553. db.commit()
  554. return True
  555. except Exception:
  556. return False
  557. def delete_all_tags_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  558. try:
  559. with get_db() as db:
  560. chat = db.get(Chat, id)
  561. chat.meta = {
  562. **chat.meta,
  563. "tags": [],
  564. }
  565. db.commit()
  566. return True
  567. except Exception:
  568. return False
  569. def delete_chat_by_id(self, id: str) -> bool:
  570. try:
  571. with get_db() as db:
  572. db.query(Chat).filter_by(id=id).delete()
  573. db.commit()
  574. return True and self.delete_shared_chat_by_chat_id(id)
  575. except Exception:
  576. return False
  577. def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool:
  578. try:
  579. with get_db() as db:
  580. db.query(Chat).filter_by(id=id, user_id=user_id).delete()
  581. db.commit()
  582. return True and self.delete_shared_chat_by_chat_id(id)
  583. except Exception:
  584. return False
  585. def delete_chats_by_user_id(self, user_id: str) -> bool:
  586. try:
  587. with get_db() as db:
  588. self.delete_shared_chats_by_user_id(user_id)
  589. db.query(Chat).filter_by(user_id=user_id).delete()
  590. db.commit()
  591. return True
  592. except Exception:
  593. return False
  594. def delete_shared_chats_by_user_id(self, user_id: str) -> bool:
  595. try:
  596. with get_db() as db:
  597. chats_by_user = db.query(Chat).filter_by(user_id=user_id).all()
  598. shared_chat_ids = [f"shared-{chat.id}" for chat in chats_by_user]
  599. db.query(Chat).filter(Chat.user_id.in_(shared_chat_ids)).delete()
  600. db.commit()
  601. return True
  602. except Exception:
  603. return False
  604. Chats = ChatTable()