270 lines
10 KiB
Python
270 lines
10 KiB
Python
#!/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()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 卡级持久嵌入账本(HEL-858 返工新增):进程内 Counters 只覆盖单进程,
|
|
# 跨进程/子进程/batch 一律落同一 SQLite 账本;500 上限按全卡累计判定。
|
|
EMBED_LEDGER_PATH = Path(os.environ.get("HEL857_EMBED_LEDGER",
|
|
DATA_DIR / "embed_ledger.sqlite3"))
|
|
|
|
|
|
class EmbedLedger:
|
|
"""跨进程持久嵌入计数。add 侧(dense/entity)与词面(keyword)分表另列。
|
|
|
|
历史用量(HEL-857 run1/run2/门禁,未持久化时期)以带方法说明的
|
|
reconstruction 行补种;补种行同样计入 used(),不重置、不改历史。
|
|
"""
|
|
|
|
def __init__(self, path: Optional[Path] = None):
|
|
self.path = Path(path) if path else EMBED_LEDGER_PATH
|
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
self._lock = __import__("threading").Lock()
|
|
with self._connect() as c:
|
|
c.execute(
|
|
"CREATE TABLE IF NOT EXISTS embed_ops ("
|
|
" id INTEGER PRIMARY KEY AUTOINCREMENT,"
|
|
" ts TEXT NOT NULL, pid INTEGER NOT NULL,"
|
|
" kind TEXT NOT NULL," # dense | entity | keyword | seed_dense | seed_keyword
|
|
" items INTEGER NOT NULL, note TEXT NOT NULL DEFAULT '')")
|
|
|
|
def _connect(self):
|
|
import sqlite3
|
|
conn = sqlite3.connect(str(self.path), timeout=30.0, isolation_level=None)
|
|
conn.execute("PRAGMA journal_mode=WAL")
|
|
conn.execute("PRAGMA synchronous=FULL")
|
|
return conn
|
|
|
|
def debit(self, kind: str, items: int = 1, note: str = "") -> None:
|
|
with self._lock, self._connect() as c:
|
|
c.execute("INSERT INTO embed_ops(ts,pid,kind,items,note) VALUES(?,?,?,?,?)",
|
|
(now_ms_iso(), os.getpid(), kind, items, note))
|
|
|
|
def used_by_kind(self) -> Dict[str, int]:
|
|
with self._connect() as c:
|
|
rows = c.execute("SELECT kind, SUM(items) FROM embed_ops GROUP BY kind").fetchall()
|
|
return {k: int(v or 0) for k, v in rows}
|
|
|
|
def used_embed_items(self) -> int:
|
|
"""密集+实体合计(词面不计入 500 上限,另列)。"""
|
|
by = self.used_by_kind()
|
|
return (by.get("dense", 0) + by.get("entity", 0)
|
|
+ by.get("seed_dense", 0) + by.get("seed_entity", 0))
|
|
|
|
def remaining(self) -> int:
|
|
return EMBED_ITEM_CAP - self.used_embed_items()
|
|
|
|
def check(self) -> None:
|
|
used = self.used_embed_items()
|
|
if used > EMBED_ITEM_CAP:
|
|
raise RuntimeError(f"卡级嵌入条数超限: {used} > {EMBED_ITEM_CAP}")
|
|
|
|
def summary(self) -> Dict[str, Any]:
|
|
by = self.used_by_kind()
|
|
return {
|
|
"ledger_path": str(self.path),
|
|
"dense": by.get("dense", 0) + by.get("seed_dense", 0),
|
|
"entity": by.get("entity", 0) + by.get("seed_entity", 0),
|
|
"embed_items_total": self.used_embed_items(),
|
|
"keyword": by.get("keyword", 0) + by.get("seed_keyword", 0),
|
|
"cap": EMBED_ITEM_CAP,
|
|
"remaining": self.remaining(),
|
|
}
|
|
|
|
|
|
def now_ms_iso() -> str:
|
|
import time as _t
|
|
return _t.strftime("%Y-%m-%dT%H:%M:%S", _t.gmtime(_t.time())) + "Z"
|
|
|
|
|
|
EMBED_LEDGER = EmbedLedger()
|
|
|
|
|
|
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)。
|
|
|
|
进程内 COUNTERS 之外,同步落卡级持久嵌入账本(跨进程累计,500 上限
|
|
按 EmbedLedger.check() 全卡判定)。
|
|
"""
|
|
emb = memory.embedding_model
|
|
orig_embed = emb.embed
|
|
|
|
def counted_embed(text, memory_action=None):
|
|
COUNTERS.embed_calls += 1
|
|
COUNTERS.embed_items += 1
|
|
EMBED_LEDGER.debit("dense", 1, note=str(memory_action))
|
|
COUNTERS.check()
|
|
EMBED_LEDGER.check()
|
|
return orig_embed(text, memory_action)
|
|
|
|
emb.embed = counted_embed # type: ignore[method-assign]
|
|
|
|
orig_embed_batch = getattr(emb, "embed_batch", None)
|
|
if callable(orig_embed_batch):
|
|
def counted_embed_batch(texts, memory_action=None):
|
|
n = len(texts) if isinstance(texts, (list, tuple)) else 1
|
|
COUNTERS.embed_items += n
|
|
EMBED_LEDGER.debit("dense", n, note=f"batch:{memory_action}")
|
|
COUNTERS.check()
|
|
EMBED_LEDGER.check()
|
|
return orig_embed_batch(texts, memory_action)
|
|
|
|
emb.embed_batch = counted_embed_batch # type: ignore[method-assign]
|
|
|
|
orig_kw = memory.vector_store.keyword_search
|
|
|
|
def counted_kw(*a, **kw):
|
|
COUNTERS.keyword_calls += 1
|
|
EMBED_LEDGER.debit("keyword", 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
|