#!/usr/bin/env python3 """HEL-857 Mem0 隔离验证共享基础设施。 设计要点(对照批准范围): - 双 Memory 实例物理隔离:分离向量目录、history.db、派生实体 collection。 - MEM0_TELEMETRY=False 必须在 import mem0 之前生效;FASTEMBED_CACHE_PATH 指向本卡 数据目录,使全部模型资源下载可测量、可哈希、可限额。 - 嵌入条数计数上限 500(密集+实体),词面(BM25)另列计数;计数器包装在实例上。 - 真实出站请求一律经 ledger.AccountingTransport 持久扣账(见 ledger.py); 本模块只提供注入函数。 """ from __future__ import annotations import hashlib import json import os import re import time from pathlib import Path from typing import Any, Dict, Optional REPO_ROOT = Path(__file__).resolve().parents[2] DATA_DIR = Path(os.environ.get("HEL857_DATA", REPO_ROOT.parent / "hel857-data")) MODEL_CACHE = DATA_DIR / "fastembed-cache" os.environ["MEM0_TELEMETRY"] = "False" os.environ.setdefault("FASTEMBED_CACHE_PATH", str(MODEL_CACHE)) GATEWAY_BASE_URL = os.environ.get("HEL857_GATEWAY", "http://192.168.200.11:8731/v1") GATEWAY_MODEL = "halogen-qwen3.8-flash-next" LLM_CALL_CAP = 60 # 本卡全部真实模型请求合计上限(含失败/取消/重试) EMBED_ITEM_CAP = 500 # 本地密集+实体嵌入条数合计上限 INPUT_CJK_CAP = 6000 # 每请求输入中文字符上限 OUTPUT_TOKEN_CAP = 1024 # 每请求输出 token 上限 PRIV = "private" PUB = "public" CJK_RE = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff]") def count_cjk(text: str) -> int: return len(CJK_RE.findall(text or "")) class Counters: """跨脚本进程内计数器;超限抛 RuntimeError 立即停。""" def __init__(self) -> None: self.embed_calls = 0 # embed() 调用次数(单条) self.embed_items = 0 # 实际嵌入条数(embed_batch 拆条) self.entity_embed_items = 0 # 实体路径嵌入条数(spaCy 缺席时为 0,如实记录) self.keyword_calls = 0 # 词面/BM25 处理次数(另列,不占 500 上限) self.llm_calls = 0 # 真实 LLM 出站次数(与 ledger 对账) self.llm_failures = 0 self.consecutive_llm_failures = 0 self.cap_notes: list[str] = [] def check(self) -> None: if self.embed_items + self.entity_embed_items > EMBED_ITEM_CAP: raise RuntimeError(f"嵌入条数超限: {self.embed_items + self.entity_embed_items} > {EMBED_ITEM_CAP}") def snapshot(self) -> Dict[str, Any]: return { "embed_calls": self.embed_calls, "embed_items_dense": self.embed_items, "embed_items_entity": self.entity_embed_items, "embed_items_total": self.embed_items + self.entity_embed_items, "embed_cap": EMBED_ITEM_CAP, "keyword_calls": self.keyword_calls, "llm_calls_real": self.llm_calls, "llm_failures": self.llm_failures, "consecutive_llm_failures": self.consecutive_llm_failures, } COUNTERS = Counters() def mem_config(role: str, *, vec_root: Path, hist_root: Path) -> Dict[str, Any]: """双实例配置。role in {private, public}。""" return { "llm": { "provider": "openai", "config": { "model": GATEWAY_MODEL, "openai_base_url": GATEWAY_BASE_URL, "api_key": os.environ.get("HEL857_GATEWAY_KEY", "hel857-local-test"), "max_tokens": OUTPUT_TOKEN_CAP, "temperature": 0.0, }, }, "embedder": { "provider": "fastembed", "config": {"model": "BAAI/bge-small-zh-v1.5"}, }, "vector_store": { "provider": "qdrant", "config": { "path": str(vec_root / f"vec_{role}"), "collection_name": f"cg_{role}", "embedding_model_dims": 512, # BAAI/bge-small-zh-v1.5 固有维度 "on_disk": True, }, }, "history_db_path": str(hist_root / f"mem0_{role}_history.db"), "version": "v1.1", } def install_counters(memory) -> None: """在实例上包装嵌入/词面计数。真实 LLM 出站计数在传输层(ledger)。""" emb = memory.embedding_model orig_embed = emb.embed def counted_embed(text, memory_action=None): COUNTERS.embed_calls += 1 COUNTERS.embed_items += 1 COUNTERS.check() return orig_embed(text, memory_action) emb.embed = counted_embed # type: ignore[method-assign] orig_kw = memory.vector_store.keyword_search def counted_kw(*a, **kw): COUNTERS.keyword_calls += 1 return orig_kw(*a, **kw) memory.vector_store.keyword_search = counted_kw # type: ignore[method-assign] def close_memory(memory) -> None: """清洁关闭本地 qdrant 客户端,释放目录锁,保证可复制备份。""" try: memory.vector_store.client.close() except Exception: pass def dir_hash(root: Path) -> str: """目录内容确定性哈希(相对路径+文件字节)。""" h = hashlib.sha256() for p in sorted(root.rglob("*")): rel = str(p.relative_to(root)) h.update(rel.encode()) if p.is_file(): h.update(p.read_bytes()) return h.hexdigest() def history_db_hash(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest() if path.exists() else "missing" def cjk_len_ok(messages) -> tuple[bool, int, int]: """返回 (是否合规, 中文字符数, 总字符数)。messages 为 openai 格式列表。""" joined = "".join(str(m.get("content", "")) for m in messages) return (count_cjk(joined) <= INPUT_CJK_CAP, count_cjk(joined), len(joined)) def now_ms() -> int: return int(time.time() * 1000) def write_result(name: str, payload: Dict[str, Any]) -> Path: out = Path(__file__).parent / "results" out.mkdir(exist_ok=True) path = out / name path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") return path