chore: project foundation

Contracts (the shared language):
- percept / state / context / utterance / render / audio / capabilities
- Capability model instead of vendor schemas (see below)

Providers (capability-based abstraction):
- LLM + Embedding: OpenAI-compatible shape IS the standard, adopted directly
- ASR: internal contract is an event stream (partial -> final), because
  /v1/audio/transcriptions has no partial and dialogue needs it for
  endpointing. OpenAI adapter degrades to supports_partial=False.
- TTS: internal contract carries tags/emotion/style, because
  /v1/audio/speech has no paralinguistics and [laughter]/[breath] are
  the core of feeling alive. Unsupported providers are stripped AND
  reported via Degradation -- silent degradation is forbidden.
- Avatar: no de-facto standard, custom RenderCmd protocol driven by State.

Core:
- mood: dynamical system, slow variables, negativity bias (grudge),
  numbing after prolonged negativity
- bazi: four pillars -> numeric vector; 'ming' is data, not prose
- projection: phi, system event -> in-world statement; uncovered events
  are counted as projection gaps

Storage:
- SQLite schema, three memory layers, dyad ledger
- accessibility floor 0.03 (not 0): forgettable but still there

Config split:
- models.yaml is the ONLY place model versions live
- character.yaml holds world rules / emotion params, no version numbers

58 tests pass; ruff clean.
This commit is contained in:
mobai
2026-10-19 20:08:52 +08:00
commit 1012d8bb79
57 changed files with 6452 additions and 0 deletions
+240
View File
@@ -0,0 +1,240 @@
"""配置加载。
两层配置,职责严格分开:
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):
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
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):
llm: LLMConfig = Field(default_factory=LLMConfig)
llm_fast: LLMConfig | None = None
llm_background: LLMConfig | None = None
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)
# ------------------------------------------------------------ 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"),
)