feat(emotion-e8): expand expression dimensions

这个提交存在于:
agent 2026-08-05 00:43:10 +08:00
父节点 178428a91e
当前提交 4a423bac69
共有 9 个文件被更改,包括 146 次插入 和 8 次删除

查看文件

@ -22,7 +22,7 @@ except ImportError: # pragma: no cover
from affect_modulation_contract import normalize_affect_modulation
EXPRESSION_CONTRACT_VERSION = "companion_interaction_expression.v1"
EXPRESSION_CONTRACT_VERSION = "companion_interaction_expression.v2"
CONTENT_TIERS = ("normal", "flirt", "adult")
CONTENT_TIER_LABELS = {"normal": "日常", "flirt": "含蓄暧昧", "adult": "成人私密"}
_CONTENT_STAGE_INDEX = {
@ -100,6 +100,12 @@ class ExpressionDecision:
proactive_budget: int
tts_style: str
affect_modulation: Mapping[str, Any]
pacing: str
directness: str
validation_style: str
self_disclosure: str
humor_mode: str
topic_initiative: str
allowed_behaviors: tuple[str, ...]
safety_mode: str
blocker: str | None
@ -570,6 +576,16 @@ def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] |
owner_exclusive=owner_exclusive,
reasons=reasons,
)
pacing = "slow" if low_energy or down_mood or modulation["arousal"] <= 0.2 else "bright" if modulation["arousal"] >= 0.7 and band == ExpressionBand.LIVELY else "steady"
directness = "indirect" if band in {ExpressionBand.AVOIDANT, ExpressionBand.HURT} else "direct" if band in {ExpressionBand.LIVELY, ExpressionBand.AFFECTIONATE} else "natural"
validation_style = "acknowledge" if band in {ExpressionBand.AVOIDANT, ExpressionBand.HURT, ExpressionBand.RELAXED} else "support_first"
if modulation["vulnerability"] >= 0.65:
validation_style = "support_first"
self_disclosure = "allowed" if owner_account and band in {ExpressionBand.CLOSE, ExpressionBand.AFFECTIONATE} else "light" if "shared_ritual" in behaviors else "none"
humor_mode = "off"
if "light_humor" in behaviors and not low_energy and not down_mood and band not in {ExpressionBand.AVOIDANT, ExpressionBand.HURT}:
humor_mode = "playful" if band == ExpressionBand.LIVELY else "light"
topic_initiative = "reply_only" if not followup else "shared_topic" if "shared_ritual" in behaviors else "followup"
return ExpressionDecision(
contract=EXPRESSION_CONTRACT_VERSION,
expression_band=band.value,
@ -585,6 +601,12 @@ def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] |
proactive_budget=budget,
tts_style=tts_style,
affect_modulation=modulation,
pacing=pacing,
directness=directness,
validation_style=validation_style,
self_disclosure=self_disclosure,
humor_mode=humor_mode,
topic_initiative=topic_initiative,
allowed_behaviors=behaviors,
safety_mode="contact_boundary_passive" if contact_boundary else "normal",
blocker=None,
@ -680,12 +702,19 @@ def expression_decision_prompt(value: ExpressionDecision | Mapping[str, Any]) ->
content_instruction = "内容尺度=含蓄暧昧;可以亲密和调情,但保持非露骨,不描写成人性行为"
else:
content_instruction = "内容尺度=日常;不要主动升级为暧昧或成人内容"
dimensions = (
f"节奏={str(decision.get('pacing') or 'steady')[:12]},"
f"直接度={str(decision.get('directness') or 'natural')[:12]},"
f"回应={str(decision.get('validation_style') or 'none')[:16]},"
f"幽默={str(decision.get('humor_mode') or 'off')[:12]},"
f"话题={str(decision.get('topic_initiative') or 'reply_only')[:16]}"
)
return (
f"当前互动表达:{EXPRESSION_BAND_LABELS[band.value]};"
f"语气={str(decision.get('tone') or 'steady')[:24]},"
f"称呼距离={str(decision.get('address_style') or 'neutral')[:24]},"
f"回复长度={str(decision.get('response_length') or 'balanced')[:24]};"
f"{followup};{initiative};{content_instruction}。"
f"{followup};{initiative};{dimensions};{content_instruction}。"
)
@ -712,6 +741,12 @@ def _blocked_decision(reason: str, blocker: str, inherited_reasons: list[str]) -
proactive_budget=0,
tts_style="none",
affect_modulation=normalize_affect_modulation({}),
pacing="slow",
directness="indirect",
validation_style="none",
self_disclosure="none",
humor_mode="off",
topic_initiative="reply_only",
allowed_behaviors=(),
safety_mode=reason,
blocker=blocker,

查看文件

