@furongjun1999/dsh-memory 0.9.8 → 0.9.9

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.
Files changed (56) hide show
  1. package/README.md +1 -1
  2. package/codebuddy/CODEBUDDY.md +4 -0
  3. package/docs/README.md +3 -0
  4. package/docs//350/247/204/350/214/203/AI/347/274/226/347/250/213/351/200/232/347/224/250/350/247/204/350/214/203.md +4 -0
  5. package/dsh/cordis.yml.example +2 -2
  6. package/lib/hooks.d.ts +11 -1
  7. package/lib/hooks.js +58 -3
  8. package/lib/index.d.ts +1 -1
  9. package/lib/index.js +2 -2
  10. package/lib/init.js +11 -2
  11. package/lib/lib/hook_audit.d.ts +3 -0
  12. package/lib/lib/hook_audit.js +37 -0
  13. package/md_cg/autonomy.py +1 -1
  14. package/md_cg/config_registry.py +329 -329
  15. package/md_cg/config_registry_bulk.py +483 -482
  16. package/md_cg/config_render.py +27 -0
  17. package/md_cg/config_validate.py +456 -455
  18. package/md_cg/conflict_surface.py +127 -0
  19. package/md_cg/mcp_server.py +5324 -5227
  20. package/md_cg/mdcg.py +12 -1
  21. package/md_cg/mdcos.py +7159 -7108
  22. package/md_cg/pooling.py +487 -485
  23. package/md_cg/qmd_llm.py +334 -334
  24. package/md_cg/reach.py +10 -4
  25. package/md_cg/sleep.py +2 -2
  26. package/md_cg/sustain.py +3 -3
  27. package/md_cg/test_auto_defaults.py +463 -463
  28. package/md_cg/test_autonomy_emotion.py +328 -328
  29. package/md_cg/test_bm25_default.py +56 -0
  30. package/md_cg/test_c3_transient_read_negative.py +7 -3
  31. package/md_cg/test_conflict_surface.py +75 -0
  32. package/md_cg/test_conflict_value_untrusted.py +63 -0
  33. package/md_cg/test_exact_text_cache.py +194 -191
  34. package/md_cg/test_hotcache_tool.py +121 -0
  35. package/md_cg/test_issue274_read_node_id_none.py +364 -341
  36. package/md_cg/test_issue561_pending_review.py +89 -5
  37. package/md_cg/test_issue578_service_info_gate.py +264 -0
  38. package/md_cg/test_p3_legacy_closure.py +441 -438
  39. package/md_cg/test_p43_pooling.py +419 -412
  40. package/md_cg/test_reach.py +5 -1
  41. package/md_cg/test_reach_exits.py +54 -0
  42. package/md_cg/test_reach_single_char.py +74 -0
  43. package/md_cg/test_search_bm25_default.py +60 -0
  44. package/md_cg/test_sleep_p1.py +1032 -1032
  45. package/md_cg/test_untrusted_audit.py +55 -0
  46. package/md_cg/test_untrusted_classifier.py +42 -0
  47. package/md_cg/test_untrusted_enforcement.py +66 -0
  48. package/md_cg/untrusted.py +45 -0
  49. package/md_cg/untrusted_audit.py +87 -0
  50. package/md_cg/value_conflict.py +71 -0
  51. package/package.json +7 -7
  52. package/src/hooks.ts +59 -5
  53. package/src/index.ts +2 -2
  54. package/src/init.ts +7 -2
  55. package/src/lib/hook_audit.ts +32 -0
  56. package/zcode/AGENTS.md +4 -0
