lingshu-skill 5.32.0 → 5.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4281 -4173
- package/README.md +1584 -1577
- package/SKILL-lite.md +59 -59
- package/SKILL-tiny.md +38 -38
- package/SKILL.md +356 -317
- package/assets/panel.html +6753 -5698
- package/cordis-plugin/lingshu-cron/plugin.js +1455 -1417
- package/cordis-plugin/lingshu-startup/context-fold.js +170 -0
- package/cordis-plugin/lingshu-startup/context-pressure.js +16 -0
- package/cordis-plugin/lingshu-startup/context-snapshot.js +176 -0
- package/cordis-plugin/lingshu-startup/plugin.js +499 -467
- package/docs/audit_notes//345/276/205/345/212/236-20261201-/351/235/242/346/235/277/344/270/245/346/237/245/344/270/216/345/256/241/350/256/241.md +162 -0
- package/docs/audit_notes//345/276/205/345/212/236-20261202-/351/235/242/346/235/277/344/272/244/344/272/222/344/270/216/346/225/260/346/215/256/345/245/221/347/272/246/345/256/241/350/256/241.md +92 -0
- package/docs/audit_notes//345/276/205/345/212/236/346/250/241/346/235/277.md +140 -0
- package/docs/commands.md +278 -247
- package/docs/mechanics.md +610 -610
- package/docs//345/276/205/345/212/236-20261201-/351/235/242/346/235/277/344/270/245/346/237/245/344/270/216/345/256/241/350/256/241.md +162 -0
- package/docs//345/276/205/345/212/236-20261202-/351/235/242/346/235/277/344/272/244/344/272/222/344/270/216/346/225/260/346/215/256/345/245/221/347/272/246/345/256/241/350/256/241.md +92 -0
- package/package.json +52 -52
- package/scripts/_scratch/_tmp_backup_race.py +70 -0
- package/scripts/_scratch/_tmp_cleanup_move.py +34 -0
- package/scripts/_scratch/_tmp_count_kinds.py +25 -0
- package/scripts/_scratch/_tmp_diag_paths.py +48 -0
- package/scripts/_scratch/_tmp_facts.py +63 -0
- package/scripts/_scratch/_tmp_find_copies.py +31 -0
- package/scripts/_scratch/_tmp_find_pin.py +29 -0
- package/scripts/_scratch/_tmp_fix_pin.py +36 -0
- package/scripts/_scratch/_tmp_fold_fixture.py +55 -0
- package/scripts/_scratch/_tmp_fold_test.mjs +81 -0
- package/scripts/_scratch/_tmp_inject_secs.py +30 -0
- package/scripts/_scratch/_tmp_kb_balance.py +159 -0
- package/scripts/_scratch/_tmp_lines.py +15 -0
- package/scripts/_scratch/_tmp_market_probe.py +13 -0
- package/scripts/_scratch/_tmp_move_partial.py +16 -0
- package/scripts/_scratch/_tmp_patch_b3.py +41 -0
- package/scripts/_scratch/_tmp_patch_b5.py +62 -0
- package/scripts/_scratch/_tmp_patch_crash_excl.py +24 -0
- package/scripts/_scratch/_tmp_patch_handoff.py +21 -0
- package/scripts/_scratch/_tmp_patch_ps1.py +25 -0
- package/scripts/_scratch/_tmp_patch_stat.py +27 -0
- package/scripts/_scratch/_tmp_patch_todo.py +25 -0
- package/scripts/_scratch/_tmp_patch_todo2.py +64 -0
- package/scripts/_scratch/_tmp_probe_session.py +51 -0
- package/scripts/_scratch/_tmp_style_probe.py +40 -0
- package/scripts/_scratch/_tmp_write_note.py +139 -0
- package/scripts/_scratch/_/346/235/245/346/272/220/350/256/260/345/275/225.txt +1 -0
- package/scripts/_scratch/asar_compaction/dsh-compaction-basic__lib__index.js +1044 -0
- package/scripts/_scratch/asar_compaction/dsh-compaction-tool-result-pruner__lib__index.js +194 -0
- package/scripts/_scratch/asar_compaction/dsh-compaction__lib__index.js +175 -0
- package/scripts/_scratch/asar_compaction/dsh-compaction__lib__types__tool-pairing.js +97 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__image-offload.js +47 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__index.js +40 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction-image-offload__lib__types__project-message.js +37 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__brand.js +9 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__checkpoint.js +36 -0
- package/scripts/_scratch/asar_compaction/dsh__node_modules__@deepseek-ai__dsh-compaction__lib__types__types.js +10 -0
- package/scripts/_scratch/commit_msg_occ.txt +16 -0
- package/scripts/_scratch/commit_msg_struct.txt +16 -0
- package/scripts/_scratch/v5.34_changelog.txt +36 -0
- package/scripts/_sync_trae_cn.py +102 -34
- package/scripts/_tmp_add_s10.py +54 -0
- package/scripts/_tmp_add_s11.py +61 -0
- package/scripts/_tmp_add_s12.py +66 -0
- package/scripts/_tmp_add_s13.py +69 -0
- package/scripts/_tmp_add_s14.py +80 -0
- package/scripts/_tmp_add_s9.py +68 -0
- package/scripts/_tmp_cache_load.py +82 -0
- package/scripts/_tmp_clean_market.py +40 -0
- package/scripts/_tmp_clean_pruned.py +81 -0
- package/scripts/_tmp_cleanup_docs.py +39 -0
- package/scripts/_tmp_cmp_ranker.py +17 -0
- package/scripts/_tmp_dolater_note.py +35 -0
- package/scripts/_tmp_dust_why.py +27 -0
- package/scripts/_tmp_explicit_import.py +40 -0
- package/scripts/_tmp_extract_compaction.py +35 -0
- package/scripts/_tmp_extract_compaction2.py +63 -0
- package/scripts/_tmp_extract_compaction3.py +51 -0
- package/scripts/_tmp_extract_compaction4.py +54 -0
- package/scripts/_tmp_finalize_s14.py +39 -0
- package/scripts/_tmp_find_compaction.py +43 -0
- package/scripts/_tmp_fix_b4.py +22 -0
- package/scripts/_tmp_fix_cli76.py +26 -0
- package/scripts/_tmp_fix_docs.py +38 -0
- package/scripts/_tmp_fix_docs_b.py +46 -0
- package/scripts/_tmp_fix_docs_b2.py +22 -0
- package/scripts/_tmp_fix_i3.py +23 -0
- package/scripts/_tmp_fix_s10.py +83 -0
- package/scripts/_tmp_fix_s11.py +14 -0
- package/scripts/_tmp_fix_s9_status.py +19 -0
- package/scripts/_tmp_fix_shadow_sim.py +37 -0
- package/scripts/_tmp_fix_traits_value.py +41 -0
- package/scripts/_tmp_import_idem.py +106 -0
- package/scripts/_tmp_log_ack.py +45 -0
- package/scripts/_tmp_mark_batch.py +28 -0
- package/scripts/_tmp_mark_batch2.py +32 -0
- package/scripts/_tmp_mark_dolater.py +26 -0
- package/scripts/_tmp_mark_dolater2.py +31 -0
- package/scripts/_tmp_move_self.py +16 -0
- package/scripts/_tmp_occ_cli.py +22 -0
- package/scripts/_tmp_occ_link.py +108 -0
- package/scripts/_tmp_optimize_recall.py +54 -0
- package/scripts/_tmp_panel_audit.py +26 -0
- package/scripts/_tmp_patch_batch3.py +65 -0
- package/scripts/_tmp_patch_rrf.py +46 -0
- package/scripts/_tmp_patch_s2s3.py +80 -0
- package/scripts/_tmp_patch_s4.py +39 -0
- package/scripts/_tmp_patch_s7.py +43 -0
- package/scripts/_tmp_patch_s8.py +91 -0
- package/scripts/_tmp_patch_skill.py +17 -0
- package/scripts/_tmp_release_guard.py +57 -0
- package/scripts/_tmp_rerank_breaker.py +62 -0
- package/scripts/_tmp_s16.py +41 -0
- package/scripts/_tmp_scan_asar.py +41 -0
- package/scripts/_tmp_scan_asar2.py +37 -0
- package/scripts/_tmp_struct_docs.py +49 -0
- package/scripts/_tmp_sum_fallback.py +42 -0
- package/scripts/_tmp_sweep.py +81 -0
- package/scripts/_tmp_sync_check.py +69 -0
- package/scripts/_tmp_sync_tail.py +39 -0
- package/scripts/_tmp_todo_clean.py +67 -0
- package/scripts/_tmp_verify_copy.py +17 -0
- package/scripts/_tmp_wire_extras.py +93 -0
- package/scripts/_tmp_wire_hsum.py +34 -0
- package/scripts/_tmp_wire_occ_b5.py +40 -0
- package/scripts/_tmp_wire_ranker.py +13 -0
- package/scripts/_tmp_wire_shadow_timeline.py +45 -0
- package/scripts/anchor_retention.py +68 -0
- package/scripts/app_context.py +1160 -0
- package/scripts/astrbot_plugin_lingshu/CHECKSUMS.json +38 -22
- package/scripts/astrbot_plugin_lingshu/engine/CHANGELOG.md +4281 -4173
- package/scripts/astrbot_plugin_lingshu/engine/README.md +1584 -1577
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-lite.md +59 -59
- package/scripts/astrbot_plugin_lingshu/engine/SKILL-tiny.md +38 -38
- package/scripts/astrbot_plugin_lingshu/engine/SKILL.md +356 -317
- package/scripts/astrbot_plugin_lingshu/engine/assets/panel.html +6753 -5698
- package/scripts/astrbot_plugin_lingshu/engine/docs/commands.md +278 -247
- package/scripts/astrbot_plugin_lingshu/engine/docs/mechanics.md +610 -610
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_sync_trae_cn.py +102 -34
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s10.py +54 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s11.py +61 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s12.py +66 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s13.py +69 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s14.py +80 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_add_s9.py +68 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cache_load.py +82 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_clean_market.py +40 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_clean_pruned.py +81 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cleanup_docs.py +39 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_cmp_ranker.py +17 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_dolater_note.py +35 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_dust_why.py +27 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_explicit_import.py +40 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction.py +35 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction2.py +63 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction3.py +51 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_extract_compaction4.py +54 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_finalize_s14.py +39 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_find_compaction.py +43 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_b4.py +22 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_cli76.py +26 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs.py +38 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs_b.py +46 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_docs_b2.py +22 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_i3.py +23 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s10.py +83 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s11.py +14 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_s9_status.py +19 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_shadow_sim.py +37 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_fix_traits_value.py +41 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_import_idem.py +106 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_log_ack.py +45 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_batch.py +28 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_batch2.py +32 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_dolater.py +26 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_mark_dolater2.py +31 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_move_self.py +16 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_occ_cli.py +22 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_occ_link.py +108 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_optimize_recall.py +54 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_panel_audit.py +26 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_batch3.py +65 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_rrf.py +46 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s2s3.py +80 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s4.py +39 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s7.py +43 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_s8.py +91 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_patch_skill.py +17 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_release_guard.py +57 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_rerank_breaker.py +62 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_s16.py +41 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_scan_asar.py +41 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_scan_asar2.py +37 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_struct_docs.py +49 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sum_fallback.py +42 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sweep.py +81 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sync_check.py +69 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_sync_tail.py +39 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_todo_clean.py +67 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_verify_copy.py +17 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_extras.py +93 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_hsum.py +34 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_occ_b5.py +40 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_ranker.py +13 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/_tmp_wire_shadow_timeline.py +45 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/anchor_retention.py +68 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/app_context.py +1160 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/bigfive.py +90 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/brain.py +1 -1
- package/scripts/astrbot_plugin_lingshu/engine/scripts/check_docs.py +191 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/cli.py +940 -88
- package/scripts/astrbot_plugin_lingshu/engine/scripts/core.py +2468 -2406
- package/scripts/astrbot_plugin_lingshu/engine/scripts/coverage_report.py +5 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/delivery.py +112 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/dream.py +41 -3
- package/scripts/astrbot_plugin_lingshu/engine/scripts/emotion.py +202 -23
- package/scripts/astrbot_plugin_lingshu/engine/scripts/gap_memory.py +186 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/growth.py +72 -8
- package/scripts/astrbot_plugin_lingshu/engine/scripts/hsum.py +206 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/mem_score.py +92 -7
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory.py +533 -60
- package/scripts/astrbot_plugin_lingshu/engine/scripts/memory_extras.py +200 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/occ.py +190 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/panel_server.py +232 -142
- package/scripts/astrbot_plugin_lingshu/engine/scripts/persona.py +2498 -2349
- package/scripts/astrbot_plugin_lingshu/engine/scripts/prepublish_tests.py +90 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/release.py +326 -287
- package/scripts/astrbot_plugin_lingshu/engine/scripts/rss_ingest.py +181 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/session_import.py +832 -764
- package/scripts/astrbot_plugin_lingshu/engine/scripts/shadow_memory.py +173 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/style_check.py +220 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/summarizer.py +343 -252
- package/scripts/astrbot_plugin_lingshu/engine/scripts/timeline.py +118 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/watchdog.py +110 -0
- package/scripts/astrbot_plugin_lingshu/engine/scripts/web_research.py +125 -0
- package/scripts/bigfive.py +90 -0
- package/scripts/brain.py +1 -1
- package/scripts/check_docs.py +191 -0
- package/scripts/cli.py +940 -88
- package/scripts/core.py +2468 -2406
- package/scripts/coverage_report.py +5 -0
- package/scripts/delivery.py +112 -0
- package/scripts/dream.py +41 -3
- package/scripts/emotion.py +202 -23
- package/scripts/gap_memory.py +186 -0
- package/scripts/growth.py +72 -8
- package/scripts/hsum.py +206 -0
- package/scripts/mem_score.py +92 -7
- package/scripts/memory.py +533 -60
- package/scripts/memory_extras.py +200 -0
- package/scripts/occ.py +190 -0
- package/scripts/panel_server.py +232 -142
- package/scripts/persona.py +2498 -2349
- package/scripts/prepublish_tests.py +90 -0
- package/scripts/release.py +326 -287
- package/scripts/rss_ingest.py +181 -0
- package/scripts/run_tests.py +13 -0
- package/scripts/session_import.py +832 -764
- package/scripts/shadow_memory.py +173 -0
- package/scripts/style_check.py +220 -0
- package/scripts/summarizer.py +343 -252
- package/scripts/timeline.py +118 -0
- package/scripts/update_dsh_copy.ps1 +110 -107
- package/scripts/watchdog.py +110 -0
- package/scripts/web_research.py +125 -0
- package/docs//345/256/241/346/240/270/346/224/271/350/277/233/345/276/205/345/212/236.md +0 -370
|
@@ -1,252 +1,343 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
# -*- coding: utf-8 -*-
|
|
3
|
-
"""会话摘要层(附录 C · P2)——五段式摘要 + 校验 + fail-open。
|
|
4
|
-
|
|
5
|
-
设计要点(照附录 C 与 billion-context 的教训):
|
|
6
|
-
1. **五段固定结构**:目标 / 已做 / 未决 / 约束 / 原话引用。其中「原话引用」必须逐字保留,
|
|
7
|
-
它是摘要漂移时的纠错锚。
|
|
8
|
-
2. **外部便宜模型可选**:配 `config.summary`(OpenAI 兼容 /chat/completions)就走模型;
|
|
9
|
-
没配、超时、报错、输出不合格 → 一律**回退到离线抽取式摘要**,绝不阻塞主流程(fail-open)。
|
|
10
|
-
3. **提交前校验**:长度上限 + 五个小标题齐全 + 不许整段回显 prompt / 代码块。
|
|
11
|
-
4. 纯标准库;模型调用用 urllib,可注入 `call` 便于测试(不联网也能测全部分支)。
|
|
12
|
-
|
|
13
|
-
CLI(在 cli.py 里挂 `summarize`):
|
|
14
|
-
brain.py summarize --input turns.jsonl [--json] [--max-chars 1500]
|
|
15
|
-
"""
|
|
16
|
-
from __future__ import annotations
|
|
17
|
-
|
|
18
|
-
import json
|
|
19
|
-
import math
|
|
20
|
-
import os
|
|
21
|
-
import re
|
|
22
|
-
import urllib.request
|
|
23
|
-
|
|
24
|
-
HEADERS = ("目标", "已做", "未决", "约束", "原话引用")
|
|
25
|
-
DEFAULT_MAX_CHARS = 1500
|
|
26
|
-
|
|
27
|
-
TEMPLATE = """你是会话摘要器。把下面的对话压成固定五段,供下一轮上下文使用。
|
|
28
|
-
|
|
29
|
-
必须严格输出这五个小标题(顺序不变),每段 1-3 行:
|
|
30
|
-
## 目标
|
|
31
|
-
(用户想要什么;可引用一句原话)
|
|
32
|
-
## 已做
|
|
33
|
-
(已经完成/确认的事实,带路径或命令)
|
|
34
|
-
## 未决
|
|
35
|
-
(还没定的问题、待办、阻塞)
|
|
36
|
-
## 约束
|
|
37
|
-
(用户明确说过的限制:风格、技术栈、不要做什么)
|
|
38
|
-
## 原话引用
|
|
39
|
-
(最多 3 句必须逐字保留的用户原话:纠正、承诺、关键数字)
|
|
40
|
-
|
|
41
|
-
规则:
|
|
42
|
-
- 总长不超过 {max_chars} 字;不要复述本提示,不要输出代码块。
|
|
43
|
-
- 上一版摘要只作参考,发现冲突以最新对话为准。
|
|
44
|
-
|
|
45
|
-
{prev}
|
|
46
|
-
---- 对话 ----
|
|
47
|
-
{turns}
|
|
48
|
-
"""
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
# ---------------------------------------------------------------- 输入归一
|
|
52
|
-
|
|
53
|
-
def normalize_turns(raw) -> list[dict]:
|
|
54
|
-
"""接受 [{role,content}] / [{role,text}] / {"messages":[...]} / JSONL 行列表。"""
|
|
55
|
-
if isinstance(raw, dict):
|
|
56
|
-
raw = raw.get("messages") or raw.get("turns") or []
|
|
57
|
-
out = []
|
|
58
|
-
for item in raw or []:
|
|
59
|
-
if not isinstance(item, dict):
|
|
60
|
-
continue
|
|
61
|
-
role = str(item.get("role") or item.get("sender") or "other").lower()
|
|
62
|
-
if role in ("human", "me", "用户"):
|
|
63
|
-
role = "user"
|
|
64
|
-
elif role in ("ai", "bot", "model", "助手"):
|
|
65
|
-
role = "assistant"
|
|
66
|
-
text = item.get("content", item.get("text", item.get("message", "")))
|
|
67
|
-
if isinstance(text, list): # OpenAI content parts
|
|
68
|
-
text = " ".join(str(x.get("text") if isinstance(x, dict) else x) for x in text)
|
|
69
|
-
text = str(text or "").strip()
|
|
70
|
-
if text:
|
|
71
|
-
out.append({"role": role, "text": text})
|
|
72
|
-
return out
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
def load_turns(path) -> list[dict]:
|
|
76
|
-
"""读 .jsonl(每行一条)或 .json(数组 / {messages:[...]})。
|
|
77
|
-
|
|
78
|
-
上限保护:导出文件可能几百 MB(整个账号的聊天记录),全量读进内存会炸。
|
|
79
|
-
这里只读前 64MB / 20 万行,超出截断并继续——摘要本来也不需要全量。
|
|
80
|
-
"""
|
|
81
|
-
from pathlib import Path
|
|
82
|
-
p = Path(path)
|
|
83
|
-
MAX_BYTES = 64 * 1024 * 1024
|
|
84
|
-
MAX_LINES = 200_000
|
|
85
|
-
raw = p.read_bytes()
|
|
86
|
-
if len(raw) > MAX_BYTES:
|
|
87
|
-
raw = raw[:MAX_BYTES]
|
|
88
|
-
text = raw.decode("utf-8-sig", errors="replace")
|
|
89
|
-
if p.suffix.lower() == ".jsonl":
|
|
90
|
-
rows = []
|
|
91
|
-
for line in text.splitlines()[:MAX_LINES]:
|
|
92
|
-
line = line.strip()
|
|
93
|
-
if not line:
|
|
94
|
-
continue
|
|
95
|
-
try:
|
|
96
|
-
rows.append(json.loads(line))
|
|
97
|
-
except ValueError:
|
|
98
|
-
continue
|
|
99
|
-
return normalize_turns(rows)
|
|
100
|
-
return normalize_turns(json.loads(text))
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
# ---------------------------------------------------------------- 五段校验
|
|
104
|
-
|
|
105
|
-
def validate(text: str, max_chars: int = DEFAULT_MAX_CHARS) -> tuple[bool, str]:
|
|
106
|
-
"""提交前校验:长度、五个小标题、拒绝回显提示/代码块。"""
|
|
107
|
-
t = str(text or "").strip()
|
|
108
|
-
if not t:
|
|
109
|
-
return False, "空摘要"
|
|
110
|
-
if len(t) > max_chars:
|
|
111
|
-
return False, f"超长:{len(t)} > {max_chars}"
|
|
112
|
-
missing = [h for h in HEADERS if f"## {h}" not in t]
|
|
113
|
-
if missing:
|
|
114
|
-
return False, "缺小标题:" + "、".join(missing)
|
|
115
|
-
if "```" in t:
|
|
116
|
-
return False, "包含代码块"
|
|
117
|
-
if "规则:" in t and "上一版摘要" in t:
|
|
118
|
-
return False, "疑似回显提示词"
|
|
119
|
-
return True, ""
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
# ---------------------------------------------------------------- 离线抽取式(fail-open 兜底)
|
|
123
|
-
|
|
124
|
-
_KEY = re.compile(r"不对|不是|改成|记住|务必|不要|必须|只能|预算|注意|风险|TODO|待办|未决|下次|明天")
|
|
125
|
-
_QUOTE = re.compile(r"不对|不是|改成|记住|务必|别|不要|必须")
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
def _clip(s: str, n: int = 120) -> str:
|
|
129
|
-
s = re.sub(r"\s+", " ", str(s or "")).strip()
|
|
130
|
-
return s if len(s) <= n else s[: n - 1] + "…"
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
def
|
|
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
|
-
return
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
if not
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
if
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
text
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# -*- coding: utf-8 -*-
|
|
3
|
+
"""会话摘要层(附录 C · P2)——五段式摘要 + 校验 + fail-open。
|
|
4
|
+
|
|
5
|
+
设计要点(照附录 C 与 billion-context 的教训):
|
|
6
|
+
1. **五段固定结构**:目标 / 已做 / 未决 / 约束 / 原话引用。其中「原话引用」必须逐字保留,
|
|
7
|
+
它是摘要漂移时的纠错锚。
|
|
8
|
+
2. **外部便宜模型可选**:配 `config.summary`(OpenAI 兼容 /chat/completions)就走模型;
|
|
9
|
+
没配、超时、报错、输出不合格 → 一律**回退到离线抽取式摘要**,绝不阻塞主流程(fail-open)。
|
|
10
|
+
3. **提交前校验**:长度上限 + 五个小标题齐全 + 不许整段回显 prompt / 代码块。
|
|
11
|
+
4. 纯标准库;模型调用用 urllib,可注入 `call` 便于测试(不联网也能测全部分支)。
|
|
12
|
+
|
|
13
|
+
CLI(在 cli.py 里挂 `summarize`):
|
|
14
|
+
brain.py summarize --input turns.jsonl [--json] [--max-chars 1500]
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import math
|
|
20
|
+
import os
|
|
21
|
+
import re
|
|
22
|
+
import urllib.request
|
|
23
|
+
|
|
24
|
+
HEADERS = ("目标", "已做", "未决", "约束", "原话引用")
|
|
25
|
+
DEFAULT_MAX_CHARS = 1500
|
|
26
|
+
|
|
27
|
+
TEMPLATE = """你是会话摘要器。把下面的对话压成固定五段,供下一轮上下文使用。
|
|
28
|
+
|
|
29
|
+
必须严格输出这五个小标题(顺序不变),每段 1-3 行:
|
|
30
|
+
## 目标
|
|
31
|
+
(用户想要什么;可引用一句原话)
|
|
32
|
+
## 已做
|
|
33
|
+
(已经完成/确认的事实,带路径或命令)
|
|
34
|
+
## 未决
|
|
35
|
+
(还没定的问题、待办、阻塞)
|
|
36
|
+
## 约束
|
|
37
|
+
(用户明确说过的限制:风格、技术栈、不要做什么)
|
|
38
|
+
## 原话引用
|
|
39
|
+
(最多 3 句必须逐字保留的用户原话:纠正、承诺、关键数字)
|
|
40
|
+
|
|
41
|
+
规则:
|
|
42
|
+
- 总长不超过 {max_chars} 字;不要复述本提示,不要输出代码块。
|
|
43
|
+
- 上一版摘要只作参考,发现冲突以最新对话为准。
|
|
44
|
+
|
|
45
|
+
{prev}
|
|
46
|
+
---- 对话 ----
|
|
47
|
+
{turns}
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# ---------------------------------------------------------------- 输入归一
|
|
52
|
+
|
|
53
|
+
def normalize_turns(raw) -> list[dict]:
|
|
54
|
+
"""接受 [{role,content}] / [{role,text}] / {"messages":[...]} / JSONL 行列表。"""
|
|
55
|
+
if isinstance(raw, dict):
|
|
56
|
+
raw = raw.get("messages") or raw.get("turns") or []
|
|
57
|
+
out = []
|
|
58
|
+
for item in raw or []:
|
|
59
|
+
if not isinstance(item, dict):
|
|
60
|
+
continue
|
|
61
|
+
role = str(item.get("role") or item.get("sender") or "other").lower()
|
|
62
|
+
if role in ("human", "me", "用户"):
|
|
63
|
+
role = "user"
|
|
64
|
+
elif role in ("ai", "bot", "model", "助手"):
|
|
65
|
+
role = "assistant"
|
|
66
|
+
text = item.get("content", item.get("text", item.get("message", "")))
|
|
67
|
+
if isinstance(text, list): # OpenAI content parts
|
|
68
|
+
text = " ".join(str(x.get("text") if isinstance(x, dict) else x) for x in text)
|
|
69
|
+
text = str(text or "").strip()
|
|
70
|
+
if text:
|
|
71
|
+
out.append({"role": role, "text": text})
|
|
72
|
+
return out
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def load_turns(path) -> list[dict]:
|
|
76
|
+
"""读 .jsonl(每行一条)或 .json(数组 / {messages:[...]})。
|
|
77
|
+
|
|
78
|
+
上限保护:导出文件可能几百 MB(整个账号的聊天记录),全量读进内存会炸。
|
|
79
|
+
这里只读前 64MB / 20 万行,超出截断并继续——摘要本来也不需要全量。
|
|
80
|
+
"""
|
|
81
|
+
from pathlib import Path
|
|
82
|
+
p = Path(path)
|
|
83
|
+
MAX_BYTES = 64 * 1024 * 1024
|
|
84
|
+
MAX_LINES = 200_000
|
|
85
|
+
raw = p.read_bytes()
|
|
86
|
+
if len(raw) > MAX_BYTES:
|
|
87
|
+
raw = raw[:MAX_BYTES]
|
|
88
|
+
text = raw.decode("utf-8-sig", errors="replace")
|
|
89
|
+
if p.suffix.lower() == ".jsonl":
|
|
90
|
+
rows = []
|
|
91
|
+
for line in text.splitlines()[:MAX_LINES]:
|
|
92
|
+
line = line.strip()
|
|
93
|
+
if not line:
|
|
94
|
+
continue
|
|
95
|
+
try:
|
|
96
|
+
rows.append(json.loads(line))
|
|
97
|
+
except ValueError:
|
|
98
|
+
continue
|
|
99
|
+
return normalize_turns(rows)
|
|
100
|
+
return normalize_turns(json.loads(text))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# ---------------------------------------------------------------- 五段校验
|
|
104
|
+
|
|
105
|
+
def validate(text: str, max_chars: int = DEFAULT_MAX_CHARS) -> tuple[bool, str]:
|
|
106
|
+
"""提交前校验:长度、五个小标题、拒绝回显提示/代码块。"""
|
|
107
|
+
t = str(text or "").strip()
|
|
108
|
+
if not t:
|
|
109
|
+
return False, "空摘要"
|
|
110
|
+
if len(t) > max_chars:
|
|
111
|
+
return False, f"超长:{len(t)} > {max_chars}"
|
|
112
|
+
missing = [h for h in HEADERS if f"## {h}" not in t]
|
|
113
|
+
if missing:
|
|
114
|
+
return False, "缺小标题:" + "、".join(missing)
|
|
115
|
+
if "```" in t:
|
|
116
|
+
return False, "包含代码块"
|
|
117
|
+
if "规则:" in t and "上一版摘要" in t:
|
|
118
|
+
return False, "疑似回显提示词"
|
|
119
|
+
return True, ""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# ---------------------------------------------------------------- 离线抽取式(fail-open 兜底)
|
|
123
|
+
|
|
124
|
+
_KEY = re.compile(r"不对|不是|改成|记住|务必|不要|必须|只能|预算|注意|风险|TODO|待办|未决|下次|明天")
|
|
125
|
+
_QUOTE = re.compile(r"不对|不是|改成|记住|务必|别|不要|必须")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _clip(s: str, n: int = 120) -> str:
|
|
129
|
+
s = re.sub(r"\s+", " ", str(s or "")).strip()
|
|
130
|
+
return s if len(s) <= n else s[: n - 1] + "…"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def textrank_top(texts: list, n: int = 3, iters: int = 20, d: float = 0.85) -> list:
|
|
134
|
+
"""TextRank 选"最中心"的句子(§2 do-later)。
|
|
135
|
+
|
|
136
|
+
为什么需要:位置启发式只看"最后 3 条"——一句"预算只有 3 天"如果不在末尾就丢了。
|
|
137
|
+
TextRank 按句子间的词重叠建图、迭代算中心性,**位置无关**,更能捞出全篇要点。
|
|
138
|
+
|
|
139
|
+
只用标准库;相似度取 term 的 jaccard;PageRank 迭代 20 次。
|
|
140
|
+
任何异常都退回"原顺序前 n 条",绝不抛。
|
|
141
|
+
"""
|
|
142
|
+
try:
|
|
143
|
+
from mem_score import jaccard as _jac, terms as _terms
|
|
144
|
+
sents = []
|
|
145
|
+
for t in texts or []:
|
|
146
|
+
for s in re.split(r"[。!?!?\n]+", str(t or "")):
|
|
147
|
+
s = s.strip()
|
|
148
|
+
if len(s) >= 8:
|
|
149
|
+
sents.append(s)
|
|
150
|
+
if not sents:
|
|
151
|
+
return []
|
|
152
|
+
if len(sents) <= n:
|
|
153
|
+
return sents
|
|
154
|
+
ts = [_terms(s) for s in sents]
|
|
155
|
+
m = len(sents)
|
|
156
|
+
score = [1.0 / m] * m
|
|
157
|
+
for _ in range(iters):
|
|
158
|
+
new = [0.0] * m
|
|
159
|
+
for i in range(m):
|
|
160
|
+
acc = 0.0
|
|
161
|
+
for j in range(m):
|
|
162
|
+
if i == j:
|
|
163
|
+
continue
|
|
164
|
+
sim = _jac(ts[i], ts[j])
|
|
165
|
+
if sim > 0:
|
|
166
|
+
out_sum = sum(_jac(ts[k], ts[j]) for k in range(m) if k != j) or 1.0
|
|
167
|
+
acc += sim / out_sum * score[j]
|
|
168
|
+
new[i] = (1 - d) / m + d * acc
|
|
169
|
+
score = new
|
|
170
|
+
order = sorted(range(m), key=lambda i: -score[i])
|
|
171
|
+
return [sents[i] for i in order[:n]]
|
|
172
|
+
except Exception:
|
|
173
|
+
out = [s.strip() for t in (texts or [])
|
|
174
|
+
for s in re.split(r"[。!?!?\n]+", str(t or "")) if s.strip()]
|
|
175
|
+
return out[:n]
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def extractive_fallback(turns: list[dict], max_chars: int = DEFAULT_MAX_CHARS,
|
|
179
|
+
ranker: str = "position") -> str:
|
|
180
|
+
"""不调模型的确定性摘要:只挑明确信号,不编造。
|
|
181
|
+
|
|
182
|
+
`ranker="textrank"` 时,"已做"段不再取最后 3 条,而是用 TextRank 挑全篇最中心的句子
|
|
183
|
+
(避免"预算只有 3 天"这类关键句因为不在末尾而被丢掉)。默认仍走位置启发式。
|
|
184
|
+
"""
|
|
185
|
+
users = [t["text"] for t in turns if t["role"] == "user"]
|
|
186
|
+
bots = [t["text"] for t in turns if t["role"] == "assistant"]
|
|
187
|
+
goal = _clip(users[0], 160) if users else "(没读到用户消息)"
|
|
188
|
+
# v5.34:同一句不允许在多个小节里重复出现。
|
|
189
|
+
# 实测症状:一段含"必须/不要"的大块会被 未决/约束/原话 三节同时抽中,
|
|
190
|
+
# 整份注入原样复制三遍,摘要等于没压。
|
|
191
|
+
used = {goal} if users else set()
|
|
192
|
+
|
|
193
|
+
def pick(cands, clip_n: int = 120) -> list[str]:
|
|
194
|
+
lines = []
|
|
195
|
+
for x in cands:
|
|
196
|
+
c = _clip(x, clip_n)
|
|
197
|
+
if not c or c in used:
|
|
198
|
+
continue
|
|
199
|
+
used.add(c)
|
|
200
|
+
lines.append(f"- {c}")
|
|
201
|
+
return lines
|
|
202
|
+
|
|
203
|
+
if ranker == "textrank":
|
|
204
|
+
_tops = textrank_top(bots, 3)
|
|
205
|
+
done = []
|
|
206
|
+
for s in _tops:
|
|
207
|
+
c = _clip(s, 120)
|
|
208
|
+
if c and c not in used:
|
|
209
|
+
used.add(c)
|
|
210
|
+
done.append(f"- {c}")
|
|
211
|
+
else:
|
|
212
|
+
done = pick([b for b in bots[-3:] if len(b) >= 8])
|
|
213
|
+
pending = pick([u for u in users[-3:] if _KEY.search(u)])[-3:]
|
|
214
|
+
constraints = pick([u for u in users
|
|
215
|
+
if re.search(r"不要|必须|只能|务必|别", u)])[-3:]
|
|
216
|
+
quotes = pick([u for u in users if _QUOTE.search(u)], 80)[-3:]
|
|
217
|
+
|
|
218
|
+
# 兜底补段(v5.34 残余风险):离线抽取只认明确信号,实测"未决/约束/原话"经常空着。
|
|
219
|
+
# 空着比缺信息更糟——读摘要的人会以为"这轮确实没有未决"。这里用保守规则兜一层:
|
|
220
|
+
# 只把**已经存在的内容**换个角度呈现,不编造。
|
|
221
|
+
if not pending:
|
|
222
|
+
_rest_u = [u for u in users if _clip(u, 120) not in used]
|
|
223
|
+
if _rest_u:
|
|
224
|
+
pending = [f"- 待确认:{_clip(_rest_u[-1], 120)}"]
|
|
225
|
+
if not constraints:
|
|
226
|
+
_cue = re.compile(r"不要|必须|只能|务必|别|预算|期限|deadline|时间只|最多|最少", re.I)
|
|
227
|
+
_c = [x for x in (users + bots) if _cue.search(x) and _clip(x, 120) not in used]
|
|
228
|
+
if _c:
|
|
229
|
+
constraints = [f"- {_clip(_c[-1], 120)}"]
|
|
230
|
+
if not quotes:
|
|
231
|
+
_rest_q = [u for u in users if _clip(u, 80) not in used]
|
|
232
|
+
if _rest_q:
|
|
233
|
+
quotes = [f"- 「{_clip(_rest_q[-1], 80)}」"]
|
|
234
|
+
|
|
235
|
+
def block(title: str, lines: list[str], empty: str) -> str:
|
|
236
|
+
body = "\n".join(lines) if lines else empty
|
|
237
|
+
return f"## {title}\n{body}"
|
|
238
|
+
|
|
239
|
+
text = "\n".join([
|
|
240
|
+
block("目标", ([f"- {goal}"] if goal else []), "- (未提取到)"),
|
|
241
|
+
block("已做", done, "- (本轮没有助手产出)"),
|
|
242
|
+
block("未决", pending, "- (本轮没有明显未决)"),
|
|
243
|
+
block("约束", constraints, "- (本轮没有明显约束)"),
|
|
244
|
+
block("原话引用", quotes, "- (本轮没有引号原话)"),
|
|
245
|
+
])
|
|
246
|
+
if len(text) > max_chars:
|
|
247
|
+
text = text[: max_chars - 1].rstrip() + "…"
|
|
248
|
+
return text
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
# ---------------------------------------------------------------- 模型调用(可选)
|
|
252
|
+
|
|
253
|
+
def _cfg_section(cfg: dict | None) -> dict:
|
|
254
|
+
if cfg is not None:
|
|
255
|
+
return dict(cfg.get("summary") or {})
|
|
256
|
+
try:
|
|
257
|
+
import core
|
|
258
|
+
return dict((core.load_config() or {}).get("summary") or {})
|
|
259
|
+
except Exception:
|
|
260
|
+
return {}
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def openai_chat(prompt: str, cfg: dict, timeout: float | None = None) -> str | None:
|
|
264
|
+
"""OpenAI 兼容 /chat/completions;任何失败返回 None(由上层 fail-open)。"""
|
|
265
|
+
base = str(cfg.get("base_url") or "").rstrip("/")
|
|
266
|
+
model = str(cfg.get("model") or "")
|
|
267
|
+
if not base or not model:
|
|
268
|
+
return None
|
|
269
|
+
key_env = str(cfg.get("api_key_env") or "")
|
|
270
|
+
api_key = os.environ.get(key_env, "") if key_env else ""
|
|
271
|
+
body = json.dumps({
|
|
272
|
+
"model": model,
|
|
273
|
+
"temperature": 0.2,
|
|
274
|
+
"messages": [{"role": "user", "content": prompt}],
|
|
275
|
+
}).encode("utf-8")
|
|
276
|
+
url = base if base.endswith("/chat/completions") else base + "/chat/completions"
|
|
277
|
+
req = urllib.request.Request(url, data=body, method="POST",
|
|
278
|
+
headers={"Content-Type": "application/json",
|
|
279
|
+
**({"Authorization": f"Bearer {api_key}"} if api_key else {})})
|
|
280
|
+
try:
|
|
281
|
+
with urllib.request.urlopen(req, timeout=timeout or float(cfg.get("timeout") or 30)) as r:
|
|
282
|
+
data = json.loads(r.read().decode("utf-8", "replace"))
|
|
283
|
+
content = (((data.get("choices") or [{}])[0]).get("message") or {}).get("content")
|
|
284
|
+
return str(content or "").strip() or None
|
|
285
|
+
except Exception as exc: # noqa: BLE001
|
|
286
|
+
try:
|
|
287
|
+
import failures
|
|
288
|
+
failures.record("summary.model", f"{type(exc).__name__}: {exc}",
|
|
289
|
+
ctx={"base_url": base, "model": model})
|
|
290
|
+
except Exception:
|
|
291
|
+
pass
|
|
292
|
+
return None
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
# ---------------------------------------------------------------- 主入口
|
|
296
|
+
|
|
297
|
+
def build_prompt(turns: list[dict], prev_summary: str = "", max_chars: int = DEFAULT_MAX_CHARS) -> str:
|
|
298
|
+
lines = []
|
|
299
|
+
for t in turns:
|
|
300
|
+
who = "用户" if t["role"] == "user" else ("我" if t["role"] == "assistant" else "其他")
|
|
301
|
+
lines.append(f"{who}: {t['text']}")
|
|
302
|
+
prev = f"上一版摘要:\n{prev_summary.strip()}\n" if prev_summary and prev_summary.strip() else ""
|
|
303
|
+
return TEMPLATE.format(max_chars=max_chars, prev=prev, turns="\n".join(lines))
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def summarize(turns: list[dict], *, cfg: dict | None = None, prev_summary: str = "",
|
|
307
|
+
max_chars: int = DEFAULT_MAX_CHARS, call=None) -> dict:
|
|
308
|
+
"""生成五段摘要:模型优先,失败/不合格一律回退抽取式。
|
|
309
|
+
|
|
310
|
+
返回 {text, source: 'model'|'fallback', actions:[...], warnings:[...], chars}
|
|
311
|
+
"""
|
|
312
|
+
turns = normalize_turns(turns)
|
|
313
|
+
actions: list[str] = []
|
|
314
|
+
warnings: list[str] = []
|
|
315
|
+
sec = _cfg_section(cfg)
|
|
316
|
+
if not sec.get("enabled"):
|
|
317
|
+
actions.append("summary.enabled=false:走离线抽取式")
|
|
318
|
+
text = extractive_fallback(turns, max_chars, ranker=str(sec.get("ranker") or "position"))
|
|
319
|
+
return {"text": text, "source": "fallback", "actions": actions,
|
|
320
|
+
"warnings": warnings, "chars": len(text)}
|
|
321
|
+
|
|
322
|
+
prompt = build_prompt(turns, prev_summary, max_chars)
|
|
323
|
+
caller = call or (lambda p: openai_chat(p, sec))
|
|
324
|
+
try:
|
|
325
|
+
text = caller(prompt)
|
|
326
|
+
except Exception as exc: # noqa: BLE001
|
|
327
|
+
text = None
|
|
328
|
+
warnings.append(f"模型调用异常:{exc!r}")
|
|
329
|
+
if text:
|
|
330
|
+
ok, why = validate(text, max_chars)
|
|
331
|
+
if ok:
|
|
332
|
+
return {"text": text, "source": "model", "actions": actions,
|
|
333
|
+
"warnings": warnings, "chars": len(text)}
|
|
334
|
+
warnings.append(f"模型输出不合格({why}),回退离线摘要")
|
|
335
|
+
else:
|
|
336
|
+
warnings.append("模型调用失败,回退离线摘要")
|
|
337
|
+
text = extractive_fallback(turns, max_chars, ranker=str(sec.get("ranker") or "position"))
|
|
338
|
+
return {"text": text, "source": "fallback", "actions": actions,
|
|
339
|
+
"warnings": warnings, "chars": len(text)}
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def estimate_tokens(text: str, chars_per_token: int = 2) -> int:
|
|
343
|
+
return int(math.ceil(len(text or "") / max(1, chars_per_token)))
|