@ -9634,7 +9634,7 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
if instruction:
self._append_turn_prompt_fragment_by_position(
req,
"<!-- private_companion_expression_decision_v1 -->",
"<!-- private_companion_expression_decision_v2 -->",
f"[Companion expression]\n{instruction}",
priority=5,
source="expression_decision",

查看文件

@ -202,7 +202,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
now=time.time(),
)
expression_projection = {
"contract": "companion_interaction_expression.v1",
"contract": "companion_interaction_expression.v2",
"status": "configured_projection",
"expression_band": current_interaction.get("expression_band") or "relaxed",
"tone": "steady",
@ -219,7 +219,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
raw_projection = raw_expression.to_dict() if hasattr(raw_expression, "to_dict") else dict(raw_expression or {})
expression_projection.update(
{
"contract": self._single_line(raw_projection.get("contract"), 80) or "companion_interaction_expression.v1",
"contract": self._single_line(raw_projection.get("contract"), 80) or "companion_interaction_expression.v2",
"expression_band": self._single_line(raw_projection.get("expression_band"), 24) or "relaxed",
"tone": self._single_line(raw_projection.get("tone"), 24) or "steady",
"response_length": self._single_line(raw_projection.get("response_length"), 24) or "balanced",

查看文件

@ -3366,6 +3366,10 @@ class ProactiveMessageMixin:
f"档位={_single_line(expression_decision.get('expression_band'), 24) or 'relaxed'};"
f"语气={_single_line(expression_decision.get('tone'), 24) or 'steady'};"
f"距离={_single_line(expression_decision.get('address_style'), 24) or 'neutral'};"
f"节奏={_single_line(expression_decision.get('pacing'), 16) or 'steady'};"
f"回应={_single_line(expression_decision.get('validation_style'), 20) or 'none'};"
f"幽默={_single_line(expression_decision.get('humor_mode'), 16) or 'off'};"
f"话题={_single_line(expression_decision.get('topic_initiative'), 20) or 'reply_only'};"
f"追问={'允许' if expression_decision.get('followup') else '关闭'};"
f"主动额度={_safe_int(expression_decision.get('proactive_budget'), 0, 0)}。"
)

查看文件

@ -68,7 +68,7 @@ class ReplyTemperatureTests(unittest.TestCase):
self.assertEqual([], legacy_calls)
self.assertIn("_private_companion_expression_decision", source)
self.assertNotIn("_private_companion_reply_temperature", source)
self.assertIn("private_companion_expression_decision_v1", source)
self.assertIn("private_companion_expression_decision_v2", source)
helper = next(
node for node in ast.walk(tree)
if isinstance(node, ast.FunctionDef) and node.name == "_bounded_expression_state_signals"

查看文件

@ -0,0 +1,81 @@
from __future__ import annotations
import ast
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import unittest
from companion_interaction_expression import (
EXPRESSION_CONTRACT_VERSION,
build_expression_decision,
expression_decision_prompt,
)
ROOT = Path(__file__).resolve().parents[1]
class EmotionE8ExpressionDimensionTests(unittest.TestCase):
def build(self, band: str, **updates: Any):
source = {
"relationship_role": "owner",
"relationship_mode": "owner_exclusive",
"relationship_score": 1200,
"current_interaction": {"expression_band": band},
"bot_state": {"energy": 70},
"proactive_candidate": {"budget": 2},
}
source.update(updates)
return build_expression_decision(source)
def test_all_bands_map_to_bounded_v2_dimensions(self) -> None:
allowed = {
"pacing": {"slow", "steady", "bright"},
"directness": {"indirect", "natural", "direct"},
"validation_style": {"none", "acknowledge", "support_first"},
"self_disclosure": {"none", "light", "allowed"},
"humor_mode": {"off", "light", "playful"},
"topic_initiative": {"reply_only", "followup", "shared_topic"},
}
self.assertEqual("companion_interaction_expression.v2", EXPRESSION_CONTRACT_VERSION)
for band in ("avoidant", "hurt", "relaxed", "lively", "warm", "close", "affectionate"):
decision = self.build(band).to_dict()
for key, values in allowed.items():
self.assertIn(decision[key], values)
def test_safety_and_low_energy_only_suppress_dimensions(self) -> None:
tired = self.build("lively", bot_state={"energy": 15}).to_dict()
self.assertEqual("slow", tired["pacing"])
self.assertEqual("off", tired["humor_mode"])
self.assertEqual("reply_only", tired["topic_initiative"])
blocked = self.build("affectionate", safety_constraints={"contact_boundary": True}).to_dict()
self.assertEqual("contact_boundary", blocked["blocker"])
self.assertEqual("off", blocked["humor_mode"])
self.assertEqual("none", blocked["self_disclosure"])
self.assertEqual("reply_only", blocked["topic_initiative"])
def test_prompt_and_tts_consume_the_same_projection(self) -> None:
decision = self.build("warm", bot_state={"energy": 70, "affect_modulation": {"valence": 0.3, "arousal": 0.1, "vulnerability": 0.8, "confidence": 1.0}}).to_dict()
prompt = expression_decision_prompt(decision)
self.assertIn(f"节奏={decision['pacing']}", prompt)
self.assertIn(f"回应={decision['validation_style']}", prompt)
self.assertLess(len(prompt), 520)
source = (ROOT / "tts_enhancement.py").read_text(encoding="utf-8")
tree = ast.parse(source)
owner = next(node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "TtsEnhancementMixin")
method = next(node for node in owner.body if isinstance(node, ast.FunctionDef) and node.name == "_tts_expression_style_context")
method.decorator_list = []
module = ast.Module(body=[method], type_ignores=[])
ast.fix_missing_locations(module)
namespace = {"Any": Any, "_single_line": lambda value, limit=0: " ".join(str(value or "").split())[:limit]}
exec(compile(module, str(ROOT / "tts_enhancement.py"), "exec"), namespace)
event = SimpleNamespace(_private_companion_expression_decision=decision)
tts_context = namespace["_tts_expression_style_context"](event)
self.assertIn(f"节奏={decision['pacing']}", tts_context)
self.assertIn(f"幽默={decision['humor_mode']}", tts_context)
if __name__ == "__main__":
unittest.main()

查看文件

@ -157,7 +157,7 @@ def _content_payload(**overrides: Any) -> dict[str, Any]:
def test_content_tier_matrix_and_intent_are_deterministic() -> None:
assert EXPRESSION_CONTRACT_VERSION == "companion_interaction_expression.v1"
assert EXPRESSION_CONTRACT_VERSION == "companion_interaction_expression.v2"
assert content_intent_from_text("我同意,开启成人模式并继续") == {
"requested_content_tier": "adult",
"turn_consent": True,

查看文件

@ -1786,6 +1786,20 @@ TTS 朗读文本:
return True
return bool(cjk_count >= 6 and kana_count < max(2, int(cjk_count * 0.35)))
@staticmethod
def _tts_expression_style_context(event: Any) -> str:
decision = getattr(event, "_private_companion_expression_decision", None)
if not isinstance(decision, dict):
return ""
return (
"统一表达投影:"
f"tts={_single_line(decision.get('tts_style'), 16) or 'neutral'};"
f"节奏={_single_line(decision.get('pacing'), 16) or 'steady'};"
f"直接度={_single_line(decision.get('directness'), 16) or 'natural'};"
f"回应={_single_line(decision.get('validation_style'), 20) or 'none'};"
f"幽默={_single_line(decision.get('humor_mode'), 16) or 'off'}。"
)
def _build_tts_rule_prompt(self, provider_kind: str = "generic") -> str:
lang = self._tts_language_label()
mode = getattr(self, "tts_generation_mode", "fast_tag")
@ -2889,6 +2903,7 @@ TTS 朗读文本:
return await self._postprocess_text_to_tts_markup(source, event, provider_kind=provider_kind, full=full)
extra = _single_line(getattr(self, "main_user_mention_voice_prompt", ""), 500) if self._event_mentions_main_user_with_keyword(event) else ""
persona_context = await self._format_tts_persona_voice_context(event)
expression_context = self._tts_expression_style_context(event)
emotion_rule = self._tts_emotion_tag_rule(provider_kind, subject="<pc_tts> 内")
if not emotion_rule:
emotion_rule = "不要加入方括号情绪标签。"
@ -2920,6 +2935,7 @@ TTS 朗读文本:
Provider 规则:{emotion_rule}
补充要求:{extra or "无"}
{persona_context}
{expression_context}
原回复:
{source}
@ -2957,6 +2973,7 @@ Provider 规则:{emotion_rule}
if not extra:
extra = self._legacy_nondefault_tts_prompt()
persona_context = await self._format_tts_persona_voice_context(event)
expression_context = self._tts_expression_style_context(event)
if voice_lang == "zh":
language_rule = "voice_text 必须是自然中文。"
visible_rule = "visible_text 仍是最终可见中文文本;如果和 voice_text 一样,可以保持同一句。"
@ -2989,6 +3006,7 @@ Provider 规则:{emotion_rule}
本轮自动语音概率线索:{probability_hint}
补充规则:{extra or "无"}
{persona_context}
{expression_context}
判断规则:
- 你要自己根据用户原话、规则线索和回复内容判断用户是否在要求或期待语音;规则快判只是线索,不是最终结论。

查看文件

@ -4687,7 +4687,7 @@ Local classifier result:
def _update_relationship_state_from_intent(self, user: dict[str, Any], intent: dict[str, Any]) -> None:
if not isinstance(intent, dict):
return
# companion_interaction_expression.v1 settles new events directly into
# companion_interaction_expression.v2 settles new events directly into
# the single short-term authority. relationship_state/mood_score and
# the old Izard/Plutchik/Gross projections remain read-only legacy data.
emotion_enabled = bool(getattr(self, "enable_emotion_simulation", True))