-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathchat_service.py
More file actions
1901 lines (1676 loc) · 70.5 KB
/
Copy pathchat_service.py
File metadata and controls
1901 lines (1676 loc) · 70.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
from __future__ import annotations
import asyncio
import json
import os
import re
import uuid
from collections.abc import AsyncIterator
from copy import deepcopy
from dataclasses import dataclass, field
from pathlib import Path, PurePosixPath
from typing import Any
from astrbot.core import logger, sp
from astrbot.core.agent.message import get_checkpoint_id, is_checkpoint_message
from astrbot.core.core_lifecycle import AstrBotCoreLifecycle
from astrbot.core.db import BaseDatabase
from astrbot.core.platform.message_type import MessageType
from astrbot.core.platform.sources.webchat.message_parts_helper import (
build_webchat_message_parts,
create_attachment_part_from_existing_file,
strip_message_parts_path_fields,
webchat_message_parts_have_content,
)
from astrbot.core.platform.sources.webchat.request_flags import (
resolve_webchat_request_flags,
)
from astrbot.core.platform.sources.webchat.webchat_queue_mgr import webchat_queue_mgr
from astrbot.core.utils.active_event_registry import active_event_registry
from astrbot.core.utils.astrbot_path import get_astrbot_data_path
from astrbot.core.utils.datetime_utils import generate_timestamp_id, to_utc_isoformat
from astrbot.core.utils.media_utils import (
MEDIA_MIME_EXTENSIONS,
detect_image_mime_type_async,
)
SSE_HEARTBEAT = ": heartbeat\n\n"
CHAT_RUN_SUBSCRIBER_QUEUE_SIZE = 256
WEBCHAT_IMAGE_MIME_TYPES = {
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".webp": "image/webp",
}
def sanitize_upload_filename(filename: str | None) -> str:
if not filename:
return generate_timestamp_id()
normalized = filename.replace("\\", "/")
name = PurePosixPath(normalized).name.replace("\x00", "").strip()
if name in ("", ".", ".."):
return generate_timestamp_id()
return name
def normalize_reasoning_message_parts(
message_parts: list[dict] | None,
reasoning: str = "",
) -> list[dict]:
parts: list[dict] = []
for part in message_parts or []:
if not isinstance(part, dict):
continue
copied = dict(part)
if copied.get("type") == "reasoning":
copied = {"type": "think", "think": copied.get("text", "")}
parts.append(copied)
if reasoning and not any(part.get("type") == "think" for part in parts):
parts.insert(0, {"type": "think", "think": reasoning})
return parts
def extract_reasoning_from_message_parts(message_parts: list[dict]) -> str:
reasoning_parts: list[str] = []
for part in message_parts:
if part.get("type") != "think":
continue
think = part.get("think")
if isinstance(think, str) and think:
reasoning_parts.append(think)
return "".join(reasoning_parts)
def collect_plain_text_from_message_parts(message_parts: list[dict]) -> str:
text_parts: list[str] = []
for part in message_parts:
if part.get("type") != "plain":
continue
text = part.get("text")
if isinstance(text, str) and text:
text_parts.append(text)
return "".join(text_parts)
def build_bot_history_content(
message_parts: list[dict],
*,
agent_stats: dict | None = None,
refs: dict | None = None,
include_reasoning_field: bool = True,
) -> dict[str, Any]:
normalized_parts = normalize_reasoning_message_parts(message_parts)
content: dict[str, Any] = {"type": "bot", "message": normalized_parts}
reasoning = extract_reasoning_from_message_parts(normalized_parts)
if reasoning and include_reasoning_field:
content["reasoning"] = reasoning
if agent_stats:
content["agent_stats"] = agent_stats
if refs:
content["refs"] = refs
return content
class BotMessageAccumulator:
def __init__(self) -> None:
self.parts: list[dict] = []
self.pending_text = ""
self.pending_tool_calls: dict[str, dict] = {}
def has_content(self) -> bool:
return bool(self.parts or self.pending_text or self.pending_tool_calls)
def add_plain(
self,
result_text: str,
*,
chain_type: str | None,
streaming: bool,
) -> None:
if chain_type == "tool_call":
self._flush_pending_text()
self._store_tool_call(result_text)
return
if chain_type == "tool_call_result":
self._flush_pending_text()
self._store_tool_call_result(result_text)
return
if chain_type == "reasoning":
self._flush_pending_text()
self._append_think_part(result_text)
return
if streaming:
self.pending_text += result_text
else:
self.pending_text = result_text
def add_attachment(self, part: dict | None) -> None:
if not part:
return
self._flush_pending_text()
self.parts.append(part)
def build_message_parts(
self, *, include_pending_tool_calls: bool = False
) -> list[dict]:
self._flush_pending_text()
if include_pending_tool_calls and self.pending_tool_calls:
for tool_call in self.pending_tool_calls.values():
self.parts.append({"type": "tool_call", "tool_calls": [tool_call]})
self.pending_tool_calls = {}
return self.parts
def plain_text(self) -> str:
return collect_plain_text_from_message_parts(self.build_message_parts())
def reasoning_text(self) -> str:
return extract_reasoning_from_message_parts(self.build_message_parts())
def _flush_pending_text(self) -> None:
if not self.pending_text:
return
if self.parts and self.parts[-1].get("type") == "plain":
last_text = self.parts[-1].get("text")
self.parts[-1]["text"] = f"{last_text or ''}{self.pending_text}"
else:
self.parts.append({"type": "plain", "text": self.pending_text})
self.pending_text = ""
def _append_think_part(self, text: str) -> None:
if not text:
return
if self.parts and self.parts[-1].get("type") == "think":
last_text = self.parts[-1].get("think")
self.parts[-1]["think"] = f"{last_text or ''}{text}"
else:
self.parts.append({"type": "think", "think": text})
def _store_tool_call(self, result_text: str) -> None:
tool_call = self._parse_json_object(result_text)
if not tool_call:
return
tool_call_id = str(tool_call.get("id") or "")
if not tool_call_id:
return
self.pending_tool_calls[tool_call_id] = tool_call
def _store_tool_call_result(self, result_text: str) -> None:
tool_result = self._parse_json_object(result_text)
if not tool_result:
return
tool_call_id = str(tool_result.get("id") or "")
if not tool_call_id:
return
tool_call = self.pending_tool_calls.pop(tool_call_id, None) or {
"id": tool_call_id
}
tool_call["result"] = tool_result.get("result")
tool_call["finished_ts"] = tool_result.get("ts")
self.parts.append({"type": "tool_call", "tool_calls": [tool_call]})
@staticmethod
def _parse_json_object(raw_text: str) -> dict | None:
try:
parsed = json.loads(raw_text)
except json.JSONDecodeError:
return None
return parsed if isinstance(parsed, dict) else None
def extract_web_search_refs(accumulated_text: str, accumulated_parts: list) -> dict:
supported = [
"web_search_baidu",
"web_search_tavily",
"web_search_bocha",
"web_search_brave",
]
web_search_results = {}
tool_call_parts = [
p
for p in accumulated_parts
if p.get("type") == "tool_call" and p.get("tool_calls")
]
for part in tool_call_parts:
for tool_call in part["tool_calls"]:
if tool_call.get("name") not in supported or not tool_call.get("result"):
continue
try:
result_data = json.loads(tool_call["result"])
for item in result_data.get("results", []):
if idx := item.get("index"):
web_search_results[idx] = {
"url": item.get("url"),
"title": item.get("title"),
"snippet": item.get("snippet"),
}
except (json.JSONDecodeError, KeyError):
pass
if not web_search_results:
return {}
ref_indices = {m.strip() for m in re.findall(r"<ref>(.*?)</ref>", accumulated_text)}
used_refs = []
for ref_index in ref_indices:
if ref_index not in web_search_results:
continue
payload = {"index": ref_index, **web_search_results[ref_index]}
if favicon := sp.temporary_cache.get("_ws_favicon", {}).get(payload["url"]):
payload["favicon"] = favicon
used_refs.append(payload)
return {"used": used_refs} if used_refs else {}
def parse_web_search_sources(result_text: str) -> dict:
"""Parse a web_search_sources back-queue payload into a refs dict.
The payload is ``{"sources": [...]}``; the refs shape mirrors
``extract_web_search_refs`` so the frontend renders native search
sources as the same clickable cards.
"""
try:
parsed = json.loads(result_text)
sources = parsed.get("sources", []) if isinstance(parsed, dict) else []
return {"used": sources} if isinstance(sources, list) else {}
except (TypeError, json.JSONDecodeError):
return {}
def sanitize_message_content(content: dict) -> dict:
if not isinstance(content, dict):
raise ValueError("Missing key: content")
normalized = deepcopy(content)
message_type = normalized.get("type")
if message_type not in {"user", "bot"}:
raise ValueError("Invalid key: content.type")
message_parts = normalized.get("message")
if not isinstance(message_parts, list):
raise ValueError("Missing key: content.message")
normalized["message"] = strip_message_parts_path_fields(message_parts)
return normalized
def extract_platform_message_text(content: dict | None) -> str:
if not isinstance(content, dict):
return ""
message_parts = content.get("message")
if not isinstance(message_parts, list):
return ""
texts: list[str] = []
for part in message_parts:
if isinstance(part, dict) and part.get("type") == "plain":
text = part.get("text")
if isinstance(text, str):
texts.append(text)
return "".join(texts)
def build_webchat_unified_msg_origin(session) -> str:
message_type = (
MessageType.GROUP_MESSAGE.value
if session.is_group
else MessageType.FRIEND_MESSAGE.value
)
return (
f"{session.platform_id}:{message_type}:"
f"{session.platform_id}!{session.creator}!{session.session_id}"
)
def build_thread_unified_msg_origin(creator: str, thread_id: str) -> str:
return f"webchat:{MessageType.FRIEND_MESSAGE.value}:webchat!{creator}!{thread_id}"
def serialize_thread(thread) -> dict:
from astrbot.core.utils.datetime_utils import to_utc_isoformat
return {
"thread_id": thread.thread_id,
"parent_session_id": thread.parent_session_id,
"parent_message_id": thread.parent_message_id,
"base_checkpoint_id": thread.base_checkpoint_id,
"selected_text": thread.selected_text,
"created_at": to_utc_isoformat(thread.created_at),
"updated_at": to_utc_isoformat(thread.updated_at),
}
def serialize_history_entry(history) -> dict:
"""Serialize a PlatformMessageHistory record with UTC-aware timestamps.
Args:
history: A PlatformMessageHistory instance. Must not be None.
Returns:
Dict with all model fields plus created_at/updated_at serialized as
UTC-aware ISO strings (e.g. ``2026-07-06T04:00:00+00:00``).
"""
return {
**history.model_dump(),
"created_at": to_utc_isoformat(history.created_at),
"updated_at": to_utc_isoformat(history.updated_at),
}
def find_checkpoint_index(history: list[dict], checkpoint_id: str) -> int | None:
for index, message in enumerate(history):
if get_checkpoint_id(message) == checkpoint_id:
return index
return None
def find_turn_range(history: list[dict], checkpoint_id: str) -> tuple[int, int] | None:
checkpoint_index = find_checkpoint_index(history, checkpoint_id)
if checkpoint_index is None:
return None
start = 0
for index in range(checkpoint_index - 1, -1, -1):
if is_checkpoint_message(history[index]):
start = index + 1
break
return start, checkpoint_index
def is_latest_checkpoint(history: list[dict], checkpoint_id: str) -> bool:
for message in reversed(history):
current_checkpoint_id = get_checkpoint_id(message)
if current_checkpoint_id:
return current_checkpoint_id == checkpoint_id
return False
def replace_user_conversation_content(original_content, edited_text: str):
if isinstance(original_content, str):
return edited_text
if not isinstance(original_content, list):
return edited_text
result: list[dict] = []
inserted_text = False
for part in original_content:
if not isinstance(part, dict):
result.append(part)
continue
if part.get("type") != "text":
result.append(part)
continue
text = part.get("text")
if isinstance(text, str) and text.startswith("<system_reminder>"):
result.append(part)
continue
if not inserted_text and edited_text:
result.append({"type": "text", "text": edited_text})
inserted_text = True
if not inserted_text and edited_text:
result.insert(0, {"type": "text", "text": edited_text})
return result
def replace_assistant_conversation_content(
original_content,
edited_text: str,
reasoning: str,
):
if isinstance(original_content, str):
return edited_text
if not isinstance(original_content, list):
return [{"type": "text", "text": edited_text}] if edited_text else []
result: list[dict] = []
inserted_text = False
inserted_think = False
for part in original_content:
if not isinstance(part, dict):
result.append(part)
continue
if part.get("type") == "text":
if not inserted_text and edited_text:
result.append({"type": "text", "text": edited_text})
inserted_text = True
continue
if part.get("type") == "think":
if not inserted_think and reasoning:
result.append({"type": "think", "think": reasoning})
inserted_think = True
continue
result.append(part)
if reasoning and not inserted_think:
result.insert(0, {"type": "think", "think": reasoning})
if edited_text and not inserted_text:
result.append({"type": "text", "text": edited_text})
return result
def find_turn_user_index(history: list[dict], start: int, end: int) -> int | None:
for index in range(start, end):
message = history[index]
if isinstance(message, dict) and message.get("role") == "user":
return index
return None
def find_turn_final_assistant_index(
history: list[dict], start: int, end: int
) -> int | None:
for index in range(end - 1, start - 1, -1):
message = history[index]
if not isinstance(message, dict) or message.get("role") != "assistant":
continue
if message.get("tool_calls") and not message.get("content"):
continue
return index
return None
def extract_attachment_ids(history_list) -> list[str]:
attachment_ids = []
for history in history_list:
content = history.content
if not content or "message" not in content:
continue
message_parts = content.get("message", [])
for part in message_parts:
if isinstance(part, dict) and "attachment_id" in part:
attachment_ids.append(part["attachment_id"])
return attachment_ids
class ChatServiceError(Exception):
pass
@dataclass(slots=True)
class ChatRunState:
"""State owned by a WebChat generation independently of its subscribers."""
run_id: str
username: str
session_id: str
llm_checkpoint_id: str
platform_history_id: str
back_queue: asyncio.Queue
subscribers: set[asyncio.Queue] = field(default_factory=set)
message_parts: list[dict] = field(default_factory=list)
agent_stats: dict = field(default_factory=dict)
refs: dict = field(default_factory=dict)
revision: int = 0
status: str = "running"
task: asyncio.Task[None] | None = None
class ChatService:
def __init__(
self,
db: BaseDatabase,
core_lifecycle: AstrBotCoreLifecycle,
) -> None:
self.db = db
self.core_lifecycle = core_lifecycle
self.attachments_dir = os.path.join(get_astrbot_data_path(), "attachments")
self.webchat_img_dir = os.path.join(get_astrbot_data_path(), "webchat", "imgs")
os.makedirs(self.attachments_dir, exist_ok=True)
self.conv_mgr = core_lifecycle.conversation_manager
self.platform_history_mgr = core_lifecycle.platform_message_history_manager
self.umop_config_router = core_lifecycle.umop_config_router
self.running_convs: dict[str, bool] = {}
self.chat_runs: dict[str, ChatRunState] = {}
self.chat_runs_by_session: dict[str, set[str]] = {}
async def build_user_message_parts(self, message: str | list) -> list[dict]:
return await build_webchat_message_parts(
message,
get_attachment_by_id=self.db.get_attachment_by_id,
strict=False,
)
async def create_attachment_from_file(
self, filename: str, attach_type: str, display_name: str | None = None
) -> dict | None:
return await create_attachment_part_from_existing_file(
filename,
attach_type=attach_type,
insert_attachment=self.db.insert_attachment,
attachments_dir=self.attachments_dir,
fallback_dirs=[self.webchat_img_dir],
display_name=display_name,
)
async def resolve_webchat_file(
self, filename: str | None
) -> tuple[str, str | None]:
if not filename:
raise ChatServiceError("Missing key: filename")
safe_name = os.path.basename(filename)
attachments_dir = Path(self.attachments_dir).resolve(strict=False)
file_path = (attachments_dir / safe_name).resolve(strict=False)
file_root = attachments_dir
if not file_path.exists():
webchat_img_dir = Path(self.webchat_img_dir).resolve(strict=False)
webchat_file_path = (webchat_img_dir / safe_name).resolve(strict=False)
if webchat_file_path.exists():
file_path = webchat_file_path
file_root = webchat_img_dir
if not file_path.is_relative_to(file_root):
raise ChatServiceError("Invalid file path")
if not file_path.exists():
raise ChatServiceError("File access error")
filename_ext = file_path.suffix.lower()
if filename_ext == ".wav":
return str(file_path), "audio/wav"
if filename_ext in WEBCHAT_IMAGE_MIME_TYPES:
return str(file_path), WEBCHAT_IMAGE_MIME_TYPES[filename_ext]
return str(file_path), None
async def resolve_webchat_file_from_dashboard_query(
self,
filename: str | None,
) -> tuple[str, str | None]:
return await self.resolve_webchat_file(filename)
async def resolve_attachment_file(
self,
attachment_id: str | None,
) -> tuple[str, str | None]:
if not attachment_id:
raise ChatServiceError("Missing key: attachment_id")
attachment = await self.db.get_attachment_by_id(attachment_id)
if not attachment:
raise ChatServiceError("Attachment not found")
file_path = Path(attachment.path).resolve(strict=False)
if not file_path.exists():
raise ChatServiceError("File access error")
return str(file_path), attachment.mime_type
async def resolve_attachment_file_from_dashboard_query(
self,
attachment_id: str | None,
) -> tuple[str, str | None]:
return await self.resolve_attachment_file(attachment_id)
async def save_uploaded_file(self, file) -> dict:
filename = sanitize_upload_filename(file.filename)
content_type = file.content_type or "application/octet-stream"
if content_type.startswith("image"):
attach_type = "image"
elif content_type.startswith("audio"):
attach_type = "record"
elif content_type.startswith("video"):
attach_type = "video"
else:
attach_type = "file"
attachments_dir = Path(self.attachments_dir).resolve(strict=False)
file_path = (attachments_dir / filename).resolve(strict=False)
if not file_path.is_relative_to(attachments_dir):
raise ChatServiceError("Invalid filename")
await file.save(str(file_path))
if attach_type == "image":
detected_mime_type = await detect_image_mime_type_async(
file_path,
default_mime_type=None,
)
if detected_mime_type:
content_type = detected_mime_type
detected_suffix = MEDIA_MIME_EXTENSIONS.get(detected_mime_type)
if detected_suffix and file_path.suffix.lower() != detected_suffix:
target_path = file_path.with_suffix(detected_suffix)
if target_path.exists():
target_path = (
attachments_dir
/ f"{generate_timestamp_id()}{detected_suffix}"
)
await asyncio.to_thread(file_path.rename, target_path)
file_path = target_path
attachment = await self.db.insert_attachment(
path=str(file_path),
type=attach_type,
mime_type=content_type,
)
if not attachment:
raise ChatServiceError("Failed to create attachment")
return {
"attachment_id": attachment.attachment_id,
"filename": os.path.basename(attachment.path),
"type": attach_type,
}
async def save_uploaded_file_from_dashboard_files(self, files) -> dict:
if "file" not in files:
raise ChatServiceError("Missing key: file")
return await self.save_uploaded_file(files["file"])
async def delete_threads_by_ids(self, thread_ids: list[str], creator: str) -> None:
for thread_id in thread_ids:
unified_msg_origin = build_thread_unified_msg_origin(creator, thread_id)
active_event_registry.request_agent_stop_all(unified_msg_origin)
tasks = []
for run_id in list(self.chat_runs_by_session.get(thread_id, set())):
run = self.chat_runs.get(run_id)
if run and run.task and not run.task.done():
run.task.cancel()
tasks.append(run.task)
if tasks:
await asyncio.gather(*tasks, return_exceptions=True)
await self.conv_mgr.delete_conversations_by_user_id(unified_msg_origin)
await self.platform_history_mgr.delete(
platform_id="webchat_thread",
user_id=thread_id,
offset_sec=99999999,
)
webchat_queue_mgr.remove_queues(thread_id)
self.running_convs.pop(thread_id, None)
async def load_current_conversation_history(self, session) -> tuple[str, list]:
unified_msg_origin = build_webchat_unified_msg_origin(session)
conversation_id = await self.conv_mgr.get_curr_conversation_id(
unified_msg_origin
)
if not conversation_id:
return "", []
conversation = await self.conv_mgr.get_conversation(
unified_msg_origin=unified_msg_origin,
conversation_id=conversation_id,
)
if not conversation:
return "", []
try:
history = json.loads(conversation.history or "[]")
except json.JSONDecodeError:
return "", []
return conversation_id, history if isinstance(history, list) else []
async def get_sorted_platform_history(self, session) -> list:
history_list = await self.platform_history_mgr.get(
platform_id=session.platform_id,
user_id=session.session_id,
page=1,
page_size=100000,
)
history_list.sort(key=lambda item: (item.created_at, item.id))
return history_list
async def delete_platform_history_after(
self, session, message_id: int
) -> list[int]:
history_list = await self.get_sorted_platform_history(session)
should_delete = False
deleted_ids: list[int] = []
for item in history_list:
if should_delete:
if item.id is not None:
deleted_ids.append(item.id)
await self.platform_history_mgr.delete_by_id(item.id)
continue
if item.id == message_id:
should_delete = True
return deleted_ids
async def save_bot_message(
self,
webchat_conv_id: str,
message_parts: list[dict],
agent_stats: dict,
refs: dict,
llm_checkpoint_id: str | None = None,
platform_history_id: str = "webchat",
):
return await self.platform_history_mgr.insert(
platform_id=platform_history_id,
user_id=webchat_conv_id,
content=build_bot_history_content(
message_parts,
agent_stats=agent_stats,
refs=refs,
),
sender_id="bot",
sender_name="bot",
llm_checkpoint_id=llm_checkpoint_id,
)
def get_active_chat_runs(self, username: str, session_id: str) -> list[dict]:
"""Return resumable runs owned by a user in one chat session.
Args:
username: Authenticated run owner.
session_id: WebChat session or thread identifier.
Returns:
Active run snapshots in creation order.
"""
snapshots = []
for run in self.chat_runs.values():
if run.username != username or run.session_id != session_id:
continue
snapshots.append(
{
"run_id": run.run_id,
"session_id": run.session_id,
"llm_checkpoint_id": run.llm_checkpoint_id,
"status": run.status,
"revision": run.revision,
"content": build_bot_history_content(
deepcopy(run.message_parts),
agent_stats=deepcopy(run.agent_stats),
refs=deepcopy(run.refs),
),
}
)
return snapshots
@staticmethod
def _publish_chat_run(run: ChatRunState, payload: dict) -> None:
"""Publish one output event without coupling the run to subscribers.
Args:
run: Chat run producing the event.
payload: Existing WebChat event payload.
"""
run.revision += 1
item = (run.revision, payload)
for subscriber in list(run.subscribers):
try:
subscriber.put_nowait(item)
except asyncio.QueueFull:
# End slow streams so they can reconnect from a fresh snapshot.
run.subscribers.discard(subscriber)
while not subscriber.empty():
subscriber.get_nowait()
subscriber.put_nowait(None)
def _subscribe_chat_run(
self,
run: ChatRunState,
*,
include_snapshot: bool,
saved_user_record=None,
) -> AsyncIterator[str]:
"""Create an SSE subscriber for a running chat generation.
Args:
run: Chat run to observe.
include_snapshot: Whether to begin with accumulated run state.
saved_user_record: Newly persisted user record for the legacy stream.
Returns:
SSE iterator detached from the generation task lifecycle.
"""
subscriber: asyncio.Queue = asyncio.Queue(
maxsize=CHAT_RUN_SUBSCRIBER_QUEUE_SIZE
)
run.subscribers.add(subscriber)
snapshot = None
if include_snapshot:
snapshot = {
"run_id": run.run_id,
"session_id": run.session_id,
"llm_checkpoint_id": run.llm_checkpoint_id,
"status": run.status,
"revision": run.revision,
"content": build_bot_history_content(
deepcopy(run.message_parts),
agent_stats=deepcopy(run.agent_stats),
refs=deepcopy(run.refs),
),
}
snapshot_revision = run.revision
async def stream():
try:
if snapshot is not None:
payload = {"type": "run_snapshot", "data": snapshot}
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
else:
session_info = {
"type": "session_id",
"data": None,
"session_id": run.session_id,
}
yield f"data: {json.dumps(session_info, ensure_ascii=False)}\n\n"
if saved_user_record:
user_saved_info = {
"type": "user_message_saved",
"data": {
"id": saved_user_record.id,
"created_at": to_utc_isoformat(
saved_user_record.created_at
),
"llm_checkpoint_id": run.llm_checkpoint_id,
},
}
yield f"data: {json.dumps(user_saved_info, ensure_ascii=False)}\n\n"
while True:
try:
item = await asyncio.wait_for(subscriber.get(), timeout=1)
except asyncio.TimeoutError:
yield SSE_HEARTBEAT
continue
if item is None:
break
revision, payload = item
if include_snapshot and revision <= snapshot_revision:
continue
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
finally:
run.subscribers.discard(subscriber)
return stream()
async def build_chat_run_stream(
self,
username: str,
run_id: str,
) -> AsyncIterator[str]:
"""Attach a new SSE subscriber to an active chat run.
Args:
username: Authenticated run owner.
run_id: Active run identifier.
Returns:
SSE iterator beginning with a full accumulated snapshot.
Raises:
ChatServiceError: If the run is absent or owned by another user.
"""
run = self.chat_runs.get(run_id)
if run is None:
raise ChatServiceError(f"Chat run {run_id} not found")
if run.username != username:
raise ChatServiceError("Permission denied")
return self._subscribe_chat_run(run, include_snapshot=True)
async def _consume_chat_run(self, run: ChatRunState) -> None:
"""Drain runner output, persist it, and fan it out to subscribers.
Args:
run: Chat run owning the producer queue and durable state.
"""
pending_accumulator = BotMessageAccumulator()
display_accumulator = BotMessageAccumulator()
pending_agent_stats = {}
pending_refs = {}
async def flush_pending_bot_message():
nonlocal pending_accumulator, pending_agent_stats, pending_refs
if not (
pending_accumulator.has_content() or pending_refs or pending_agent_stats
):
return None
message_parts_to_save = pending_accumulator.build_message_parts(
include_pending_tool_calls=True
)
plain_text = collect_plain_text_from_message_parts(message_parts_to_save)
try:
extracted_refs = extract_web_search_refs(
plain_text,
message_parts_to_save,
)
if not extracted_refs and pending_refs:
extracted_refs = pending_refs
except Exception as exc:
logger.exception(
f"Failed to extract web search refs: {exc}",
exc_info=True,
)
extracted_refs = pending_refs
run.refs = extracted_refs
saved_record = await self.save_bot_message(
run.session_id,
message_parts_to_save,
pending_agent_stats,
extracted_refs,
run.llm_checkpoint_id,
run.platform_history_id,
)
pending_accumulator = BotMessageAccumulator()
pending_agent_stats = {}
pending_refs = {}
return saved_record
self.running_convs[run.session_id] = True
try:
while True:
result = await run.back_queue.get()
if not result:
continue
if result.get("message_id") and str(result["message_id"]) != run.run_id:
logger.warning("webchat stream message_id mismatch")
continue
result_text = result.get("data", "")
msg_type = result.get("type")
streaming = result.get("streaming", False)
chain_type = result.get("chain_type")
if chain_type == "agent_stats":
try:
run.agent_stats = json.loads(result_text)
except (TypeError, json.JSONDecodeError):
run.agent_stats = {}
pending_agent_stats = run.agent_stats
self._publish_chat_run(
run,
{"type": "agent_stats", "data": run.agent_stats},
)
continue
if chain_type == "web_search_sources":
pending_refs = parse_web_search_sources(result_text)
run.refs = pending_refs
continue
attachment_saved_payload = None
if msg_type == "plain":
for accumulator in (pending_accumulator, display_accumulator):
accumulator.add_plain(
result_text,
chain_type=chain_type,
streaming=streaming,