package/md_cg/qmd_llm.py CHANGED
@@ -1,334 +1,334 @@
1
- # -*- coding: utf-8 -*-
2
- """QMD 的 LLM 接入:源图抽取、题面扩展、作答与判官调用 + 统一系统提示词 + 身份隔离缓存。
3
-
4
- 开关与配置(全部显式,无隐式回落)
5
- ----------------------------------
6
- · ``MDCG_QMD_SYS``:**只有取值恰为 "1"** 才给 extract / query / answer 三类调用带同一条
7
- 统一系统提示词 ``SYSTEM``;未设或其它任何取值 = 关,messages 只有一条 user(与原型不带系统
8
- 提示词的臂逐字相同)。**judge(判官)在任何取值下都不带 system**——保证与既有臂判分口径可比。
9
- · ``MDCG_QMD_LLM_BASE`` / ``MDCG_QMD_LLM_MODEL`` / ``MDCG_QMD_LLM_KEY``:OpenAI 兼容
10
- ``/chat/completions`` 的地址、模型、密钥,三者**缺一即抛 ``LLMUnavailable``**(点名缺哪个),
11
- 不发请求、不静默降级。刻意**不**回落 ``MDCG_LLM_KEY`` / ``DEEPSEEK_API_KEY``:QMD 的网关可能
12
- 与反思单元不同厂商,回落即凭证外泄(与 issue #96 同一立场)。
13
-
14
- 依据(白箱三问之一)
15
- --------------------
16
- · 原型:TanPowasd/LingShu-prime ``TanPowasd/agm/bench/hive_official.py``(``SYSTEM``、``chat``、
17
- ``parse_json``)、``TanPowasd/agm/confluence/qx.py``(题面扩展提示词与 ``clean``)、
18
- ``hive_extract.py`` / ``extract.py``(源图抽取提示词)。提示词文本逐字取自原型。
19
- · 原型审计 dsh-bounty#466:追问缓存未按系统提示词隔离、产物按臂名存在即复用 ⇒ 本模块的缓存键
20
- 含(角色、模型、地址、密钥摘要、max_tokens、实际发出的 system 文本、prompt),条目内另存身份并在
21
- 读出时逐项比对。密钥只以 sha256 摘要进身份,明文不写入任何缓存文件(PR #395 对抗复核补)。
22
-
23
- 生效条件(白箱三问之二)
24
- ------------------------
25
- · 只被显式调用时生效;本仓既有检索/写入路径不 import 本模块(守卫 ``md_cg/test_qmd.py`` P13)。
26
- · 网关返回体若外包一层 ``{"data": {...}}``(实测 Cline 网关如此)则解开;``choices`` 缺失、
27
- content 为空、``finish_reason == "length"`` 一律抛 ``RuntimeError``,不当作空答案。
28
-
29
- 错了怎么办 / 边界(白箱三问之三)
30
- --------------------------------
31
- · 抽取失败的批次会拆半重试到单条;仍失败的条目**原样列入返回的 missing**,由调用方决定;
32
- ``md_cg/qmd.py`` 拿到缺块源图会抛 ``PartialGraph``、缺题 hint 会抛 ``MissingHint``。
33
- · 无 LLM 时端到端增益不成立;本模块只提供调用面,不提供任何「无 key 替代」。
34
- """
35
- from __future__ import annotations
36
-
37
- import hashlib
38
- import json
39
- import os
40
- import re
41
- import urllib.error
42
- import urllib.request
43
-
44
- __all__ = ["SYSTEM", "SYS_ENV", "BASE_ENV", "MODEL_ENV", "KEY_ENV", "ROLES", "LLMUnavailable", "CacheIdentityError",
45
- "sys_on", "system_for", "messages", "config", "chat", "Cache", "call", "parse_json", "clean_hint",
46
- "query_prompt", "graph_prompt", "extract_hints", "extract_triples"]
47
-
48
- SYS_ENV = "MDCG_QMD_SYS"
49
- BASE_ENV = "MDCG_QMD_LLM_BASE"
50
- MODEL_ENV = "MDCG_QMD_LLM_MODEL"
51
- KEY_ENV = "MDCG_QMD_LLM_KEY"
52
- ROLES = ("extract", "query", "answer", "judge")
53
-
54
- SYSTEM = ("你是灵枢长期记忆系统里的一个组件,负责从给定材料中抽取、检索或回答。\n"
55
- "1. 只依据本次用户消息里给出的材料和问题工作,不使用材料以外的知识,不猜测,不编造。\n"
56
- "2. 人名、地名、物品名、日期、数字一律照原文逐字写,不改写、不意译。\n"
57
- "3. 问题有多个要点时逐点覆盖,不遗漏;材料里确实没有的,明确说没有,不要硬凑。\n"
58
- "4. 严格按要求的格式输出:要 JSON 就只输出一个 JSON 对象,不加代码块、不加解释。")
59
-
60
-
61
- class LLMUnavailable(RuntimeError):
62
- """QMD 的 LLM 配置不全(缺地址/模型/密钥)。显式边界:不发请求、不降级。"""
63
-
64
-
65
- class CacheIdentityError(RuntimeError):
66
- """缓存条目记录的身份与本次调用不一致(不复用、不覆盖)。"""
67
-
68
-
69
- # 生效条件:环境变量 MDCG_QMD_SYS 取值恰为 "1" 时返回 True,否则 False。
70
- def sys_on() -> bool:
71
- return os.environ.get(SYS_ENV) == "1"
72
-
73
-
74
- # 生效条件:role 为 judge 时恒返回 None;其余角色在 sys_on() 为真时返回 SYSTEM,否则 None;未知角色抛 ValueError。
75
- def system_for(role: str):
76
- if role not in ROLES:
77
- raise ValueError(f"未知角色 {role!r}(应为 {ROLES})")
78
- if role == "judge":
79
- return None
80
- return SYSTEM if sys_on() else None
81
-
82
-
83
- # 生效条件:给定 role 与 prompt,返回实际要发出的 messages 列表(system_for 非空时首条为 system)。
84
- def messages(role: str, prompt: str) -> list:
85
- s = system_for(role)
86
- return ([{"role": "system", "content": s}] if s else []) + [{"role": "user", "content": prompt}]
87
-
88
-
89
- # 生效条件:MDCG_QMD_LLM_BASE / MODEL / KEY 三个环境变量都为非空时返回 {"base","model","key"},任一缺失抛 LLMUnavailable 并点名。
90
- def config() -> dict:
91
- cfg = {"base": os.environ.get(BASE_ENV), "model": os.environ.get(MODEL_ENV), "key": os.environ.get(KEY_ENV)}
92
- miss = [n for n, k in ((BASE_ENV, "base"), (MODEL_ENV, "model"), (KEY_ENV, "key")) if not (cfg[k] or "").strip()]
93
- if miss:
94
- raise LLMUnavailable("QMD 的 LLM 未配置:缺 " + "、".join(miss) + "(不回落其它厂商的密钥变量)")
95
- return cfg
96
-
97
-
98
- # 生效条件:给定网关返回体 data,解开可选的 {"data": ...} 外包;choices 缺失、content 空或 finish_reason=="length" 时抛 RuntimeError,否则返回 content。
99
- def _content(data: dict) -> str:
100
- if "choices" not in data and isinstance(data.get("data"), dict):
101
- data = data["data"]
102
- ch = data.get("choices") or []
103
- if not ch:
104
- raise RuntimeError("LLM 响应无 choices:" + json.dumps(data, ensure_ascii=False)[:300])
105
- if ch[0].get("finish_reason") == "length":
106
- raise RuntimeError("LLM 输出被截断(finish_reason=length)")
107
- txt = (ch[0].get("message") or {}).get("content") or ""
108
- if not txt.strip():
109
- raise RuntimeError("LLM 返回空 content")
110
- return txt
111
-
112
-
113
- # 生效条件:给定 role、prompt(cfg 缺省时由 config() 解析,配置不全即抛 LLMUnavailable),向 base 的 /chat/completions 发一次 POST(temperature=0,max_tokens 仅在显式给出时传),经 _content 校验后返回文本;opener 供测试注入。
114
- def chat(role: str, prompt: str, cfg: dict = None, timeout: int = 300, max_tokens: int = None, opener=None) -> str:
115
- cfg = cfg or config()
116
- body = {"model": cfg["model"], "messages": messages(role, prompt), "temperature": 0}
117
- if max_tokens:
118
- body["max_tokens"] = max_tokens
119
- req = urllib.request.Request(cfg["base"].rstrip("/") + "/chat/completions", data=json.dumps(body).encode("utf-8"),
120
- headers={"Content-Type": "application/json", "Authorization": f"Bearer {cfg['key']}"})
121
- with (opener or urllib.request.urlopen)(req, timeout=timeout) as r:
122
- return _content(json.loads(r.read().decode("utf-8")))
123
-
124
-
125
- def _sha(s: str) -> str:
126
- return hashlib.sha256(s.encode("utf-8")).hexdigest()
127
-
128
-
129
- class Cache:
130
- """按调用身份隔离的结果缓存:一调用一文件,文件名 = 身份的 sha256。
131
-
132
- 身份 = (角色,模型,地址,密钥的 sha256,max_tokens(未给为 None),实际发出的 system 文本的 sha256 或 None,
133
- prompt 的 sha256)。密钥只存摘要,明文不落盘。
134
- 读出时把条目里存的身份与本次逐项比对,不一致抛 CacheIdentityError(不复用、不覆盖)。
135
- """
136
-
137
- def __init__(self, root):
138
- self.root = os.fspath(root)
139
- os.makedirs(self.root, exist_ok=True)
140
-
141
- # 生效条件:给定 role、prompt、cfg 与 max_tokens,返回身份字典;max_tokens 取假值时记 None(与 chat 不传该字段一致),密钥只记 sha256。
142
- @staticmethod
143
- def identity(role: str, prompt: str, cfg: dict, max_tokens: int = None) -> dict:
144
- s = system_for(role)
145
- return {"role": role, "model": cfg["model"], "base": cfg["base"], "key_sha": _sha(cfg["key"]),
146
- "max_tokens": max_tokens or None, "system_sha": _sha(s) if s else None, "prompt_sha": _sha(prompt)}
147
-
148
- # 生效条件:给定 identity 字典,返回其规范 JSON 的 sha256 作为缓存文件名主干。
149
- @staticmethod
150
- def key(ident: dict) -> str:
151
- return _sha(json.dumps(ident, ensure_ascii=False, sort_keys=True))
152
-
153
- def _path(self, ident):
154
- return os.path.join(self.root, self.key(ident) + ".json")
155
-
156
- # 生效条件:给定 role、prompt、cfg、max_tokens:缓存文件不存在返回 None;存在且条目身份与本次相同返回其文本;身份不同抛 CacheIdentityError。
157
- def get(self, role: str, prompt: str, cfg: dict, max_tokens: int = None):
158
- ident = self.identity(role, prompt, cfg, max_tokens)
159
- p = self._path(ident)
160
- if not os.path.exists(p):
161
- return None
162
- with open(p, encoding="utf-8") as f:
163
- d = json.load(f)
164
- if d.get("identity") != ident:
165
- raise CacheIdentityError(f"{p} 的身份 {d.get('identity')} ≠ 本次 {ident}")
166
- return d["text"]
167
-
168
- # 生效条件:给定 role、prompt、cfg、文本与 max_tokens,把 {"identity","text"} 写入身份对应的缓存文件。
169
- def put(self, role: str, prompt: str, cfg: dict, text: str, max_tokens: int = None) -> None:
170
- ident = self.identity(role, prompt, cfg, max_tokens)
171
- with open(self._path(ident), "w", encoding="utf-8") as f:
172
- json.dump({"identity": ident, "text": text}, f, ensure_ascii=False)
173
-
174
-
175
- # 生效条件:给定 role、prompt:cache 命中则返回缓存文本(counter 不变);否则调用 chat,结果写入 cache(若给)并给 counter["calls"] 加一后返回;kw 里的 max_tokens 同时进缓存身份。
176
- def call(role: str, prompt: str, cfg: dict = None, cache: Cache = None, counter: dict = None, **kw) -> str:
177
- cfg = cfg or config()
178
- mt = kw.get("max_tokens")
179
- if cache is not None:
180
- hit = cache.get(role, prompt, cfg, mt)
181
- if hit is not None:
182
- return hit
183
- if counter is not None:
184
- counter["calls"] = counter.get("calls", 0) + 1
185
- txt = chat(role, prompt, cfg=cfg, **kw)
186
- if cache is not None:
187
- cache.put(role, prompt, cfg, txt, mt)
188
- return txt
189
-
190
-
191
- # 生效条件:给定模型输出文本,剥掉首尾代码围栏后取首个 "{" 到末个 "}" 之间解析为 JSON 返回;解析失败抛 ValueError。
192
- def parse_json(txt: str):
193
- t = re.sub(r"^```(?:json)?|```$", "", txt.strip(), flags=re.M).strip()
194
- i, j = t.find("{"), t.rfind("}")
195
- return json.loads(t[i:j + 1])
196
-
197
-
198
- # 生效条件:给定一题的原始抽取结果 v:非字典或 ents/preds 皆空返回 None;否则返回字段裁成字符串(ents/preds/kw 各至多 8 条、hyde 至多 300 字、time 空值归 None)的规范字典。
199
- def clean_hint(v):
200
- if not isinstance(v, dict):
201
- return None
202
- L = lambda x: [str(s).strip() for s in (x if isinstance(x, list) else [x] if x else []) if str(s).strip()][:8] # noqa: E731
203
- ents, preds = L(v.get("ents")), L(v.get("preds"))
204
- if not ents and not preds:
205
- return None
206
- t = v.get("time")
207
- return {"ents": ents, "preds": preds, "time": str(t).strip() if t not in (None, "", "null") else None,
208
- "kw": L(v.get("kw")), "hyde": str(v.get("hyde") or "").strip()[:300]}
209
-
210
-
211
- Q_EN = """You prepare search queries for a memory system over a long chat history between two people.
212
- For EACH question, output:
213
- - "ents": the people, objects, places, events, activities it asks about, written as they would appear in the chat (short noun phrases; resolve "she/he" only if the question names them);
214
- - "preds": the relation or action asked about, as short verb phrases, plus 1-2 likely paraphrases;
215
- - "time": the time constraint if any ("last year", "May 2023", "before the move"), else null;
216
- - "kw": 3-6 extra keywords a matching chat line would likely contain (synonyms, related concrete words);
217
- - "hyde": one short sentence, as the speaker might have said it in the chat, that would answer the question (invent plausible specifics; it is only used for search).
218
- Output ONLY JSON: {{"q": {{"<id>": {{"ents": [...], "preds": [...], "time": null, "kw": [...], "hyde": "..."}}, ...}}}}
219
-
220
- Questions:
221
- {qs}"""
222
-
223
- Q_ZH = """你在为一个检索中文小说正文的记忆系统准备检索式。对下面每道题,输出:
224
- - "ents":题目问到的人物、物品、地点、事件,用小说原文里可能出现的写法(人名写全名,也给常见称呼);
225
- - "preds":题目问的关系或动作,短动词短语,并给 1-2 个近义说法;
226
- - "time":题中的时间约束(如“第三天夜里”“事发前”),没有就 null;
227
- - "kw":3-6 个命中的原文句子里很可能出现的词(近义词、相关具体词);
228
- - "hyde":一句像小说原文的假想句子,能回答本题(细节可以编,只用于检索)。
229
- 只输出 JSON:{{"q": {{"<题号>": {{"ents": [...], "preds": [...], "time": null, "kw": [...], "hyde": "..."}}, ...}}}}
230
-
231
- 题目:
232
- {qs}"""
233
-
234
- G_EN = """You convert dialogue turns into a knowledge graph. For EACH turn below, list its facts as
235
- [subject, predicate, object] triples.
236
- Rules:
237
- - Replace pronouns (I, me, my, you, she, we, it...) with the concrete name they refer to; "I" is the speaker.
238
- - Keep entity names short and as written (e.g. "Caroline", "LGBTQ support group", "pottery class").
239
- - Predicates are short verb phrases ("attended", "plans to", "is", "painted", "felt").
240
- - Add a date/time only if the turn states one, as a triple [event, "when", time].
241
- - Include facts from [image: ...] captions as things the speaker shared.
242
- - A turn with no factual content gets [].
243
- Output ONLY JSON: {{"turns": {{"<turn id>": [[s,p,o], ...], ...}}}}
244
-
245
- Turns:
246
- {turns}"""
247
-
248
- G_ZH = """你要把小说正文片段转成知识图谱。对下面每个片段,列出其中的事实,格式为 [主语, 谓语, 宾语] 三元组。
249
- 规则:
250
- - 代词(他、她、它、我们、这……)一律换成它指代的具体人名或事物名。
251
- - 实体名保持简短、照原文写法(人名、地名、物品、组织、事件)。
252
- - 谓语是简短的动词短语(“交给”“怀疑”“住在”“是”“答应”)。
253
- - 原文写了时间、原因、条件时,用 [事件, "时间"/"原因"/"条件", 内容] 表示。
254
- - 没有事实的片段给 []。
255
- 只输出 JSON:{{"chunks": {{"<片段编号>": [[主,谓,宾], ...], ...}}}}
256
-
257
- 片段:
258
- {chunks}"""
259
-
260
-
261
- # 生效条件:给定 [(题号, 问题)] 与 lang("zh"/"en"),返回题面扩展提示词(与原型 qx.py 逐字相同)。
262
- def query_prompt(items, lang: str) -> str:
263
- return (Q_ZH if lang == "zh" else Q_EN).format(qs="\n".join(f"[{i}] {q}" for i, q in items))
264
-
265
-
266
- # 生效条件:给定 [(编号, 文本)] 与 lang,返回源图抽取提示词(zh 与原型 hive_extract.py、en 与 extract.py 逐字相同)。
267
- def graph_prompt(items, lang: str) -> str:
268
- if lang == "zh":
269
- return G_ZH.format(chunks="\n".join(f"[{i}] {t.strip()}" for i, t in items))
270
- return G_EN.format(turns="\n".join(f"[{i}] {t}" for i, t in items))
271
-
272
-
273
- # 生效条件:给定条目批 items、单批解析函数 one(批) → {编号: 结果}(异常视为整批失败)与重试次数:整批失败先原样重试 retries 次;仍缺的条目多于 1 条则拆半递归,单条则记入 missing。返回 (结果字典, missing 编号列表)。
274
- def _batched(items, one, retries: int = 1):
275
- got, missing = {}, []
276
-
277
- def run(b, left):
278
- try:
279
- r = one(b)
280
- except (ValueError, KeyError, TypeError, RuntimeError, OSError, urllib.error.URLError) as e: # 显式列举,结果计入 missing
281
- r, err = {}, e
282
- else:
283
- err = None
284
- got.update(r)
285
- miss = [x for x in b if x[0] not in r]
286
- if not miss:
287
- return
288
- if not r and left > 0:
289
- return run(miss, left - 1)
290
- if len(miss) > 1:
291
- h = (len(miss) + 1) // 2
292
- run(miss[:h], retries); run(miss[h:], retries)
293
- else:
294
- missing.append((miss[0][0], repr(err) if err else "输出缺该条"))
295
-
296
- run(list(items), retries)
297
- return got, missing
298
-
299
-
300
- # 生效条件:给定 [(题号, 问题)]、lang 与批大小,按批调用 query 角色抽题面扩展(缓存/计数见 call),返回 ({题号: hint}, [(缺失题号, 原因)])。
301
- def extract_hints(items, lang: str, batch: int = 10, cfg: dict = None, cache: Cache = None, counter: dict = None):
302
- cfg = cfg or config()
303
-
304
- def one(b):
305
- obj = parse_json(call("query", query_prompt(b, lang), cfg=cfg, cache=cache, counter=counter))
306
- g = (obj or {}).get("q", obj) or {}
307
- return {i: c for i, _ in b if (c := clean_hint(g.get(i) or g.get(f"[{i}]")))}
308
-
309
- got, missing = {}, []
310
- for k in range(0, len(items), batch):
311
- a, m = _batched(items[k:k + batch], one)
312
- got.update(a); missing += m
313
- return got, missing
314
-
315
-
316
- # 生效条件:给定 [(编号, 文本)]、lang 与批大小,按批调用 extract 角色抽源图三元组,返回 ({编号: [[主,谓,宾], ...]}, [(缺失编号, 原因)]);输出里不是三元组的项丢弃,[] 合法。
317
- def extract_triples(items, lang: str, batch: int = 10, cfg: dict = None, cache: Cache = None, counter: dict = None,
318
- max_tokens: int = None):
319
- cfg = cfg or config()
320
- field = "chunks" if lang == "zh" else "turns"
321
-
322
- def one(b):
323
- obj = parse_json(call("extract", graph_prompt(b, lang), cfg=cfg, cache=cache, counter=counter, max_tokens=max_tokens))
324
- m = {}
325
- for k, v in ((obj or {}).get(field, {}) or {}).items():
326
- if isinstance(v, list):
327
- m[str(k).strip("[] ")] = [t for t in v if isinstance(t, list) and len(t) == 3]
328
- return {i: m[i] for i, _ in b if i in m}
329
-
330
- got, missing = {}, []
331
- for k in range(0, len(items), batch):
332
- a, m = _batched(items[k:k + batch], one)
333
- got.update(a); missing += m
334
- return got, missing
1
+ # -*- coding: utf-8 -*-
2
+ """QMD 的 LLM 接入:源图抽取、题面扩展、作答与判官调用 + 统一系统提示词 + 身份隔离缓存。
3
+
4
+ 开关与配置(全部显式,无隐式回落)
5
+ ----------------------------------
6
+ · ``MDCG_QMD_SYS``:**只有取值恰为 "1"** 才给 extract / query / answer 三类调用带同一条
7
+ 统一系统提示词 ``SYSTEM``;未设或其它任何取值 = 关,messages 只有一条 user(与原型不带系统
8
+ 提示词的臂逐字相同)。**judge(判官)在任何取值下都不带 system**——保证与既有臂判分口径可比。
9
+ · ``MDCG_QMD_LLM_BASE`` / ``MDCG_QMD_LLM_MODEL`` / ``MDCG_QMD_LLM_KEY``:OpenAI 兼容
10
+ ``/chat/completions`` 的地址、模型、密钥,三者**缺一即抛 ``LLMUnavailable``**(点名缺哪个),
11
+ 不发请求、不静默降级。刻意**不**回落 ``MDCG_LLM_KEY`` / ``DEEPSEEK_API_KEY``:QMD 的网关可能
12
+ 与反思单元不同厂商,回落即凭证外泄(与 issue #96 同一立场)。
13
+
14
+ 依据(白箱三问之一)
15
+ --------------------
16
+ · 原型:TanPowasd/LingShu-prime ``TanPowasd/agm/bench/hive_official.py``(``SYSTEM``、``chat``、
17
+ ``parse_json``)、``TanPowasd/agm/confluence/qx.py``(题面扩展提示词与 ``clean``)、
18
+ ``hive_extract.py`` / ``extract.py``(源图抽取提示词)。提示词文本逐字取自原型。
19
+ · 原型审计 dsh-bounty#466:追问缓存未按系统提示词隔离、产物按臂名存在即复用 ⇒ 本模块的缓存键
20
+ 含(角色、模型、地址、密钥摘要、max_tokens、实际发出的 system 文本、prompt),条目内另存身份并在
21
+ 读出时逐项比对。密钥只以 sha256 摘要进身份,明文不写入任何缓存文件(PR #395 对抗复核补)。
22
+
23
+ 生效条件(白箱三问之二)
24
+ ------------------------
25
+ · 只被显式调用时生效;本仓既有检索/写入路径不 import 本模块(守卫 ``md_cg/test_qmd.py`` P13)。
26
+ · 网关返回体若外包一层 ``{"data": {...}}``(实测 Cline 网关如此)则解开;``choices`` 缺失、
27
+ content 为空、``finish_reason == "length"`` 一律抛 ``RuntimeError``,不当作空答案。
28
+
29
+ 错了怎么办 / 边界(白箱三问之三)
30
+ --------------------------------
31
+ · 抽取失败的批次会拆半重试到单条;仍失败的条目**原样列入返回的 missing**,由调用方决定;
32
+ ``md_cg/qmd.py`` 拿到缺块源图会抛 ``PartialGraph``、缺题 hint 会抛 ``MissingHint``。
33
+ · 无 LLM 时端到端增益不成立;本模块只提供调用面,不提供任何「无 key 替代」。
34
+ """
35
+ from __future__ import annotations
36
+
37
+ import hashlib
38
+ import json
39
+ import os
40
+ import re
41
+ import urllib.error
42
+ import urllib.request
43
+
44
+ __all__ = ["SYSTEM", "SYS_ENV", "BASE_ENV", "MODEL_ENV", "KEY_ENV", "ROLES", "LLMUnavailable", "CacheIdentityError",
45
+ "sys_on", "system_for", "messages", "config", "chat", "Cache", "call", "parse_json", "clean_hint",
46
+ "query_prompt", "graph_prompt", "extract_hints", "extract_triples"]
47
+
48
+ SYS_ENV = "MDCG_QMD_SYS"
49
+ BASE_ENV = "MDCG_QMD_LLM_BASE"
50
+ MODEL_ENV = "MDCG_QMD_LLM_MODEL"
51
+ KEY_ENV = "MDCG_QMD_LLM_KEY"
52
+ ROLES = ("extract", "query", "answer", "judge")
53
+
54
+ SYSTEM = ("你是灵枢长期记忆系统里的一个组件,负责从给定材料中抽取、检索或回答。\n"
55
+ "1. 只依据本次用户消息里给出的材料和问题工作,不使用材料以外的知识,不猜测,不编造。\n"
56
+ "2. 人名、地名、物品名、日期、数字一律照原文逐字写,不改写、不意译。\n"
57
+ "3. 问题有多个要点时逐点覆盖,不遗漏;材料里确实没有的,明确说没有,不要硬凑。\n"
58
+ "4. 严格按要求的格式输出:要 JSON 就只输出一个 JSON 对象,不加代码块、不加解释。")
59
+
60
+
61
+ class LLMUnavailable(RuntimeError):
62
+ """QMD 的 LLM 配置不全(缺地址/模型/密钥)。显式边界:不发请求、不降级。"""
63
+
64
+
65
+ class CacheIdentityError(RuntimeError):
66
+ """缓存条目记录的身份与本次调用不一致(不复用、不覆盖)。"""
67
+
68
+
69
+ # 生效条件:环境变量 MDCG_QMD_SYS 取值恰为 "1" 时返回 True,否则 False。
70
+ def sys_on() -> bool:
71
+ return os.environ.get(SYS_ENV) == "1"
72
+
73
+
74
+ # 生效条件:role 为 judge 时恒返回 None;其余角色在 sys_on() 为真时返回 SYSTEM,否则 None;未知角色抛 ValueError。
75
+ def system_for(role: str):
76
+ if role not in ROLES:
77
+ raise ValueError(f"未知角色 {role!r}(应为 {ROLES})")
78
+ if role == "judge":
79
+ return None
80
+ return SYSTEM if sys_on() else None
81
+
82
+
83
+ # 生效条件:给定 role 与 prompt,返回实际要发出的 messages 列表(system_for 非空时首条为 system)。
84
+ def messages(role: str, prompt: str) -> list:
85
+ s = system_for(role)
86
+ return ([{"role": "system", "content": s}] if s else []) + [{"role": "user", "content": prompt}]
87
+
88
+
89
+ # 生效条件:MDCG_QMD_LLM_BASE / MODEL / KEY 三个环境变量都为非空时返回 {"base","model","key"},任一缺失抛 LLMUnavailable 并点名。
90
+ def config() -> dict:
91
+ cfg = {"base": os.environ.get(BASE_ENV), "model": os.environ.get(MODEL_ENV), "key": os.environ.get(KEY_ENV)}
92
+ miss = [n for n, k in ((BASE_ENV, "base"), (MODEL_ENV, "model"), (KEY_ENV, "key")) if not (cfg[k] or "").strip()]
93
+ if miss:
94
+ raise LLMUnavailable("QMD 的 LLM 未配置:缺 " + "、".join(miss) + "(不回落其它厂商的密钥变量)")
95
+ return cfg
96
+
97
+
98
+ # 生效条件:给定网关返回体 data,解开可选的 {"data": ...} 外包;choices 缺失、content 空或 finish_reason=="length" 时抛 RuntimeError,否则返回 content。
99
+ def _content(data: dict) -> str:
100
+ if "choices" not in data and isinstance(data.get("data"), dict):
101
+ data = data["data"]
102
+ ch = data.get("choices") or []
103
+ if not ch:
104
+ raise RuntimeError("LLM 响应无 choices:" + json.dumps(data, ensure_ascii=False)[:300])
105
+ if ch[0].get("finish_reason") == "length":
106
+ raise RuntimeError("LLM 输出被截断(finish_reason=length)")
107
+ txt = (ch[0].get("message") or {}).get("content") or ""
108
+ if not txt.strip():
109
+ raise RuntimeError("LLM 返回空 content")
110
+ return txt
111
+
112
+
113
+ # 生效条件:给定 role、prompt(cfg 缺省时由 config() 解析,配置不全即抛 LLMUnavailable),向 base 的 /chat/completions 发一次 POST(temperature=0,max_tokens 仅在显式给出时传),经 _content 校验后返回文本;opener 供测试注入。
114
+ def chat(role: str, prompt: str, cfg: dict = None, timeout: int = 300, max_tokens: int = None, opener=None) -> str:
115
+ cfg = cfg or config()
116
+ body = {"model": cfg["model"], "messages": messages(role, prompt), "temperature": 0}
117
+ if max_tokens:
118
+ body["max_tokens"] = max_tokens
119
+ req = urllib.request.Request(cfg["base"].rstrip("/") + "/chat/completions", data=json.dumps(body).encode("utf-8"),
120
+ headers={"Content-Type": "application/json", "Authorization": f"Bearer {cfg['key']}"})
121
+ with (opener or urllib.request.urlopen)(req, timeout=timeout) as r:
122
+ return _content(json.loads(r.read().decode("utf-8")))
123
+
124
+
125
+ def _sha(s: str) -> str:
126
+ return hashlib.sha256(s.encode("utf-8")).hexdigest()
127
+
128
+
129
+ class Cache:
130
+ """按调用身份隔离的结果缓存:一调用一文件,文件名 = 身份的 sha256。
131
+
132
+ 身份 = (角色,模型,地址,密钥的 sha256,max_tokens(未给为 None),实际发出的 system 文本的 sha256 或 None,
133
+ prompt 的 sha256)。密钥只存摘要,明文不落盘。
134
+ 读出时把条目里存的身份与本次逐项比对,不一致抛 CacheIdentityError(不复用、不覆盖)。
135
+ """
136
+
137
+ def __init__(self, root):
138
+ self.root = os.fspath(root)
139
+ os.makedirs(self.root, exist_ok=True)
140
+
141
+ # 生效条件:给定 role、prompt、cfg 与 max_tokens,返回身份字典;max_tokens 取假值时记 None(与 chat 不传该字段一致),密钥只记 sha256。
142
+ @staticmethod
143
+ def identity(role: str, prompt: str, cfg: dict, max_tokens: int = None) -> dict:
144
+ s = system_for(role)
145
+ return {"role": role, "model": cfg["model"], "base": cfg["base"], "key_sha": _sha(cfg["key"]),
146
+ "max_tokens": max_tokens or None, "system_sha": _sha(s) if s else None, "prompt_sha": _sha(prompt)}
147
+
148
+ # 生效条件:给定 identity 字典,返回其规范 JSON 的 sha256 作为缓存文件名主干。
149
+ @staticmethod
150
+ def key(ident: dict) -> str:
151
+ return _sha(json.dumps(ident, ensure_ascii=False, sort_keys=True))
152
+
153
+ def _path(self, ident):
154
+ return os.path.join(self.root, self.key(ident) + ".json")
155
+
156
+ # 生效条件:给定 role、prompt、cfg、max_tokens:缓存文件不存在返回 None;存在且条目身份与本次相同返回其文本;身份不同抛 CacheIdentityError。
157
+ def get(self, role: str, prompt: str, cfg: dict, max_tokens: int = None):
158
+ ident = self.identity(role, prompt, cfg, max_tokens)
159
+ p = self._path(ident)
160
+ if not os.path.exists(p):
161
+ return None
162
+ with open(p, encoding="utf-8") as f:
163
+ d = json.load(f)
164
+ if d.get("identity") != ident:
165
+ raise CacheIdentityError(f"{p} 的身份 {d.get('identity')} ≠ 本次 {ident}")
166
+ return d["text"]
167
+
168
+ # 生效条件:给定 role、prompt、cfg、文本与 max_tokens,把 {"identity","text"} 写入身份对应的缓存文件。
169
+ def put(self, role: str, prompt: str, cfg: dict, text: str, max_tokens: int = None) -> None:
170
+ ident = self.identity(role, prompt, cfg, max_tokens)
171
+ with open(self._path(ident), "w", encoding="utf-8") as f:
172
+ json.dump({"identity": ident, "text": text}, f, ensure_ascii=False)
173
+
174
+
175
+ # 生效条件:给定 role、prompt:cache 命中则返回缓存文本(counter 不变);否则调用 chat,结果写入 cache(若给)并给 counter["calls"] 加一后返回;kw 里的 max_tokens 同时进缓存身份。
176
+ def call(role: str, prompt: str, cfg: dict = None, cache: Cache = None, counter: dict = None, **kw) -> str:
177
+ cfg = cfg or config()
178
+ mt = kw.get("max_tokens")
179
+ if cache is not None:
180
+ hit = cache.get(role, prompt, cfg, mt)
181
+ if hit is not None:
182
+ return hit
183
+ if counter is not None:
184
+ counter["calls"] = counter.get("calls", 0) + 1
185
+ txt = chat(role, prompt, cfg=cfg, **kw)
186
+ if cache is not None:
187
+ cache.put(role, prompt, cfg, txt, mt)
188
+ return txt
189
+
190
+
191
+ # 生效条件:给定模型输出文本,剥掉首尾代码围栏后取首个 "{" 到末个 "}" 之间解析为 JSON 返回;解析失败抛 ValueError。
192
+ def parse_json(txt: str):
193
+ t = re.sub(r"^```(?:json)?|```$", "", txt.strip(), flags=re.M).strip()
194
+ i, j = t.find("{"), t.rfind("}")
195
+ return json.loads(t[i:j + 1])
196
+
197
+
198
+ # 生效条件:给定一题的原始抽取结果 v:非字典或 ents/preds 皆空返回 None;否则返回字段裁成字符串(ents/preds/kw 各至多 8 条、hyde 至多 300 字、time 空值归 None)的规范字典。
199
+ def clean_hint(v):
200
+ if not isinstance(v, dict):
201
+ return None
202
+ L = lambda x: [str(s).strip() for s in (x if isinstance(x, list) else [x] if x else []) if str(s).strip()][:8] # noqa: E731
203
+ ents, preds = L(v.get("ents")), L(v.get("preds"))
204
+ if not ents and not preds:
205
+ return None
206
+ t = v.get("time")
207
+ return {"ents": ents, "preds": preds, "time": str(t).strip() if t not in (None, "", "null") else None,
208
+ "kw": L(v.get("kw")), "hyde": str(v.get("hyde") or "").strip()[:300]}
209
+
210
+
211
+ Q_EN = """You prepare search queries for a memory system over a long chat history between two people.
212
+ For EACH question, output:
213
+ - "ents": the people, objects, places, events, activities it asks about, written as they would appear in the chat (short noun phrases; resolve "she/he" only if the question names them);
214
+ - "preds": the relation or action asked about, as short verb phrases, plus 1-2 likely paraphrases;
215
+ - "time": the time constraint if any ("last year", "May 2023", "before the move"), else null;
216
+ - "kw": 3-6 extra keywords a matching chat line would likely contain (synonyms, related concrete words);
217
+ - "hyde": one short sentence, as the speaker might have said it in the chat, that would answer the question (invent plausible specifics; it is only used for search).
218
+ Output ONLY JSON: {{"q": {{"<id>": {{"ents": [...], "preds": [...], "time": null, "kw": [...], "hyde": "..."}}, ...}}}}
219
+
220
+ Questions:
221
+ {qs}"""
222
+
223
+ Q_ZH = """你在为一个检索中文小说正文的记忆系统准备检索式。对下面每道题,输出:
224
+ - "ents":题目问到的人物、物品、地点、事件,用小说原文里可能出现的写法(人名写全名,也给常见称呼);
225
+ - "preds":题目问的关系或动作,短动词短语,并给 1-2 个近义说法;
226
+ - "time":题中的时间约束(如“第三天夜里”“事发前”),没有就 null;
227
+ - "kw":3-6 个命中的原文句子里很可能出现的词(近义词、相关具体词);
228
+ - "hyde":一句像小说原文的假想句子,能回答本题(细节可以编,只用于检索)。
229
+ 只输出 JSON:{{"q": {{"<题号>": {{"ents": [...], "preds": [...], "time": null, "kw": [...], "hyde": "..."}}, ...}}}}
230
+
231
+ 题目:
232
+ {qs}"""
233
+
234
+ G_EN = """You convert dialogue turns into a knowledge graph. For EACH turn below, list its facts as
235
+ [subject, predicate, object] triples.
236
+ Rules:
237
+ - Replace pronouns (I, me, my, you, she, we, it...) with the concrete name they refer to; "I" is the speaker.
238
+ - Keep entity names short and as written (e.g. "Caroline", "LGBTQ support group", "pottery class").
239
+ - Predicates are short verb phrases ("attended", "plans to", "is", "painted", "felt").
240
+ - Add a date/time only if the turn states one, as a triple [event, "when", time].
241
+ - Include facts from [image: ...] captions as things the speaker shared.
242
+ - A turn with no factual content gets [].
243
+ Output ONLY JSON: {{"turns": {{"<turn id>": [[s,p,o], ...], ...}}}}
244
+
245
+ Turns:
246
+ {turns}"""
247
+
248
+ G_ZH = """你要把小说正文片段转成知识图谱。对下面每个片段,列出其中的事实,格式为 [主语, 谓语, 宾语] 三元组。
249
+ 规则:
250
+ - 代词(他、她、它、我们、这……)一律换成它指代的具体人名或事物名。
251
+ - 实体名保持简短、照原文写法(人名、地名、物品、组织、事件)。
252
+ - 谓语是简短的动词短语(“交给”“怀疑”“住在”“是”“答应”)。
253
+ - 原文写了时间、原因、条件时,用 [事件, "时间"/"原因"/"条件", 内容] 表示。
254
+ - 没有事实的片段给 []。
255
+ 只输出 JSON:{{"chunks": {{"<片段编号>": [[主,谓,宾], ...], ...}}}}
256
+
257
+ 片段:
258
+ {chunks}"""
259
+
260
+
261
+ # 生效条件:给定 [(题号, 问题)] 与 lang("zh"/"en"),返回题面扩展提示词(与原型 qx.py 逐字相同)。
262
+ def query_prompt(items, lang: str) -> str:
263
+ return (Q_ZH if lang == "zh" else Q_EN).format(qs="\n".join(f"[{i}] {q}" for i, q in items))
264
+
265
+
266
+ # 生效条件:给定 [(编号, 文本)] 与 lang,返回源图抽取提示词(zh 与原型 hive_extract.py、en 与 extract.py 逐字相同)。
267
+ def graph_prompt(items, lang: str) -> str:
268
+ if lang == "zh":
269
+ return G_ZH.format(chunks="\n".join(f"[{i}] {t.strip()}" for i, t in items))
270
+ return G_EN.format(turns="\n".join(f"[{i}] {t}" for i, t in items))
271
+
272
+
273
+ # 生效条件:给定条目批 items、单批解析函数 one(批) → {编号: 结果}(异常视为整批失败)与重试次数:整批失败先原样重试 retries 次;仍缺的条目多于 1 条则拆半递归,单条则记入 missing。返回 (结果字典, missing 编号列表)。
274
+ def _batched(items, one, retries: int = 1):
275
+ got, missing = {}, []
276
+
277
+ def run(b, left):
278
+ try:
279
+ r = one(b)
280
+ except (ValueError, KeyError, TypeError, RuntimeError, OSError, urllib.error.URLError) as e: # 显式列举,结果计入 missing
281
+ r, err = {}, e
282
+ else:
283
+ err = None
284
+ got.update(r)
285
+ miss = [x for x in b if x[0] not in r]
286
+ if not miss:
287
+ return
288
+ if not r and left > 0:
289
+ return run(miss, left - 1)
290
+ if len(miss) > 1:
291
+ h = (len(miss) + 1) // 2
292
+ run(miss[:h], retries); run(miss[h:], retries)
293
+ else:
294
+ missing.append((miss[0][0], repr(err) if err else "输出缺该条"))
295
+
296
+ run(list(items), retries)
297
+ return got, missing
298
+
299
+
300
+ # 生效条件:给定 [(题号, 问题)]、lang 与批大小,按批调用 query 角色抽题面扩展(缓存/计数见 call),返回 ({题号: hint}, [(缺失题号, 原因)])。
301
+ def extract_hints(items, lang: str, batch: int = 10, cfg: dict = None, cache: Cache = None, counter: dict = None):
302
+ cfg = cfg or config()
303
+
304
+ def one(b):
305
+ obj = parse_json(call("query", query_prompt(b, lang), cfg=cfg, cache=cache, counter=counter))
306
+ g = (obj or {}).get("q", obj) or {}
307
+ return {i: c for i, _ in b if (c := clean_hint(g.get(i) or g.get(f"[{i}]")))}
308
+
309
+ got, missing = {}, []
310
+ for k in range(0, len(items), batch):
311
+ a, m = _batched(items[k:k + batch], one)
312
+ got.update(a); missing += m
313
+ return got, missing
314
+
315
+
316
+ # 生效条件:给定 [(编号, 文本)]、lang 与批大小,按批调用 extract 角色抽源图三元组,返回 ({编号: [[主,谓,宾], ...]}, [(缺失编号, 原因)]);输出里不是三元组的项丢弃,[] 合法。
317
+ def extract_triples(items, lang: str, batch: int = 10, cfg: dict = None, cache: Cache = None, counter: dict = None,
318
+ max_tokens: int = None):
319
+ cfg = cfg or config()
320
+ field = "chunks" if lang == "zh" else "turns"
321
+
322
+ def one(b):
323
+ obj = parse_json(call("extract", graph_prompt(b, lang), cfg=cfg, cache=cache, counter=counter, max_tokens=max_tokens))
324
+ m = {}
325
+ for k, v in ((obj or {}).get(field, {}) or {}).items():
326
+ if isinstance(v, list):
327
+ m[str(k).strip("[] ")] = [t for t in v if isinstance(t, list) and len(t) == 3]
328
+ return {i: m[i] for i, _ in b if i in m}
329
+
330
+ got, missing = {}, []
331
+ for k in range(0, len(items), batch):
332
+ a, m = _batched(items[k:k + batch], one)
333
+ got.update(a); missing += m
334
+ return got, missing