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.
333 lines
11 KiB
Python
333 lines
11 KiB
Python
"""八字编译:四柱 → 数值向量。
|
||
|
||
**关键设计判断:八字不是 prompt,是状态机的初始条件。**
|
||
|
||
如果把八字写成 prompt 里的一段散文,它会在长对话里漂移,
|
||
而且"clamp 只能恢复约一半行为余量"(人格漂移研究的结论)。
|
||
写成数值参数,它就是硬的。
|
||
|
||
编译流程:
|
||
四柱 → 五行强度 → 日主强弱 → 十神分布 → 派生参数
|
||
|
||
这里刻意把「排盘」和「编译」分开:
|
||
排盘依赖 lunar-python(外部库,可能换)
|
||
编译是纯函数(可测试,无依赖)
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from dataclasses import dataclass, field
|
||
|
||
# ------------------------------------------------------------------ 常量表
|
||
|
||
#: 地支藏干:本气 / 中气 / 余气
|
||
CANGAN: dict[str, tuple[str, ...]] = {
|
||
"子": ("癸",),
|
||
"丑": ("己", "癸", "辛"),
|
||
"寅": ("甲", "丙", "戊"),
|
||
"卯": ("乙",),
|
||
"辰": ("戊", "乙", "癸"),
|
||
"巳": ("丙", "庚", "戊"),
|
||
"午": ("丁", "己"),
|
||
"未": ("己", "丁", "乙"),
|
||
"申": ("庚", "壬", "戊"),
|
||
"酉": ("辛",),
|
||
"戌": ("戊", "辛", "丁"),
|
||
"亥": ("壬", "甲"),
|
||
}
|
||
|
||
#: 天干 → 五行
|
||
GAN_ELEM: dict[str, str] = {
|
||
"甲": "木", "乙": "木",
|
||
"丙": "火", "丁": "火",
|
||
"戊": "土", "己": "土",
|
||
"庚": "金", "辛": "金",
|
||
"壬": "水", "癸": "水",
|
||
}
|
||
|
||
#: 地支 → 五行(本气)
|
||
ZHI_ELEM: dict[str, str] = {
|
||
"子": "水", "丑": "土", "寅": "木", "卯": "木",
|
||
"辰": "土", "巳": "火", "午": "火", "未": "土",
|
||
"申": "金", "酉": "金", "戌": "土", "亥": "水",
|
||
}
|
||
|
||
ELEMENTS = ("木", "火", "土", "金", "水")
|
||
|
||
#: 五行生克(生)
|
||
SHENG = {"木": "火", "火": "土", "土": "金", "金": "水", "水": "木"}
|
||
#: 五行克
|
||
KE = {"木": "土", "土": "水", "水": "火", "火": "金", "金": "木"}
|
||
|
||
#: 十神 → 对各参数的影响
|
||
GOD_PARAMS: dict[str, dict[str, float]] = {
|
||
"比肩": {"autonomy": 0.8, "compliance": -0.4},
|
||
"劫财": {"impulsivity": 0.7, "sharing": -0.5},
|
||
"食神": {"expressiveness": 0.6, "warmth": 0.5},
|
||
"伤官": {"expressiveness": 0.9, "compliance": -0.8},
|
||
"正财": {"realism": 0.7, "romance": -0.4},
|
||
"偏财": {"generosity": 0.7, "routine": -0.5},
|
||
"正官": {"discipline": 0.8, "correcting": 0.7},
|
||
"七杀": {"anxiety": 0.8, "aggression": 0.7},
|
||
"正印": {"caretaking": 0.7, "initiative": -0.5},
|
||
"偏印": {"solitude_need": 0.8, "explaining": -0.6},
|
||
}
|
||
|
||
#: 日主五行 → 底色(只用于生成时给措辞参考,不参与计算)
|
||
DAY_MASTER_TRAIT: dict[str, str] = {
|
||
"甲": "正直、向上、不弯",
|
||
"乙": "柔韧、缠绕、迂回",
|
||
"丙": "外放、热烈、直给",
|
||
"丁": "内敛、细腻、忽明忽暗",
|
||
"戊": "厚重、稳定、慢",
|
||
"己": "包容、细致、易积压",
|
||
"庚": "刚硬、果断、锋利",
|
||
"辛": "精致、敏感、易碎",
|
||
"壬": "流动、宏大、不羁",
|
||
"癸": "渗透、隐微、绵长",
|
||
}
|
||
|
||
#: 藏干权重
|
||
CANGAN_WEIGHTS = (0.6, 0.3, 0.1)
|
||
#: 月令加成
|
||
MONTH_MULTIPLIER = 2.0
|
||
|
||
|
||
# ------------------------------------------------------------------ 结构
|
||
|
||
|
||
@dataclass(frozen=True, slots=True)
|
||
class Pillars:
|
||
"""四柱。year/month/day/time 各为「干支」两字,如 "甲子"。"""
|
||
|
||
year: str
|
||
month: str
|
||
day: str
|
||
time: str
|
||
|
||
@property
|
||
def day_master(self) -> str:
|
||
"""日主 = 日柱天干。"""
|
||
return self.day[0]
|
||
|
||
def as_dict(self) -> dict[str, str]:
|
||
return {"year": self.year, "month": self.month, "day": self.day, "time": self.time}
|
||
|
||
|
||
@dataclass(frozen=True, slots=True)
|
||
class Derived:
|
||
"""编译后的数值向量。这是「命」,之后只读。"""
|
||
|
||
autonomy: float = 0.5
|
||
compliance: float = 0.5
|
||
expressiveness: float = 0.5
|
||
warmth: float = 0.5
|
||
anxiety: float = 0.5
|
||
aggression: float = 0.5
|
||
discipline: float = 0.5
|
||
correcting: float = 0.5
|
||
solitude_need: float = 0.5
|
||
impulsivity: float = 0.5
|
||
sharing: float = 0.5
|
||
realism: float = 0.5
|
||
romance: float = 0.5
|
||
generosity: float = 0.5
|
||
routine: float = 0.5
|
||
caretaking: float = 0.5
|
||
initiative: float = 0.5
|
||
explaining: float = 0.5
|
||
|
||
sensitivity: float = 1.0
|
||
"""身弱 > 1(更容易被事件冲击),身强 < 1。"""
|
||
|
||
recovery_scale: float = 1.0
|
||
"""身弱 > 1(恢复更慢),身强 < 1。"""
|
||
|
||
trust_floor: float = 0.5
|
||
element_bias: dict[str, float] = field(default_factory=dict)
|
||
strength: float = 0.5
|
||
|
||
def as_dict(self) -> dict[str, object]:
|
||
from dataclasses import fields
|
||
|
||
d: dict[str, object] = {}
|
||
for f in fields(self):
|
||
value = getattr(self, f.name)
|
||
d[f.name] = dict(value) if f.name == "element_bias" else value
|
||
return d
|
||
|
||
def traits_text(self) -> str:
|
||
"""给生成用的简短描述。**不用于注入人设**,只用于措辞参考。"""
|
||
bits: list[str] = []
|
||
if self.expressiveness > 0.65:
|
||
bits.append("话多、直接")
|
||
elif self.expressiveness < 0.35:
|
||
bits.append("话少、不解释")
|
||
if self.compliance < 0.35:
|
||
bits.append("不服管")
|
||
if self.correcting > 0.6:
|
||
bits.append("爱纠正人")
|
||
if self.solitude_need > 0.65:
|
||
bits.append("需要独处")
|
||
if self.warmth > 0.6:
|
||
bits.append("温和")
|
||
if self.anxiety > 0.65:
|
||
bits.append("容易焦虑")
|
||
return "、".join(bits) or "难以归类"
|
||
|
||
|
||
# ------------------------------------------------------------------ 计算
|
||
|
||
|
||
def element_scores(pillars: Pillars) -> dict[str, float]:
|
||
"""五行强度。天干 1.0,地支藏干按 0.6/0.3/0.1,月令 ×2。"""
|
||
scores = dict.fromkeys(ELEMENTS, 0.0)
|
||
|
||
for key in ("year", "month", "day", "time"):
|
||
ganzhi = getattr(pillars, key)
|
||
if len(ganzhi) != 2:
|
||
raise ValueError(f"{key} 柱格式错误,应为两字干支,得到 {ganzhi!r}")
|
||
gan, zhi = ganzhi[0], ganzhi[1]
|
||
|
||
# 天干
|
||
scores[GAN_ELEM[gan]] += 1.0
|
||
|
||
# 地支藏干
|
||
for ca, w in zip(CANGAN.get(zhi, ()), CANGAN_WEIGHTS, strict=False):
|
||
scores[GAN_ELEM[ca]] += w
|
||
|
||
# 月令加权
|
||
if key == "month":
|
||
scores[GAN_ELEM[gan]] += 1.0 * (MONTH_MULTIPLIER - 1.0)
|
||
for ca, w in zip(CANGAN.get(zhi, ()), CANGAN_WEIGHTS, strict=False):
|
||
scores[GAN_ELEM[ca]] += w * (MONTH_MULTIPLIER - 1.0)
|
||
|
||
return scores
|
||
|
||
|
||
def day_master_strength(pillars: Pillars, scores: dict[str, float]) -> float:
|
||
"""日主强弱 0..1。
|
||
|
||
简化算法:日主五行能量 + 生我五行能量 × 0.5,
|
||
对比总能量。0.5 为中和。
|
||
"""
|
||
me = GAN_ELEM[pillars.day_master]
|
||
supporting = me
|
||
# 生我者
|
||
generator = next((e for e, t in SHENG.items() if t == me), me)
|
||
|
||
total = sum(scores.values()) or 1.0
|
||
mine = scores.get(supporting, 0.0) + scores.get(generator, 0.0) * 0.5
|
||
return max(0.0, min(1.0, mine / total))
|
||
|
||
|
||
def ten_god(day_master: str, other: str) -> str:
|
||
"""以日主为基准,求 other 天干的十神。
|
||
|
||
简化实现:按五行生克与阴阳关系定名。
|
||
"""
|
||
me = GAN_ELEM[day_master]
|
||
it = GAN_ELEM[other]
|
||
same_polarity = _same_polarity(day_master, other)
|
||
|
||
if me == it:
|
||
return "比肩" if same_polarity else "劫财"
|
||
if SHENG[me] == it:
|
||
# 我生:同性食神,异性伤官
|
||
return "食神" if same_polarity else "伤官"
|
||
if SHENG[it] == me:
|
||
# 生我:同性偏印,异性正印
|
||
return "偏印" if same_polarity else "正印"
|
||
if KE[me] == it:
|
||
# 我克:同性偏财,异性正财
|
||
return "偏财" if same_polarity else "正财"
|
||
# 克我:同性七杀,异性正官
|
||
return "七杀" if same_polarity else "正官"
|
||
|
||
|
||
def _same_polarity(a: str, b: str) -> bool:
|
||
"""天干阴阳是否相同(甲丙戊庚壬为阳)。"""
|
||
yang = set("甲丙戊庚壬")
|
||
return (a in yang) == (b in yang)
|
||
|
||
|
||
def ten_god_distribution(pillars: Pillars) -> dict[str, float]:
|
||
"""十神分布(归一化权重)。"""
|
||
dm = pillars.day_master
|
||
counts: dict[str, float] = {}
|
||
|
||
for key in ("year", "month", "day", "time"):
|
||
ganzhi = getattr(pillars, key)
|
||
gan, zhi = ganzhi[0], ganzhi[1]
|
||
if key != "day": # 日干本身是日主,不计十神
|
||
counts[ten_god(dm, gan)] = counts.get(ten_god(dm, gan), 0.0) + 1.0
|
||
for ca in CANGAN.get(zhi, ()):
|
||
counts[ten_god(dm, ca)] = counts.get(ten_god(dm, ca), 0.0) + 0.35
|
||
|
||
total = sum(counts.values()) or 1.0
|
||
return {k: v / total for k, v in counts.items()}
|
||
|
||
|
||
def compile_pillars(pillars: Pillars) -> Derived:
|
||
"""四柱 → Derived。纯函数,可测试。"""
|
||
scores = element_scores(pillars)
|
||
strength = day_master_strength(pillars, scores)
|
||
gods = ten_god_distribution(pillars)
|
||
|
||
params = {
|
||
"autonomy": 0.5, "compliance": 0.5, "expressiveness": 0.5,
|
||
"warmth": 0.5, "anxiety": 0.5, "aggression": 0.5,
|
||
"discipline": 0.5, "correcting": 0.5, "solitude_need": 0.5,
|
||
"impulsivity": 0.5, "sharing": 0.5, "realism": 0.5,
|
||
"romance": 0.5, "generosity": 0.5, "routine": 0.5,
|
||
"caretaking": 0.5, "initiative": 0.5, "explaining": 0.5,
|
||
}
|
||
|
||
# 十神加权:每个十神带着自己的偏移,权重是它在命里的占比
|
||
for god, weight in gods.items():
|
||
for param, delta in GOD_PARAMS.get(god, {}).items():
|
||
params[param] += delta * weight
|
||
|
||
# 钳制到 0..1
|
||
for k in list(params):
|
||
params[k] = max(0.0, min(1.0, params[k]))
|
||
|
||
total = sum(scores.values()) or 1.0
|
||
element_bias = {e: scores.get(e, 0.0) / total for e in ELEMENTS}
|
||
|
||
return Derived(
|
||
**params,
|
||
sensitivity=1.35 - 0.70 * strength,
|
||
recovery_scale=1.60 - 1.20 * strength,
|
||
element_bias=element_bias,
|
||
strength=strength,
|
||
)
|
||
|
||
|
||
# ------------------------------------------------------------------ 排盘
|
||
|
||
|
||
def pillars_from_lunar(year: int, month: int, day: int, hour: int, minute: int = 0) -> Pillars:
|
||
"""用 lunar-python 排盘。
|
||
|
||
lunar-python 是可选依赖(未列入 pyproject 的必需项)。
|
||
没装就抛 ImportError,调用方应回退到静态配置的四柱。
|
||
|
||
接口在这里固定,换库不改业务代码。
|
||
"""
|
||
try:
|
||
from lunar_python import Solar # type: ignore[import-not-found]
|
||
except ImportError as exc: # pragma: no cover
|
||
raise ImportError(
|
||
"需要 lunar-python 才能排盘;pip install lunar-python,"
|
||
"或在 character.yaml 里直接提供四柱。"
|
||
) from exc
|
||
|
||
ec = Solar.fromYmdHms(year, month, day, hour, minute, 0).getLunar().getEightChar()
|
||
return Pillars(
|
||
year=str(ec.getYear()),
|
||
month=str(ec.getMonth()),
|
||
day=str(ec.getDay()),
|
||
time=str(ec.getTime()),
|
||
)
|