-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzh_cosearch_agent_app.py
More file actions
3098 lines (2726 loc) · 112 KB
/
zh_cosearch_agent_app.py
File metadata and controls
3098 lines (2726 loc) · 112 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 time
import ast
import re
import threading
import queue
import os
import json
from dataclasses import dataclass
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
from handlers.summary_handler import handle_summary_intent, SummaryContext
from agents.cosearch_agent import CoSearchAgent
from agents.search_engine import SearchEngine
from memory.cosearch_agent_memory import Memory
from memory.rag_results_memory import SearchMemory
from memory.click_memory import ClickMemory
from utils import (
get_conversation_history,
get_user_only_conversation_history,
replace_utterance_ids,
get_user_info,
get_channel_info,
send_rag_answer,
send_link_only_rag_answer,
send_clarify_question,
update_rag_answer,
send_answer,
resolve_user_name,
is_new_channel,
send_status_message,
delete_status_message,
slack_chat_update,
SERPAPI_KEY,
OPENAI_KEY,
SQL_PASSWORD,
register_channel_display_name,
)
from memory.imm_profile_store import ImmProfileStore
from memory.mental_model_memory import MentalModelMemory
from handlers.topic_handler import handle_topic_intent, _execute_topic, TopicContext
from handlers.division_handler import handle_division_intent, _execute_division, DivisionContext
from handlers.profile_confirm import (
handle_profile_confirm, handle_profile_edit, handle_profile_modal_submit
)
from handlers.profile_utils import (
draft_profiles_from_convs,
notify_profile_update_if_changed,
)
from handlers.profile_watcher import watch_profile_in_background
from memory.pending_intent_memory import PendingIntentMemory
from judgment_planner import resolve_judgment_plan
from config import settings, validate_required_settings
from trigger_rules import (
clean_query_text,
has_confusion_cue,
extract_candidate_terms,
is_decision_like_message,
is_conflict_like_message,
)
# Slack API tokens
validate_required_settings()
SLACK_BOT_TOKEN = settings.slack_bot_token
SLACK_APP_TOKEN = settings.slack_app_token
BOT_ID = settings.slack_bot_id
app = App(token=SLACK_BOT_TOKEN)
search_engine = SearchEngine(api_key=SERPAPI_KEY)
agent = CoSearchAgent(
search_engine=search_engine,
api_key=OPENAI_KEY,
model_name=settings.llm_model_name,
fallback_model_name=settings.llm_fallback_model_name,
prompt_dir="prompts/ch",
)
triage_agent = CoSearchAgent(
search_engine=search_engine,
api_key=OPENAI_KEY,
model_name=settings.llm_fallback_model_name,
fallback_model_name=settings.llm_fallback_model_name,
prompt_dir="prompts/ch",
)
memory = Memory(sql_password=SQL_PASSWORD)
search_memory = SearchMemory(sql_password=SQL_PASSWORD)
click_memory = ClickMemory(sql_password=SQL_PASSWORD)
mental_model_memory = MentalModelMemory(jl_dir="jl")
profile_memory = ImmProfileStore(mental_model_memory=mental_model_memory, sql_password=SQL_PASSWORD)
pending_memory = PendingIntentMemory(sql_password=SQL_PASSWORD)
pending_memory.create_table_if_not_exists()
channel_id2names = get_channel_info(table_name="channel_info")
user_id2names = get_user_info(table_name="user_info")
# channel_id2names = {}
# user_id2names = {}
user_id2names[BOT_ID] = "CoSearchAgent"
def _resolve_name_for_imm_bootstrap(uid: str) -> str:
return str(user_id2names.get(uid, uid))
mental_model_memory.bootstrap_imm_from_jl(user_name_resolver=_resolve_name_for_imm_bootstrap)
# 全局对象字典,供画像确认后恢复意图执行时使用
_GLOBAL_OBJECTS = {
"agent": agent,
"search_engine": search_engine,
"memory": memory,
"search_memory": search_memory,
}
# 本次运行已见过的频道(内存缓存,重启后由 DB 补充)
_seen_channels: set = set()
_LAST_PROACTIVE_TRIGGER: dict = {}
_PERIODIC_ANALYSIS_STATE: dict = {}
_CHANNEL_INFO_SYNCED: set = set()
_CHANNEL_INTRO_SENT: set = set()
_AUTO_PROMPT_STATE: dict = {}
_AUTO_ROUND_COUNTER: dict = {}
_AUTO_FOLLOWUP_STATE: dict = {}
_EXPLAIN_TRIGGER_STATE: dict = {}
_MM_ACTIVE_CHANNEL_LAST_TS: dict[str, float] = {}
_MM_ACTIVE_CHANNEL_USERS: dict[str, dict[str, float]] = {}
_MM_ARCHIVED_CHANNELS: set[str] = set()
MM_UPDATE_RECENT_ROUNDS = 5
def _has_active_judgment_followup(channel_id: str, user_id: str) -> bool:
prefix = f"judgment:{channel_id}:{user_id}:"
for key, state in _AUTO_FOLLOWUP_STATE.items():
if key.startswith(prefix) and bool((state or {}).get("active")):
return True
return False
# 用户已解释话题字典:按频道隔离,防止不同频道的历史解释互相污染。
# key = f"{channel_id}:{user_id}", value = [query1, query2, ...]
_user_explained_topics: dict[str, list[str]] = {}
def _send_channel_intro_once(client, channel_id: str, inviter: str | None = None, reason: str = "") -> bool:
"""已停用频道打招呼逻辑。"""
return False
def _looks_like_profile_intro(text: str) -> bool:
"""识别用户是否在当前消息中明确提供了画像线索。"""
content = (text or "").strip()
if not content:
return False
task_request_cues = (
"总结", "归纳", "复盘", "回顾", "选题", "分工", "解释", "判断",
"帮我", "请帮", "能不能", "可不可以", "怎么", "如何", "请问",
)
if any(k in content for k in task_request_cues):
return False
strong_patterns = (
r"我(是|来自|学|读)(.{0,20})(专业|方向|学院)",
r"我(是|来自|学|读)(.{0,20})(本科生|硕士生|博士生|研究生|本科|硕士|博士|phd|PhD)",
r"(我的|我)(研究方向|研究兴趣|专业)是",
r"我(主修|从事|主要做)",
r"我对.{1,30}(感兴趣|有兴趣|更关注|关注|想研究|想做|计划研究)",
)
return any(re.search(p, content) for p in strong_patterns)
def _is_guidance_like_query(text: str) -> bool:
"""判断是否为引导用户继续补充信息的话术,而非可检索问题。"""
q = clean_query_text(text or "")
if not q:
return True
cues = (
"请继续", "继续介绍", "继续补充", "请补充", "先介绍", "具体介绍",
"说说你的", "说明你的", "描述你的", "进一步", "详细一点",
"你的研究方向", "您的研究方向", "项目兴趣", "先说下", "先聊聊",
)
if any(c in q for c in cues):
return True
# 纯引导类短句通常不适合直接检索。
if len(q) <= 20 and ("请" in q or "你" in q or "您" in q):
return True
return False
def _is_searchworthy_auto_query(response_type: str, query: str, user_utterance: str) -> bool:
"""非@自动回复路径的检索门槛,避免把引导语直接送入检索。"""
q = clean_query_text(query or "")
if not q:
return False
# 判断类如果是引导补充信息,先不检索。
if response_type == "judgment" and _is_guidance_like_query(q):
return False
# 用户在做画像自我介绍时,优先走画像更新,不直接检索。
if _looks_like_profile_intro(user_utterance):
return False
return True
def _is_smalltalk_message(text: str) -> bool:
"""识别非任务型寒暄/客套,避免触发检索。"""
q = clean_query_text(text or "")
if not q:
return True
# 明确停滞表达不应被当作寒暄拦截。
if _is_topic_stall_signal(q):
return False
direct_set = {
"你好", "您好", "哈喽", "嗨", "hi", "hello", "在吗", "在不在",
"早上好", "中午好", "下午好", "晚上好",
"谢谢", "感谢", "辛苦了", "收到", "好的", "ok", "okk", "嗯", "嗯嗯",
}
if q.lower() in direct_set:
return True
# 短寒暄+标点,如“你好呀”“hello~”
short = re.sub(r"[\s~~!!.。]+", "", q).lower()
if short in {"你好呀", "你好啊", "hello呀", "hi呀", "在吗呀", "谢谢你", "谢谢啦"}:
return True
# 含明显任务意图则不视为寒暄
task_cues = (
"总结", "选题", "分工", "解释", "判断", "怎么", "如何", "为什么", "请", "帮", "?", "?",
"卡住", "没思路", "没有思路", "不知道", "想不出", "没进展", "没有方向", "没有想法", "没想法",
)
if any(c in q for c in task_cues):
return False
return len(q) <= 6
def _is_topic_stall_message(text: str) -> bool:
"""选题讨论中“无进展/无思路”信号。"""
q = clean_query_text(text or "")
if not q:
return False
topic_cues = ("选题", "题目", "方向", "做什么", "研究什么")
stall_cues = ("没思路", "不知道", "想不出", "卡住", "没进展", "没有方向", "不会", "没有想法")
return any(c in q for c in topic_cues) and any(c in q for c in stall_cues)
def _is_topic_stall_signal(text: str) -> bool:
"""宽松判定:用于 mm_decision.reason/query 的停滞信号识别。"""
q = clean_query_text(text or "")
if not q:
return False
# 兼容模型输出中意外空格/换行导致的关键词断裂。
q_compact = re.sub(r"\s+", "", q)
stall_cues = (
"没思路", "没有思路", "不知道", "想不出", "卡住", "没进展", "没有方向", "无思路", "缺乏选题思路", "没有想法", "没想法", "无想法",
)
return any(c in q for c in stall_cues) or any(c in q_compact for c in stall_cues)
def _is_division_stall_signal(text: str) -> bool:
"""分工阶段停滞信号:仅在“分工相关 + 推进困难”时触发。"""
q = clean_query_text(text or "")
if not q:
return False
q_compact = re.sub(r"\s+", "", q)
division_cues = (
"分工", "任务分配", "谁负责", "谁来做", "怎么分配", "怎么分工",
)
stall_cues = (
"没思路", "没有思路", "不知道", "想不出", "卡住", "没进展", "推进不动", "不清楚", "不会",
"没有想法", "没想法", "分不清", "拿不准",
)
return (
(any(c in q for c in division_cues) or any(c in q_compact for c in division_cues))
and (any(c in q for c in stall_cues) or any(c in q_compact for c in stall_cues))
)
def _build_imm_smm_context(channel_id: str, user_id: str, user_name: str, convs: str, query: str) -> str:
"""统一生成:频道全部非Bot IMM + SMM + 近五轮对话 + query。"""
channel_name = channel_id2names.get(channel_id, channel_id)
active_user_ids = _get_active_user_ids_in_channel(
client=app.client,
channel_id=channel_id,
bot_id=BOT_ID,
user_id2names=user_id2names,
memory=memory,
channel_name=channel_name,
)
imm_bundle: dict[str, dict] = {}
seen: set[str] = set()
for uid in active_user_ids:
clean_uid = str(uid or "").strip()
if not clean_uid or clean_uid == BOT_ID or clean_uid in seen:
continue
seen.add(clean_uid)
uname = str(user_id2names.get(clean_uid) or clean_uid)
imm_bundle[clean_uid] = mental_model_memory.get_imm(user_id=clean_uid, user_name=uname)
# 兜底:至少包含当前用户。
if not imm_bundle:
imm_bundle[user_id] = mental_model_memory.get_imm(user_id=user_id, user_name=user_name)
smm = mental_model_memory.get_smm(channel_id=channel_id)
conv_lines = [line for line in str(convs or "").splitlines() if str(line).strip()]
recent_convs = "\n".join(conv_lines[-INTENT_CONTEXT_MESSAGE_LIMIT:])
return (
"【IMM(频道非Bot用户合集)】\n"
f"{json.dumps(imm_bundle or {}, ensure_ascii=False)}\n\n"
"【SMM】\n"
f"{json.dumps(smm or {}, ensure_ascii=False)}\n\n"
"【近五轮对话】\n"
f"{recent_convs}\n\n"
"【当前问题】\n"
f"{query}"
)
def _int_env(name: str, default: int) -> int:
raw = os.getenv(name, str(default)).strip()
try:
return int(raw)
except ValueError:
print(f"[DEBUG][proactive] 环境变量 {name} 非法: {raw!r},回退默认值 {default}")
return default
TERM_COOLDOWN_SECONDS = _int_env("TERM_COOLDOWN_SECONDS", 180)
JUDGMENT_COOLDOWN_SECONDS = _int_env("JUDGMENT_COOLDOWN_SECONDS", 180)
PERIODIC_ANALYSIS_MESSAGE_WINDOW = _int_env("PERIODIC_ANALYSIS_MESSAGE_WINDOW", 10)
PERIODIC_ANALYSIS_SECONDS_WINDOW = _int_env("PERIODIC_ANALYSIS_SECONDS_WINDOW", 30)
INTENT_CONTEXT_MESSAGE_LIMIT = _int_env("INTENT_CONTEXT_MESSAGE_LIMIT", 10)
AUTO_RECOGNIZE_EVERY_ROUNDS = _int_env("AUTO_RECOGNIZE_EVERY_ROUNDS", 1)
LOW_INFO_TERM_WINDOW_SECONDS = _int_env("LOW_INFO_TERM_WINDOW_SECONDS", 100)
EXPLAIN_REPEAT_COOLDOWN_SECONDS = _int_env("EXPLAIN_REPEAT_COOLDOWN_SECONDS", 180)
AUTO_CONFIRM_EXPIRE_SECONDS = _int_env("AUTO_CONFIRM_EXPIRE_SECONDS", 180)
FOLLOWUP_ROUNDS = _int_env("FOLLOWUP_ROUNDS", 3)
FOLLOWUP_POLL_SECONDS = _int_env("FOLLOWUP_POLL_SECONDS", 2)
FOLLOWUP_MAX_CYCLES = _int_env("FOLLOWUP_MAX_CYCLES", 4)
FOLLOWUP_MAX_SECONDS = _int_env("FOLLOWUP_MAX_SECONDS", 300)
MM_TIMER_POLL_SECONDS = _int_env("MM_TIMER_POLL_SECONDS", 5)
MM_ACTIVE_CHANNEL_WINDOW_SECONDS = _int_env("MM_ACTIVE_CHANNEL_WINDOW_SECONDS", 300)
MM_TERM_SOLVING_REVIEW_SECONDS = _int_env("MM_TERM_SOLVING_REVIEW_SECONDS", 300)
MESSAGE_LOCK_WAIT_SECONDS = _int_env("MESSAGE_LOCK_WAIT_SECONDS", 20)
EVENT_DEDUP_WINDOW_SECONDS = _int_env("EVENT_DEDUP_WINDOW_SECONDS", 300)
# 异步处理队列:按 (channel_id, user_id) 分区串行,避免同一用户消息乱序处理。
@dataclass
class _MessageTask:
channel_id: str
channel_name: str
user_id: str
user_name: str
ts: str
event_type: str
raw_text: str
user_utterance: str
query: str
mentioned_bot: bool
_message_task_queues: dict[tuple[str, str], queue.Queue] = {}
_message_worker_threads: dict[tuple[str, str], threading.Thread] = {}
_worker_mutex = threading.Lock()
_mm_timer_worker_thread: threading.Thread | None = None
# 事件去重:避免同一条消息被 app_mention + message 双订阅重复处理。
# key: (channel_id, user_id, ts) -> first_seen_epoch
_recent_message_event_keys: dict[tuple[str, str, str], float] = {}
_event_dedupe_lock = threading.Lock()
def _is_duplicate_message_event(channel_id: str, user_id: str, ts: str, event_type: str = "") -> bool:
now = time.time()
key = (channel_id, user_id, ts)
with _event_dedupe_lock:
first_seen = _recent_message_event_keys.get(key)
if first_seen and (now - first_seen) <= EVENT_DEDUP_WINDOW_SECONDS:
print(
f"[DEBUG][handle_message] 去重命中,跳过重复事件 "
f"type={event_type!r} channel={channel_id!r} user={user_id!r} ts={ts!r}"
)
return True
_recent_message_event_keys[key] = now
# 仅在键数较多时清理过期项,控制常驻内存。
if len(_recent_message_event_keys) > 2000:
expire_before = now - EVENT_DEDUP_WINDOW_SECONDS
expired_keys = [k for k, seen_at in _recent_message_event_keys.items() if seen_at < expire_before]
for k in expired_keys:
_recent_message_event_keys.pop(k, None)
return False
def _get_message_task_queue(channel_id: str, user_id: str) -> queue.Queue:
key = (channel_id, user_id)
with _worker_mutex:
q = _message_task_queues.get(key)
if q is None:
q = queue.Queue()
_message_task_queues[key] = q
return q
def _ensure_message_worker(client, channel_id: str, user_id: str) -> None:
key = (channel_id, user_id)
with _worker_mutex:
thread = _message_worker_threads.get(key)
if thread and thread.is_alive():
return
q = _message_task_queues.get(key)
if q is None:
q = queue.Queue()
_message_task_queues[key] = q
def _worker():
while True:
task = q.get()
try:
_process_message_task(client=client, task=task)
except Exception as e:
print(
f"[DEBUG][handle_message] 后台处理异常 channel={task.channel_id!r} "
f"user={task.user_id!r} ts={task.ts!r}: {e}"
)
finally:
q.task_done()
thread = threading.Thread(target=_worker, daemon=True)
_message_worker_threads[key] = thread
thread.start()
def _enqueue_message_task(client, task: _MessageTask) -> None:
_ensure_message_worker(client=client, channel_id=task.channel_id, user_id=task.user_id)
q = _get_message_task_queue(task.channel_id, task.user_id)
q.put(task)
def _get_active_user_ids_in_channel(client, channel_id: str, bot_id: str,
user_id2names: dict, memory: Memory,
channel_name: str) -> list[str]:
"""
获取当前频道中参与过对话的真实用户 ID 列表(排除 Bot)。
改用从数据库读取发言记录的方式,避免需要额外的 Slack API 权限。
"""
try:
# 从数据库读取该频道的所有发言者
all_rows = memory.load_all_utterances(table_name=channel_name)
speakers = set()
for row in all_rows:
speaker = str(row.get("speaker", "")).strip()
if speaker and speaker != "CoSearchAgent":
speakers.add(speaker)
# 反查 user_id:user_id2names 是 {uid: uname}
# 兼容两种 speaker 落库格式:真实用户名 或 Slack UID(例如 U0A2JNV4WTT)
speakers_lower = {s.lower() for s in speakers}
active = []
for uid, uname in user_id2names.items():
if uid == bot_id or uid == "bot_id":
continue
uname_str = str(uname or "").strip()
if uid in speakers or (uname_str and uname_str.lower() in speakers_lower):
active.append(uid)
print(f"[DEBUG][app] 频道 {channel_name} 参与用户(从DB): {active} speakers={speakers}")
return active
except Exception as e:
print(f"[DEBUG][app] ⚠ 获取频道参与用户失败: {e}")
return []
# 意图 → 中文标签映射(用于状态消息)
INTENT_LABEL_MAP = {
"【选题】": "📚 选题建议",
"【分工】": "📋 研究分工",
"【总结】": "🗓️ 对话总结",
"【专业解释】": "🧠 专业解释",
"【知识解答】": "📖 知识解答",
"【判断】": "⚖️ 判断分析",
"【其他】": "💬 闲聊问答",
}
def _format_profile_text_for_explain(channel_id: str, user_id: str, user_name: str) -> str:
profile = profile_memory.load(user_id, channel_id)
imm = mental_model_memory.get_imm(user_id=user_id, user_name=user_name)
imm_profile = (imm or {}).get("个人画像") if isinstance((imm or {}).get("个人画像"), dict) else {}
imm_kb = (imm or {}).get("个人领域知识库") if isinstance((imm or {}).get("个人领域知识库"), dict) else {}
imm_major = str(imm_profile.get("专业领域") or (imm or {}).get("professional_background") or "").strip()
top_terms = list(imm_kb.get("提取术语") or (imm or {}).get("familiar_terms") or [])[:12]
if not profile:
return (
f"用户:{user_name}\n"
f"专业:{imm_major or '未知'}\n"
"研究兴趣:暂无\n"
"方法偏好:暂无\n"
f"已掌握术语:{'、'.join(top_terms) if top_terms else '暂无'}"
)
interests = "、".join(profile.get("research_interests") or []) or "暂无"
methods = "、".join(profile.get("methodology") or []) or "暂无"
major = imm_major or profile.get("major") or "未知"
return (
f"用户:{profile.get('user_name') or user_name}\n"
f"专业:{major}\n"
f"研究兴趣:{interests}\n"
f"方法偏好:{methods}\n"
f"已掌握术语:{'、'.join(top_terms) if top_terms else '暂无'}"
)
def _infer_mention_response_type(query: str, imm: dict) -> str:
"""在@场景下,用查询文本 + IMM 快速推断回复类型(不再额外调用LLM)。"""
text = clean_query_text(query or "")
if not text:
return "knowledge"
if is_decision_like_message(text) or is_conflict_like_message(text):
return "judgment"
if has_confusion_cue(text):
return "professional_explain"
imm_kb = (imm or {}).get("个人领域知识库") if isinstance((imm or {}).get("个人领域知识库"), dict) else {}
terms = list(imm_kb.get("提取术语") or (imm or {}).get("familiar_terms") or []) + list((imm or {}).get("known_terms") or [])
lowered = text.lower()
for term in terms:
clean_term = str(term or "").strip().lower()
if clean_term and clean_term in lowered:
return "professional_explain"
return "knowledge"
def _now_ts() -> float:
return time.time()
def _normalize_term(term: str) -> str:
clean = re.sub(r"[^\w\u4e00-\u9fff\-]+", "", (term or "").strip().lower())
return clean
def _parse_yes_no(text: str) -> str:
content = (text or "").strip().lower()
if not content:
return "unknown"
yes_cues = ("需要", "要", "可以", "好", "行", "是", "yes", "y")
no_cues = ("不需要", "不用", "不要", "不用了", "不", "否", "no", "n", "算了")
if any(cue in content for cue in no_cues):
return "no"
if any(cue in content for cue in yes_cues):
return "yes"
return "unknown"
def _has_understood_cue(text: str) -> bool:
understood_cues = ("懂了", "明白了", "清楚了", "知道了", "ok", "收到", "了解了")
content = (text or "").lower()
return any(c in content for c in understood_cues)
def _is_low_info_followup(text: str) -> bool:
content = clean_query_text(text or "").lower()
if not content:
return False
low_info_phrases = (
"这是啥", "这是什么", "啥", "是什么", "什么意思", "难吗", "没学过", "没学过啊", "不懂", "听不懂",
)
if content in low_info_phrases:
return True
return len(content) <= 6 and has_confusion_cue(content)
def _extract_recent_term_from_convs(convs: str, lookback_lines: int = 12) -> str:
if not convs:
return ""
lines = [ln.strip() for ln in str(convs).splitlines() if ln.strip()]
for line in reversed(lines[-lookback_lines:]):
terms = extract_candidate_terms(line)
if terms:
return _normalize_term(terms[0])
return ""
def _strip_speaker_prefix(line: str) -> str:
text = (line or "").strip()
if not text:
return ""
if ":" in text:
return text.split(":", 1)[1].strip()
if ":" in text:
return text.split(":", 1)[1].strip()
return text
def _extract_recent_user_texts(convs: str, lookback_lines: int = 12) -> list[str]:
if not convs:
return []
lines = [ln.strip() for ln in str(convs).splitlines() if ln.strip()]
result: list[str] = []
for line in lines[-lookback_lines:]:
if line.startswith("CoSearchAgent:"):
continue
text = _strip_speaker_prefix(line)
if text:
result.append(text)
return result
def _extract_recent_decision_query(convs: str, fallback: str) -> str:
recent_texts = _extract_recent_user_texts(convs, lookback_lines=12)
for text in reversed(recent_texts):
if is_decision_like_message(text):
return clean_query_text(text)
return clean_query_text(fallback)
def _has_conflict_escalation(convs: str, current_text: str, min_signals: int = 3) -> bool:
recent_texts = _extract_recent_user_texts(convs, lookback_lines=10)
signals = 0
for text in recent_texts + [clean_query_text(current_text)]:
if is_conflict_like_message(text) or is_decision_like_message(text):
signals += 1
return signals >= min_signals
def _extract_recent_term_from_channel_window(
channel_name: str,
now_ts: float,
window_seconds: int = 100,
max_scan_rows: int = 120,
) -> str:
if not channel_name:
return ""
cutoff_ts = float(now_ts) - float(window_seconds)
try:
rows = memory.load_all_utterances(table_name=channel_name)
except Exception:
return ""
scanned = 0
for row in reversed(rows):
if scanned >= max_scan_rows:
break
scanned += 1
speaker = str(row.get("speaker") or "")
if speaker == "CoSearchAgent":
continue
utterance = str(row.get("utterance") or "").strip()
if not utterance:
continue
ts_raw = row.get("timestamp") or "0"
try:
ts_val = float(ts_raw)
except Exception:
continue
if ts_val < cutoff_ts:
break
terms = extract_candidate_terms(utterance)
if terms:
return _normalize_term(terms[0])
return ""
def _build_auto_key(channel_id: str, user_id: str) -> str:
return f"{channel_id}:{user_id}"
def _build_explain_term_key(channel_id: str, user_id: str, term: str) -> str:
return f"{channel_id}:{user_id}:{_normalize_term(term)}"
def _get_explain_trigger_meta(channel_id: str, user_id: str, term: str) -> dict:
key = _build_explain_term_key(channel_id, user_id, term)
return _EXPLAIN_TRIGGER_STATE.get(key) or {"count": 0, "last_ts": 0.0}
def _record_explain_trigger(channel_id: str, user_id: str, term: str):
clean_term = _normalize_term(term)
if not clean_term:
return
key = _build_explain_term_key(channel_id, user_id, clean_term)
meta = _EXPLAIN_TRIGGER_STATE.get(key) or {"count": 0, "last_ts": 0.0}
meta["count"] = int(meta.get("count", 0)) + 1
meta["last_ts"] = _now_ts()
_EXPLAIN_TRIGGER_STATE[key] = meta
def _build_auto_confirm_text(kind: str, term: str, repeat_explain: bool = False) -> str:
if kind == "explain":
if repeat_explain:
return f"检测到你对术语“{term or '该术语'}”可能还有疑问,需要我进一步解释吗?"
return f"检测到你们在讨论术语“{term or '该术语'}”,需要我现在给一个专业解释吗?"
return "检测到你们可能在争论同一问题,需要我发起一次判断分析吗?"
def _build_auto_confirm_blocks(kind: str, term: str, repeat_explain: bool = False) -> list[dict]:
text = _build_auto_confirm_text(kind=kind, term=term, repeat_explain=repeat_explain)
return [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"{text}\n\n点击按钮确认,确认后我再开始检索。",
},
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {"type": "plain_text", "text": "需要"},
"style": "primary",
"action_id": "auto_prompt_accept",
"value": "yes",
},
{
"type": "button",
"text": {"type": "plain_text", "text": "不需要"},
"action_id": "auto_prompt_decline",
"value": "no",
},
],
},
]
def _update_auto_prompt_card(client, channel_id: str, pending: dict, text: str):
prompt_ts = str(pending.get("prompt_ts") or "").strip()
if not prompt_ts:
return
try:
slack_chat_update(
client=client,
channel=channel_id,
ts=prompt_ts,
blocks=[
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": text,
},
}
],
)
except Exception as e:
print(f"[DEBUG][auto_prompt] 更新确认卡片失败: {e}")
def _parse_explain_search_output(raw_output: str, fallback_query: str) -> tuple[str, str]:
thought = ""
rewritten_query = ""
for line in (raw_output or "").splitlines():
clean_line = line.strip()
if not clean_line:
continue
if clean_line.startswith("检索思路:"):
thought = clean_line.split(":", 1)[-1].strip()
elif clean_line.startswith("检索词:"):
rewritten_query = clean_line.split(":", 1)[-1].strip()
rewritten_query = clean_query_text(rewritten_query or fallback_query)
return thought, rewritten_query
def _fallback_explain_search_query(query: str, term: str = "") -> str:
normalized_term = _normalize_term(term)
if normalized_term:
if re.fullmatch(r"[a-z]{2,12}", normalized_term):
return normalized_term.upper()
return normalized_term
return clean_query_text(query)
def _resolve_professional_explain_search_query(query: str, convs: str, term: str = "") -> tuple[str, float, str]:
fallback_query = _fallback_explain_search_query(query=query, term=term)
try:
rewrite_output, rewrite_time = agent.rewrite_professional_explain_query(
query=query,
convs=convs,
term=term,
)
rewrite_thought, rewrite_query = _parse_explain_search_output(rewrite_output, fallback_query)
return rewrite_query, rewrite_time, rewrite_thought
except Exception as e:
print(f"[DEBUG][explain_rewrite] 检索词改写失败,回退默认术语检索: {e}")
return fallback_query, 0.0, ""
def _queue_auto_prompt(
client,
channel_name: str,
channel_id: str,
user_id: str,
user_name: str,
kind: str,
term: str,
query: str,
reason: str,
trigger_ts: str,
):
repeat_explain = False
if kind == "explain":
clean_term = _normalize_term(term)
meta = _get_explain_trigger_meta(channel_id=channel_id, user_id=user_id, term=clean_term)
prev_count = int(meta.get("count", 0))
last_ts = float(meta.get("last_ts", 0.0))
now_ts = _now_ts()
# 避免短时间内同术语重复触发太多次;第2次允许并改成“进一步解释”文案。
if prev_count >= 2 and (now_ts - last_ts) < EXPLAIN_REPEAT_COOLDOWN_SECONDS:
print(
f"[DEBUG][auto_prompt] 跳过重复解释 term={clean_term!r} "
f"count={prev_count} cooldown={EXPLAIN_REPEAT_COOLDOWN_SECONDS}s"
)
return
repeat_explain = prev_count >= 1
# 取消二次确认:自动识别到可介入场景后直接执行。
key = _build_auto_key(channel_id, user_id)
_AUTO_PROMPT_STATE[key] = {
"kind": kind,
"term": term or "",
"query": query or "",
"reason": reason or "",
"repeat_explain": repeat_explain,
"trigger_ts": str(trigger_ts),
"created_at": _now_ts(),
}
_execute_auto_prompt_decision(
client=client,
channel_id=channel_id,
channel_name=channel_name,
user_id=user_id,
user_name=user_name,
action_ts=str(trigger_ts),
decision="yes",
)
if kind == "explain":
_record_explain_trigger(channel_id=channel_id, user_id=user_id, term=term)
def _term_already_known(channel_id: str, user_id: str, term: str) -> bool:
clean_term = _normalize_term(term)
if not clean_term:
return True
known = profile_memory.get_known_terms(user_id=user_id, channel_id=channel_id)
return clean_term in known
def _mark_term_known(channel_id: str, user_id: str, user_name: str, term: str):
clean_term = _normalize_term(term)
if not clean_term:
return
added = profile_memory.add_known_term(user_id=user_id, channel_id=channel_id, term=clean_term)
if added:
print(f"[DEBUG][known_term] 已记录已知术语 user={user_name!r} term={clean_term!r}")
def _load_new_user_messages(channel_name: str, user_name: str, last_ts: float, max_items: int = 50) -> list[dict]:
rows = memory.load_all_utterances(table_name=channel_name)
out = []
for row in rows:
speaker = row.get("speaker") or ""
utterance = (row.get("utterance") or "").strip()
ts_raw = row.get("timestamp") or "0"
if speaker != user_name or not utterance:
continue
try:
ts_val = float(ts_raw)
except Exception:
continue
if ts_val <= last_ts:
continue
out.append({"timestamp": ts_val, "utterance": utterance})
out.sort(key=lambda x: x["timestamp"])
return out[-max_items:]
def _run_special_judgment_choice(
client,
channel_id: str,
user_id: str,
user_name: str,
channel_name: str,
):
try:
convs = get_conversation_history(
client=client,
channel_id=channel_id,
bot_id=BOT_ID,
user_id2names=user_id2names,
ts=str(_now_ts()),
limit=60,
)
prompt = (
"你是争议裁决助手。请基于以下对话给出明确选择,禁止模糊中立。\n"
"输出格式必须为JSON:"
"{\"choice\":\"...\",\"reason\":\"...\",\"next_step\":\"...\"}\n"
"要求:\n"
"1) choice 必须给出明确站位或方案。\n"
"2) reason 用2句以内,给出核心依据。\n"
"3) next_step 给出可执行下一步。\n\n"
f"用户:{user_name}\n"
f"近期对话:\n{convs}\n"
)
raw = agent.generate_openai_response(prompt)
data = _safe_load_json(raw)
choice = str(data.get("choice") or "方案A").strip()
reason = str(data.get("reason") or "基于当前约束与可执行性,优先该方案。").strip()
next_step = str(data.get("next_step") or "先按该方案执行一个最小可验证版本,再复盘。").strip()
answer = (
f"<@{user_id}> 在你们持续争论的点上,我给出明确判断:*{choice}*。\n"
f"依据:{reason}\n"
f"建议下一步:{next_step}"
)
response = send_answer(client=client, channel_id=channel_id, user_id=user_id, answer=answer)
memory.write_into_memory(
table_name=channel_name,
utterance_info={
"speaker": "CoSearchAgent",
"utterance": answer,
"convs": convs,
"query": "special_judgment_choice",
"rewrite_query": "",
"rewrite_thought": "",
"clarify": "",
"clarify_thought": "",
"clarify_cnt": 0,
"search_results": "",
"infer_time": str({"workflow": "special_judgment_choice"}),
"reply_timestamp": str(_now_ts()),
"reply_user": user_name,
"timestamp": response["ts"],
},
)
except Exception as e:
print(f"[DEBUG][followup_judgment] 特殊判断失败: {e}")
def _start_explain_followup_worker(
client,
channel_id: str,
channel_name: str,
user_id: str,
user_name: str,
term: str,
trigger_ts: float,
):
follow_key = f"explain:{channel_id}:{user_id}:{_normalize_term(term)}"
_AUTO_FOLLOWUP_STATE[follow_key] = {"active": True}
def _worker():
clean_term = _normalize_term(term)
last_ts = float(trigger_ts)
rounds_left = FOLLOWUP_ROUNDS
cycles = 0
started_at = _now_ts()
mention_seen = False
confusion_seen = False
understood_seen = False
print(f"[DEBUG][followup_explain] 启动 follow_key={follow_key!r}")
while _AUTO_FOLLOWUP_STATE.get(follow_key, {}).get("active"):
if _now_ts() - started_at > FOLLOWUP_MAX_SECONDS:
# 到达观察上限且未出现新的困惑跟进,视为该术语暂时已掌握。
mental_model_memory.update_unknown_term_status(
user_id=user_id,
user_name=user_name,
term=term,
status="已解决",
note="观察窗口内未继续追问,自动结案",
reset_timer=False,
)
_mark_term_known(channel_id=channel_id, user_id=user_id, user_name=user_name, term=term)
break
time.sleep(max(1, FOLLOWUP_POLL_SECONDS))
try:
new_msgs = _load_new_user_messages(channel_name, user_name, last_ts)
except Exception as e:
print(f"[DEBUG][followup_explain] 读取消息失败: {e}")