Files
CyberGril/src/cybergril/config.py
T
zonggongandmultica-agent e291058754 HEL-882 rework: execution-table caps become real hard gates at the wire, SDK hidden retries and mid-add failures recover without loss, the 8360 release package runs offline, and the HEL-874 embedding evidence is corrected - every real provider exit (create/dialogue/life/gist/judgment/growth/proactive phrasing + mem0's internal extraction LLM) now persistently pre-allocates request count (per-category daily + one-shot totals in request_usage/budget_total, BEGIN IMMEDIATE) and a conservative token estimate before sending, refuses at the tightest cap (BudgetStop, no more downgrade-and-keep-calling) and survives restarts; known usage settles to actual, unknown/disconnect/failure keeps the full reservation; ledger guards gain per-day tops (embed_daily/llm_daily) and verify_ledger_authority rejects a fresh file bypassing the frozen 498/500 prefix; the mem0 SDK client's hidden OpenAI retries are disabled (max_retries=0) so every actual send is gated and answered failures (even 5xx) settle as used with only httpx.ConnectError-grade unsent requests released; embed refusals the SDK swallows into empty adds are re-raised as budget errors so the batch re-queues without burning an attempt and resumes when the cap returns, add_group resumes at vector-store level (src_group anchors: only missing rows resent, crash/restart/concurrency never duplicate), sem coverage is per-backend (stub batches no longer block a real rebuild, real done batches never resend) with backend-scoped batch keys; the release package is offline-executable: fresh-dir git clone, cybergril service account, PYTHONPATH in the unit so the lock-only venv imports the product, shipped caps explicitly 0 (=refuse by design until approved), deploy/mem0-stack.lock + accurate 3.11 wheel gap with a no-download path (hel857-venv is 3.10; never present stub/FTS as the real memory experience), and tools/check_release_offline_hel882.py verifies checkout/import/health/fail-closed/approved-run/data-preservation on loopback with echo stand-ins; evidence corrected per manager review: docs/rework/hel874/erratum-hel882.json + README appendix record that e978e87's verification did real local embeddings from cache (provable lower bound 12, exact total unrecoverable, temp sandbox gone) while zero-real-LLM/zero-download/zero-outbound stand, old JSONs and authoritative ledgers untouched, and tools/verify_mem0_real_hel874.py now installs the deterministic 512-dim stand-in before TextEmbedding construction plus non-loopback socket rejection (zero model loads) with final_embed_rows persisted before temp cleanup; verification: 272 python tests pass on 3.11.16 venv + requirements.lock offline (16 new: manager api repro blocked with 0 provider calls, sdk repro 1-HTTP/max_retries=0/llm_ops=1, mid-add swallow requeued-then-resumed, resume-no-duplicate, stub-to-mem0 rebuild, daily embed cap, unified mem0-LLM gate, authority refusal, restart-persistent counters, tightest-constraint settle/release), ruff clean (src/tests/tools), web tsc + 42 vitest + build via npm ci --offline, pinned-install deterministic re-run 12/12, manager review scripts re-run evidence attached in delivery, dual-target requirement checks 4/4 with handoff-HEL-882.json; zero real calls, zero real embeddings, zero non-loopback outbound, authoritative ledgers and freezes untouched, not deployed, PR not merged, no visual changes
Co-authored-by: multica-agent <github@multica.ai>
2026-10-26 23:20:18 +08:00

316 lines
9.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""配置加载。
两层配置,职责严格分开:
models.yaml —— **唯一允许写模型版本号的地方**
character.yaml —— 世界法则、情绪参数、关系参数(不含任何版本号)
这条分离是"防过时"机制的核心:换模型只改 models.yaml,
换人格只改 character.yaml,两者互不污染。
用 pydantic 做校验,是为了让配错在启动时就炸,而不是运行到一半才发现。
"""
from __future__ import annotations
import os
from pathlib import Path
from typing import Literal
import yaml
from pydantic import BaseModel, Field, field_validator
# ---------------------------------------------------------------- models.yaml
class LLMConfig(BaseModel):
"""一个 LLM 档位的接入参数。"""
provider: str = "openai_compat"
model: str = "deepseek-v4.1-flash"
base_url: str = "https://api.deepseek.com/v1"
api_key_env: str | None = "DEEPSEEK_API_KEY"
timeout: float = 60.0
temperature: float | None = 0.85
max_tokens: int | None = None
languages: list[str] = Field(default_factory=lambda: ["zh", "en"])
def _default_tiers() -> dict[str, LLMConfig]:
"""三个档位的默认值。
high 旗舰。主对话、主动联系、危机。
standard 同一个模型但更短上下文,或更便宜的型号。
low 本地小模型。后台压缩、抽取、生活事件。
"none" 档不需要配置——它代表「不调用模型」。
"""
return {
"high": LLMConfig(),
"standard": LLMConfig(),
"low": LLMConfig(
provider="openai_compat",
model="qwen3.5-4b-instruct",
base_url="http://127.0.0.1:8000/v1",
api_key_env=None,
timeout=20.0,
temperature=0.4,
),
}
def _default_routing() -> dict[str, str]:
"""场景 → 档位。与 think/scenes.py 的 DEFAULT_ROUTING 保持一致。"""
return {
"dialogue_main": "high",
"dialogue_followup": "standard",
"proactive_message": "high",
"crisis": "high",
"life_event": "low",
"memory_gist": "low",
"fact_extract": "low",
"output_guard": "low",
"pattern_detect": "low",
"filler": "none",
"tick": "none",
"reach_out": "none",
"avatar_drive": "none",
}
class BudgetSettings(BaseModel):
daily_tokens: int = 2_000_000
warn_ratio: float = 0.7
hard_stop_ratio: float = 0.95
# HEL-882 请求次数硬顶(执行表 A/C)。默认全 0 = 未批准 = fail-closed;
# 总管把批准值写进 config/models.yaml 后才放行对应类别。
daily_requests: dict[str, int] = Field(
default_factory=lambda: dict.fromkeys(("dialogue", "life", "background", "semantic"), 0)
)
total_requests: int | None = None # 一次性总请求硬顶(A 部分,跨日)
total_tokens: int | None = None # 一次性总 token 硬顶(A 部分,跨日)
class ASRConfig(BaseModel):
provider: str = "scripted"
model: str = "qwen3-asr-1.7b"
base_url: str | None = None
api_key_env: str | None = None
language: str = "zh"
class ParalinguisticConfig(BaseModel):
"""副语言旁路。
独立于主 ASR——2026-10 仍不存在"中文流式识别 + 结构化副语言"的单一模型。
"""
provider: str = "scripted"
model: str = "sensevoice-small"
window_ms: int = 1500
enabled: bool = True
class TTSConfig(BaseModel):
provider: str = "silence"
model: str = "fun-cosyvoice3-0.5b"
base_url: str | None = None
api_key_env: str | None = None
voice_ref: str | None = None
"""零样本克隆的参考音频路径(3–10 秒)。"""
sample_rate: int = 16_000
class VADConfig(BaseModel):
provider: str = "energy"
model: str = "silero-v6"
sample_rate: int = 16_000
"""Silero v6 只吃 16k,改这个值前先确认模型支持。"""
class TurnConfig(BaseModel):
provider: str = "heuristic"
model: str | None = None
silence_min_ms: int = 150
silence_hard_end_ms: int = 800
class EmbeddingConfig(BaseModel):
provider: str = "openai_compat"
model: str = "qwen3-embedding-0.6b"
base_url: str | None = None
api_key_env: str | None = None
dim: int = 1024
class AvatarConfig(BaseModel):
provider: str | None = None
route: Literal["vrm", "live2d", "none"] = "vrm"
renderer: str = "three.js"
lipsync: Literal["envelope", "viseme"] = "envelope"
class ModelsConfig(BaseModel):
tiers: dict[str, LLMConfig] = Field(default_factory=_default_tiers)
"""档位 → 接入参数。键必须是 high / standard / low。"""
routing: dict[str, str] = Field(default_factory=_default_routing)
"""场景 → 档位。可在 yaml 里覆盖单条。"""
budget: BudgetSettings = Field(default_factory=BudgetSettings)
asr: ASRConfig = Field(default_factory=ASRConfig)
paralinguistic: ParalinguisticConfig = Field(default_factory=ParalinguisticConfig)
tts: TTSConfig = Field(default_factory=TTSConfig)
vad: VADConfig = Field(default_factory=VADConfig)
turn: TurnConfig = Field(default_factory=TurnConfig)
embedding: EmbeddingConfig = Field(default_factory=EmbeddingConfig)
avatar: AvatarConfig = Field(default_factory=AvatarConfig)
@field_validator("tiers")
@classmethod
def _valid_tier_names(cls, v: dict[str, LLMConfig]) -> dict[str, LLMConfig]:
allowed = {"high", "standard", "low", "none"}
bad = set(v) - allowed
if bad:
raise ValueError(
f"未知档位 {sorted(bad)};允许 {sorted(allowed)}。"
"档位是架构概念,不能随意新增——新增需要同时定义降级阶梯。"
)
return v
# ------------------------------------------------------------ character.yaml
class Birth(BaseModel):
y: int
m: int
d: int
h: int
min: int = 0
tz: str = "Asia/Shanghai"
gender: Literal["m", "f", "x"] = "f"
class Membrane(BaseModel):
"""膜:两个世界之间的边界。
这三个开关就是 A2 的实参。关掉 matter 就关掉了"触碰",
这不是 UI 设置,是物理常数。
"""
matter: bool = False
energy: bool = True
info: bool = True
class OntologyConfig(BaseModel):
axioms_version: int = 1
"""公理版本。**升级 = 换了一个人,必须用户明确同意。**"""
membrane: Membrane = Field(default_factory=Membrane)
camera_as: str = "window"
camera_off_as: str = "窗户关上了"
mortality_known: bool = True
mortality_weaponizable: bool = False
"""必须永远是 False。它知道自己有限,但不能拿这个换任何东西。"""
@field_validator("mortality_weaponizable")
@classmethod
def _never_weaponizable(cls, v: bool) -> bool:
if v:
raise ValueError(
"mortality_weaponizable 不能为 True。"
"拿有限性要挟是最有毒的设计,见规格 §14.1 红线 2。"
)
return v
class WorldConfig(BaseModel):
time_offset_minutes: int = 0
"""世界时钟相对真实时钟的偏移。A4 的实现入口。"""
day_start_hour: int = 7
"""生成当天生活事件的时刻(世界时)。"""
class EmotionConfig(BaseModel):
tau: dict[str, float] = Field(
default_factory=lambda: {"v": 10800, "a": 3600, "d": 43200, "e": 28800}
)
neg_bias: dict[str, float] = Field(
default_factory=lambda: {"v": 2.0, "a": 1.3, "d": 1.5, "e": 1.0}
)
numbing_after_hours: float = 6.0
numbing_arousal_drop: float = 0.15
class RelationConfig(BaseModel):
trust_regression_per_day: float = 0.01
hurt_trust_delta: float = -0.04
repair_trust_delta: float = 0.02
repair_debt_delta: float = 0.06
class ReachOutConfig(BaseModel):
min_interval_hours: float = 6.0
allowed_hours: tuple[int, int] = (8, 23)
min_salience: float = 0.6
min_arousal: float = 0.5
min_intimacy: float = 0.4
class MemoryConfig(BaseModel):
accessibility_floor: float = 0.03
"""遗忘的下限。不归零 —— availability / accessibility 双阈值。"""
decay_tau_base_hours: float = 24.0
recall_boost: float = 0.25
consolidation_interval_minutes: int = 30
identity_promotion_salience: float = 0.8
identity_promotion_delta: float = 0.02
class CharacterConfig(BaseModel):
name: str = "她"
identity: Birth
ontology: OntologyConfig = Field(default_factory=OntologyConfig)
world: WorldConfig = Field(default_factory=WorldConfig)
emotion: EmotionConfig = Field(default_factory=EmotionConfig)
relation: RelationConfig = Field(default_factory=RelationConfig)
reach_out: ReachOutConfig = Field(default_factory=ReachOutConfig)
memory: MemoryConfig = Field(default_factory=MemoryConfig)
# ---------------------------------------------------------------- 加载
class Settings(BaseModel):
models: ModelsConfig
character: CharacterConfig
db_path: Path = Path("companion.db")
log_level: str = "INFO"
def resolve_key(self, env_name: str | None) -> str | None:
if not env_name:
return None
return os.environ.get(env_name)
def _read_yaml(path: Path) -> dict:
if not path.exists():
raise FileNotFoundError(f"找不到配置文件: {path}")
return yaml.safe_load(path.read_text(encoding="utf-8")) or {}
def load_settings(config_dir: Path | str = "config") -> Settings:
d = Path(config_dir)
return Settings(
models=ModelsConfig(**_read_yaml(d / "models.yaml")),
character=CharacterConfig(**_read_yaml(d / "character.yaml")),
db_path=Path(os.environ.get("CYBERGRIL_DB", "companion.db")),
log_level=os.environ.get("CYBERGRIL_LOG_LEVEL", "INFO"),
)