feat(emotion-e6): add bounded affect modulation
这个提交存在于:
父节点
aa1689038a
当前提交
60487391d9
共有 5 个文件被更改,包括 190 次插入 和 0 次删除
47
affect_modulation.py
普通文件
47
affect_modulation.py
普通文件
|
|
@ -0,0 +1,47 @@
|
||||||
|
"""Compose condition-level affect deltas without creating another state authority."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
try:
|
||||||
|
from .affect_modulation_contract import normalize_affect_modulation
|
||||||
|
except ImportError: # pragma: no cover
|
||||||
|
from affect_modulation_contract import normalize_affect_modulation
|
||||||
|
|
||||||
|
|
||||||
|
def compose_affect_modulation(conditions: list[dict[str, Any]], *, now: float) -> dict[str, Any]:
|
||||||
|
valence = arousal = vulnerability = confidence_total = 0.0
|
||||||
|
source_ids: list[str] = []
|
||||||
|
for condition in conditions[:64]:
|
||||||
|
if not isinstance(condition, dict):
|
||||||
|
continue
|
||||||
|
modulation = normalize_affect_modulation(condition.get("modulation"))
|
||||||
|
confidence = modulation["confidence"]
|
||||||
|
if confidence <= 0:
|
||||||
|
continue
|
||||||
|
start = condition.get("start_ts")
|
||||||
|
half_life = condition.get("half_life_seconds")
|
||||||
|
decay = 1.0
|
||||||
|
if type(start) in {int, float} and type(half_life) in {int, float} and float(half_life) >= 60:
|
||||||
|
decay = 0.5 ** (max(0.0, now - float(start)) / min(86400.0, float(half_life)))
|
||||||
|
weight = confidence * decay
|
||||||
|
valence += modulation["valence"] * weight
|
||||||
|
arousal += modulation["arousal"] * weight
|
||||||
|
vulnerability += modulation["vulnerability"] * weight
|
||||||
|
confidence_total += weight
|
||||||
|
event_id = str(condition.get("source_event_id") or "")[:96]
|
||||||
|
if event_id and event_id not in source_ids:
|
||||||
|
source_ids.append(event_id)
|
||||||
|
divisor = max(1.0, confidence_total)
|
||||||
|
return normalize_affect_modulation({
|
||||||
|
"valence": valence / divisor,
|
||||||
|
"arousal": arousal / divisor,
|
||||||
|
"vulnerability": vulnerability / divisor,
|
||||||
|
"confidence": min(1.0, confidence_total),
|
||||||
|
"source_event_ids": source_ids,
|
||||||
|
"computed_at": now,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["compose_affect_modulation"]
|
||||||
46
affect_modulation_contract.py
普通文件
46
affect_modulation_contract.py
普通文件
|
|
@ -0,0 +1,46 @@
|
||||||
|
"""Bounded affect modulation DTO shared across companion plugins."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import math
|
||||||
|
from typing import Any, Mapping
|
||||||
|
|
||||||
|
AFFECT_MODULATION_VERSION = "affect_modulation.v1"
|
||||||
|
AFFECT_MODULATION_FIELDS = ("schema_version", "valence", "arousal", "vulnerability", "confidence", "source_event_ids", "computed_at")
|
||||||
|
AFFECT_MODULATION_FINGERPRINT = hashlib.sha256("|".join(AFFECT_MODULATION_FIELDS).encode("ascii")).hexdigest()[:20]
|
||||||
|
|
||||||
|
|
||||||
|
def _number(value: Any, default: float, low: float, high: float) -> float:
|
||||||
|
if type(value) not in {int, float}:
|
||||||
|
return default
|
||||||
|
numeric = float(value)
|
||||||
|
if not math.isfinite(numeric):
|
||||||
|
return default
|
||||||
|
return round(max(low, min(high, numeric)), 4)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_affect_modulation(value: Any) -> dict[str, Any]:
|
||||||
|
source = dict(value) if isinstance(value, Mapping) else {}
|
||||||
|
raw_ids = source.get("source_event_ids")
|
||||||
|
ids: list[str] = []
|
||||||
|
if isinstance(raw_ids, (list, tuple)):
|
||||||
|
for item in raw_ids[:12]:
|
||||||
|
if type(item) is not str:
|
||||||
|
continue
|
||||||
|
cleaned = " ".join(item.split())[:96]
|
||||||
|
if cleaned and cleaned not in ids:
|
||||||
|
ids.append(cleaned)
|
||||||
|
computed_at = source.get("computed_at")
|
||||||
|
return {
|
||||||
|
"schema_version": AFFECT_MODULATION_VERSION,
|
||||||
|
"valence": _number(source.get("valence"), 0.0, -1.0, 1.0),
|
||||||
|
"arousal": _number(source.get("arousal"), 0.0, 0.0, 1.0),
|
||||||
|
"vulnerability": _number(source.get("vulnerability"), 0.0, 0.0, 1.0),
|
||||||
|
"confidence": _number(source.get("confidence"), 0.0, 0.0, 1.0),
|
||||||
|
"source_event_ids": ids,
|
||||||
|
"computed_at": float(computed_at) if type(computed_at) in {int, float} and math.isfinite(float(computed_at)) else 0.0,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ["AFFECT_MODULATION_FIELDS", "AFFECT_MODULATION_FINGERPRINT", "AFFECT_MODULATION_VERSION", "normalize_affect_modulation"]
|
||||||
|
|
@ -16,6 +16,10 @@ try:
|
||||||
from .interaction_dynamics import project_interaction_dynamics
|
from .interaction_dynamics import project_interaction_dynamics
|
||||||
except ImportError: # pragma: no cover - direct module import in lightweight tests
|
except ImportError: # pragma: no cover - direct module import in lightweight tests
|
||||||
from interaction_dynamics import project_interaction_dynamics
|
from interaction_dynamics import project_interaction_dynamics
|
||||||
|
try:
|
||||||
|
from .affect_modulation_contract import normalize_affect_modulation
|
||||||
|
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.v1"
|
||||||
|
|
@ -95,6 +99,7 @@ class ExpressionDecision:
|
||||||
initiative: str
|
initiative: str
|
||||||
proactive_budget: int
|
proactive_budget: int
|
||||||
tts_style: str
|
tts_style: str
|
||||||
|
affect_modulation: Mapping[str, Any]
|
||||||
allowed_behaviors: tuple[str, ...]
|
allowed_behaviors: tuple[str, ...]
|
||||||
safety_mode: str
|
safety_mode: str
|
||||||
blocker: str | None
|
blocker: str | None
|
||||||
|
|
@ -516,6 +521,24 @@ def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] |
|
||||||
warmth = min(100, warmth + 5)
|
warmth = min(100, warmth + 5)
|
||||||
reasons.append("up_mood_expression_lift")
|
reasons.append("up_mood_expression_lift")
|
||||||
|
|
||||||
|
modulation = normalize_affect_modulation(bot_state.get("affect_modulation"))
|
||||||
|
if modulation["confidence"] > 0:
|
||||||
|
if modulation["valence"] <= -0.35:
|
||||||
|
warmth = max(0, warmth - 3)
|
||||||
|
if tone not in {"reserved", "careful"}:
|
||||||
|
tone = "gentle"
|
||||||
|
elif modulation["valence"] >= 0.35 and band not in {ExpressionBand.AVOIDANT, ExpressionBand.HURT}:
|
||||||
|
warmth = min(100, warmth + 3)
|
||||||
|
if modulation["arousal"] <= 0.2:
|
||||||
|
tts_style = "soft"
|
||||||
|
elif modulation["arousal"] >= 0.7 and not low_energy and not down_mood and band not in {ExpressionBand.AVOIDANT, ExpressionBand.HURT}:
|
||||||
|
tts_style = "bright"
|
||||||
|
if modulation["vulnerability"] >= 0.65:
|
||||||
|
followup = False
|
||||||
|
if tone != "reserved":
|
||||||
|
tone = "careful"
|
||||||
|
reasons.append("affect_modulation_applied")
|
||||||
|
|
||||||
schedule = _mapping(source.get("schedule"))
|
schedule = _mapping(source.get("schedule"))
|
||||||
budget = _candidate_budget(_mapping(source.get("proactive_candidate")))
|
budget = _candidate_budget(_mapping(source.get("proactive_candidate")))
|
||||||
if "proactive_care_limit" in relationship_baseline:
|
if "proactive_care_limit" in relationship_baseline:
|
||||||
|
|
@ -561,6 +584,7 @@ def build_expression_decision(input_data: ExpressionInput | Mapping[str, Any] |
|
||||||
initiative=initiative,
|
initiative=initiative,
|
||||||
proactive_budget=budget,
|
proactive_budget=budget,
|
||||||
tts_style=tts_style,
|
tts_style=tts_style,
|
||||||
|
affect_modulation=modulation,
|
||||||
allowed_behaviors=behaviors,
|
allowed_behaviors=behaviors,
|
||||||
safety_mode="contact_boundary_passive" if contact_boundary else "normal",
|
safety_mode="contact_boundary_passive" if contact_boundary else "normal",
|
||||||
blocker=None,
|
blocker=None,
|
||||||
|
|
@ -687,6 +711,7 @@ def _blocked_decision(reason: str, blocker: str, inherited_reasons: list[str]) -
|
||||||
initiative="blocked",
|
initiative="blocked",
|
||||||
proactive_budget=0,
|
proactive_budget=0,
|
||||||
tts_style="none",
|
tts_style="none",
|
||||||
|
affect_modulation=normalize_affect_modulation({}),
|
||||||
allowed_behaviors=(),
|
allowed_behaviors=(),
|
||||||
safety_mode=reason,
|
safety_mode=reason,
|
||||||
blocker=blocker,
|
blocker=blocker,
|
||||||
|
|
|
||||||
|
|
@ -106,6 +106,7 @@ from .dreaming import (
|
||||||
weighted_unique_fragment_sample,
|
weighted_unique_fragment_sample,
|
||||||
)
|
)
|
||||||
from .helpers import _date_key, _normalize_outbound_punctuation_flow, _normalize_photo_subject_owner, _now_ts, _path_text, _photo_subject_owner_prompt_label, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks, _today_key, normalize_legacy_tag_text
|
from .helpers import _date_key, _normalize_outbound_punctuation_flow, _normalize_photo_subject_owner, _now_ts, _path_text, _photo_subject_owner_prompt_label, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks, _today_key, normalize_legacy_tag_text
|
||||||
|
from .affect_modulation import compose_affect_modulation
|
||||||
from .memo_notes import memo_note_due_state, memo_note_sort_key, normalize_memo_note
|
from .memo_notes import memo_note_due_state, memo_note_sort_key, normalize_memo_note
|
||||||
from .planning import (
|
from .planning import (
|
||||||
build_daily_plan_prompt,
|
build_daily_plan_prompt,
|
||||||
|
|
@ -6732,6 +6733,7 @@ class DailyStateMixin:
|
||||||
"energy": energy,
|
"energy": energy,
|
||||||
"note": note,
|
"note": note,
|
||||||
"conditions": active,
|
"conditions": active,
|
||||||
|
"affect_modulation": compose_affect_modulation(active, now=composed_at),
|
||||||
}
|
}
|
||||||
if override_active:
|
if override_active:
|
||||||
result["location_override_ts"] = existing_override_ts
|
result["location_override_ts"] = existing_override_ts
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,70 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
from pathlib import Path
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from affect_modulation import compose_affect_modulation
|
||||||
|
from affect_modulation_contract import normalize_affect_modulation
|
||||||
|
from companion_interaction_expression import build_expression_decision
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
class EmotionE6AffectModulationTests(unittest.TestCase):
|
||||||
|
def test_contract_is_identical_and_malicious_numbers_fail_neutral(self) -> None:
|
||||||
|
companion = (ROOT / "affect_modulation_contract.py").read_text(encoding="utf-8")
|
||||||
|
memory = (ROOT.parent / "memory" / "core" / "affect_modulation.py").read_text(encoding="utf-8")
|
||||||
|
self.assertEqual(companion, memory)
|
||||||
|
result = normalize_affect_modulation({
|
||||||
|
"valence": "0.9",
|
||||||
|
"arousal": math.inf,
|
||||||
|
"vulnerability": object(),
|
||||||
|
"confidence": math.nan,
|
||||||
|
"source_event_ids": ["emo-1", object()],
|
||||||
|
})
|
||||||
|
self.assertEqual(0.0, result["valence"])
|
||||||
|
self.assertEqual(0.0, result["arousal"])
|
||||||
|
self.assertEqual(0.0, result["vulnerability"])
|
||||||
|
self.assertEqual(0.0, result["confidence"])
|
||||||
|
self.assertEqual(["emo-1"], result["source_event_ids"])
|
||||||
|
|
||||||
|
def test_condition_modulation_decays_monotonically(self) -> None:
|
||||||
|
condition = {
|
||||||
|
"source_event_id": "emo-1",
|
||||||
|
"start_ts": 1000.0,
|
||||||
|
"half_life_seconds": 100.0,
|
||||||
|
"modulation": {"valence": 0.8, "arousal": 0.6, "vulnerability": 0.4, "confidence": 1.0},
|
||||||
|
}
|
||||||
|
first = compose_affect_modulation([condition], now=1000.0)
|
||||||
|
second = compose_affect_modulation([condition], now=1100.0)
|
||||||
|
self.assertGreater(first["valence"], second["valence"])
|
||||||
|
self.assertGreater(first["confidence"], second["confidence"])
|
||||||
|
|
||||||
|
def test_modulation_changes_expression_detail_not_authority(self) -> None:
|
||||||
|
base = {
|
||||||
|
"relationship_score": 650,
|
||||||
|
"relationship_role": "friend",
|
||||||
|
"current_interaction": {"expression_band": "warm"},
|
||||||
|
"proactive_candidate": {"budget": 1},
|
||||||
|
"content_policy": {"private_chat": True, "flirt_enabled": False},
|
||||||
|
}
|
||||||
|
quiet = build_expression_decision({
|
||||||
|
**base,
|
||||||
|
"bot_state": {"energy": 70, "affect_modulation": {"valence": 0.4, "arousal": 0.1, "vulnerability": 0.2, "confidence": 1.0}},
|
||||||
|
})
|
||||||
|
bright = build_expression_decision({
|
||||||
|
**base,
|
||||||
|
"bot_state": {"energy": 70, "affect_modulation": {"valence": 0.4, "arousal": 0.9, "vulnerability": 0.2, "confidence": 1.0}},
|
||||||
|
})
|
||||||
|
self.assertEqual("warm", quiet.expression_band)
|
||||||
|
self.assertEqual(quiet.expression_band, bright.expression_band)
|
||||||
|
self.assertEqual(quiet.content_tier, bright.content_tier)
|
||||||
|
self.assertEqual(quiet.proactive_budget, bright.proactive_budget)
|
||||||
|
self.assertEqual("soft", quiet.tts_style)
|
||||||
|
self.assertEqual("bright", bright.tts_style)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
正在加载…
添加表格
在新工单中引用