feat(emotion-e5): add gradual interaction recovery
这个提交存在于:
父节点
72b6696b79
当前提交
aa1689038a
共有 6 个文件被更改,包括 272 次插入 和 13 次删除
|
|
@ -12,6 +12,11 @@ from dataclasses import asdict, dataclass
|
|||
from enum import Enum
|
||||
from typing import Any, Mapping
|
||||
|
||||
try:
|
||||
from .interaction_dynamics import project_interaction_dynamics
|
||||
except ImportError: # pragma: no cover - direct module import in lightweight tests
|
||||
from interaction_dynamics import project_interaction_dynamics
|
||||
|
||||
|
||||
EXPRESSION_CONTRACT_VERSION = "companion_interaction_expression.v1"
|
||||
CONTENT_TIERS = ("normal", "flirt", "adult")
|
||||
|
|
@ -580,6 +585,10 @@ def current_interaction_projection(
|
|||
) -> dict[str, Any]:
|
||||
"""Normalize persisted and legacy interaction state for runtime/page use."""
|
||||
raw = dict(value) if isinstance(value, Mapping) else {}
|
||||
current_ts = _bounded_timestamp(now)
|
||||
dynamics = project_interaction_dynamics(raw, now=current_ts) if current_ts else {}
|
||||
if dynamics:
|
||||
raw.update(dynamics)
|
||||
band = _band_from_interaction(raw) or ExpressionBand.RELAXED
|
||||
role = _text(relationship_role)
|
||||
score = _bounded_int(raw.get("relationship_score", relationship_score), 0, -1200, 1200)
|
||||
|
|
@ -596,15 +605,14 @@ def current_interaction_projection(
|
|||
band = normal_cap_band
|
||||
reason_codes.append("normal_interaction_band_cap_applied")
|
||||
expires_at = _bounded_timestamp(raw.get("expires_at"))
|
||||
current_ts = _bounded_timestamp(now)
|
||||
manual = bool(raw.get("manual_override") or _text(raw.get("source")) == "manual")
|
||||
if expires_at and current_ts and current_ts >= expires_at:
|
||||
if not dynamics and expires_at and current_ts and current_ts >= expires_at:
|
||||
band = ExpressionBand.RELAXED
|
||||
manual = False
|
||||
reason_codes.append("interaction_expired")
|
||||
source = "manual" if manual else _text(raw.get("source")) or "automatic"
|
||||
reason = str(raw.get("reason") or raw.get("reason_code") or "").replace("\r", " ").replace("\n", " ")[:120]
|
||||
return {
|
||||
projection = {
|
||||
"expression_band": band.value,
|
||||
"label": EXPRESSION_BAND_LABELS[band.value],
|
||||
"source": source,
|
||||
|
|
@ -619,6 +627,19 @@ def current_interaction_projection(
|
|||
"last_event_id": _bounded_text(raw.get("last_event_id"), 96),
|
||||
"trace_id": _bounded_text(raw.get("trace_id"), 96),
|
||||
}
|
||||
if dynamics:
|
||||
projection.update({
|
||||
"dynamics_version": dynamics["dynamics_version"],
|
||||
"load": dynamics["load"],
|
||||
"peak_intensity": dynamics["peak_intensity"],
|
||||
"decay_started_at": dynamics["decay_started_at"],
|
||||
"half_life": dynamics["half_life"],
|
||||
"recovery_band": dynamics["recovery_band"],
|
||||
"projection_revision": dynamics["projection_revision"],
|
||||
"polarity": dynamics["polarity"],
|
||||
"base_band": dynamics["base_band"],
|
||||
})
|
||||
return projection
|
||||
|
||||
|
||||
def expression_decision_prompt(value: ExpressionDecision | Mapping[str, Any]) -> str:
|
||||
|
|
|
|||
115
interaction_dynamics.py
普通文件
115
interaction_dynamics.py
普通文件
|
|
@ -0,0 +1,115 @@
|
|||
"""Deterministic recovery dynamics behind the seven interaction bands."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import Any, Mapping
|
||||
|
||||
|
||||
DYNAMICS_VERSION = "interaction_dynamics.v1"
|
||||
NEGATIVE_BANDS = {"avoidant", "hurt"}
|
||||
POSITIVE_BANDS = {"lively", "warm", "close", "affectionate"}
|
||||
|
||||
|
||||
def _finite(value: Any, default: float = 0.0) -> float:
|
||||
if isinstance(value, bool):
|
||||
return default
|
||||
try:
|
||||
numeric = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return numeric if math.isfinite(numeric) else default
|
||||
|
||||
|
||||
def project_interaction_dynamics(value: Any, *, now: Any) -> dict[str, Any]:
|
||||
raw = dict(value) if isinstance(value, Mapping) else {}
|
||||
if raw.get("dynamics_version") != DYNAMICS_VERSION:
|
||||
return {}
|
||||
current = max(0.0, min(100.0, _finite(raw.get("load"))))
|
||||
peak = max(current, min(100.0, _finite(raw.get("peak_intensity"), current)))
|
||||
started = max(0.0, _finite(raw.get("decay_started_at"), _finite(raw.get("updated_at"))))
|
||||
current_ts = max(started, _finite(now, started))
|
||||
half_life = max(300.0, min(86400.0, _finite(raw.get("half_life"), 3600.0)))
|
||||
load = current * (0.5 ** (max(0.0, current_ts - started) / half_life))
|
||||
polarity = -1 if int(_finite(raw.get("polarity"), 0)) < 0 else 1 if int(_finite(raw.get("polarity"), 0)) > 0 else 0
|
||||
stored_band = str(raw.get("base_band") or raw.get("expression_band") or "relaxed")
|
||||
if polarity < 0:
|
||||
band = "avoidant" if load >= 70.0 else "hurt" if load >= 12.0 else "relaxed"
|
||||
elif polarity > 0 and stored_band in POSITIVE_BANDS and load >= 8.0:
|
||||
band = stored_band
|
||||
else:
|
||||
band = "relaxed"
|
||||
recovery_band = "steady"
|
||||
if load > 0.5 and load < peak * 0.9:
|
||||
recovery_band = "recovering"
|
||||
elif load >= peak * 0.98 and peak > 0:
|
||||
recovery_band = "reinforced"
|
||||
remaining = half_life * math.log2(max(1.0, load)) if load > 1.0 else 0.0
|
||||
return {
|
||||
"dynamics_version": DYNAMICS_VERSION,
|
||||
"expression_band": band,
|
||||
"base_band": stored_band,
|
||||
"load": round(load, 4),
|
||||
"peak_intensity": round(peak, 4),
|
||||
"decay_started_at": started,
|
||||
"half_life": half_life,
|
||||
"polarity": polarity,
|
||||
"recovery_band": recovery_band,
|
||||
"expires_at": current_ts + remaining if remaining > 0 else 0.0,
|
||||
"projection_revision": max(1, min(1000000, int(_finite(raw.get("projection_revision"), 1)))),
|
||||
}
|
||||
|
||||
|
||||
def settle_interaction_dynamics(
|
||||
existing: Any,
|
||||
*,
|
||||
requested_band: str,
|
||||
event_kind: str,
|
||||
intensity: Any,
|
||||
now: Any,
|
||||
) -> dict[str, Any]:
|
||||
current_ts = max(0.0, _finite(now))
|
||||
prior = project_interaction_dynamics(existing, now=current_ts)
|
||||
prior_load = _finite(prior.get("load"))
|
||||
prior_polarity = int(_finite(prior.get("polarity"), 0))
|
||||
event_intensity = max(0.0, min(100.0, _finite(intensity)))
|
||||
kind = str(event_kind or "neutral").strip().lower()
|
||||
requested = requested_band if requested_band in NEGATIVE_BANDS | POSITIVE_BANDS | {"relaxed"} else "relaxed"
|
||||
|
||||
if kind == "hurt" and requested in NEGATIVE_BANDS:
|
||||
base = prior_load if prior_polarity < 0 else 0.0
|
||||
load = min(100.0, base + max(20.0, event_intensity) * max(0.25, 1.0 - base / 140.0))
|
||||
polarity = -1
|
||||
base_band = requested
|
||||
half_life = 3600.0
|
||||
elif prior_polarity < 0 and kind in {"apology", "comfort", "praise", "intimacy", "play"}:
|
||||
factor = {"apology": 0.35, "comfort": 0.25, "praise": 0.12, "intimacy": 0.20, "play": 0.10}[kind]
|
||||
load = max(0.0, prior_load - max(6.0, event_intensity * factor))
|
||||
polarity = -1 if load > 0.5 else 0
|
||||
base_band = str(prior.get("base_band") or "hurt")
|
||||
half_life = _finite(prior.get("half_life"), 3600.0)
|
||||
elif requested in POSITIVE_BANDS:
|
||||
base = prior_load if prior_polarity > 0 else 0.0
|
||||
load = min(100.0, base * 0.75 + max(10.0, event_intensity * 0.65))
|
||||
polarity = 1
|
||||
base_band = requested
|
||||
half_life = 7200.0
|
||||
else:
|
||||
return prior
|
||||
|
||||
peak = max(load, _finite(prior.get("peak_intensity")) if polarity == prior_polarity else 0.0)
|
||||
raw = {
|
||||
"dynamics_version": DYNAMICS_VERSION,
|
||||
"expression_band": base_band,
|
||||
"base_band": base_band,
|
||||
"load": load,
|
||||
"peak_intensity": peak,
|
||||
"decay_started_at": current_ts,
|
||||
"half_life": half_life,
|
||||
"polarity": polarity,
|
||||
"projection_revision": int(_finite(prior.get("projection_revision"), 0)) + 1,
|
||||
}
|
||||
return project_interaction_dynamics(raw, now=current_ts)
|
||||
|
||||
|
||||
__all__ = ["DYNAMICS_VERSION", "project_interaction_dynamics", "settle_interaction_dynamics"]
|
||||
|
|
@ -1482,7 +1482,12 @@ class MemoryCompanionAdapterMixin:
|
|||
if bool(getattr(self, "enable_custom_relationship_stage_policy", False))
|
||||
else None
|
||||
)
|
||||
projection = relationship_projection_for_bridge(user.get("relationship_score", 0), policy)
|
||||
projection = relationship_projection_for_bridge(
|
||||
user.get("relationship_score", 0),
|
||||
policy,
|
||||
previous_stage_key=user.get("relationship_phase_key", ""),
|
||||
)
|
||||
user["relationship_phase_key"] = projection.get("phase_key", "acquaintance")
|
||||
role_getter = getattr(self, "_private_user_role", None)
|
||||
try:
|
||||
role = role_getter(user, user_id) if callable(role_getter) else str(user.get("relationship_role") or "friend")
|
||||
|
|
|
|||
|
|
@ -187,7 +187,13 @@ def normalize_relationship_stage_policy(value: Any) -> list[dict[str, Any]]:
|
|||
return normalized
|
||||
|
||||
|
||||
def relationship_stage_for_score(value: Any, policy: Any = None) -> dict[str, Any]:
|
||||
def relationship_stage_for_score(
|
||||
value: Any,
|
||||
policy: Any = None,
|
||||
*,
|
||||
previous_stage_key: Any = "",
|
||||
hysteresis_margin: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
try:
|
||||
score = int(value)
|
||||
except (TypeError, ValueError):
|
||||
|
|
@ -199,6 +205,22 @@ def relationship_stage_for_score(value: Any, policy: Any = None) -> dict[str, An
|
|||
if stage["min"] <= score <= stage["max"]:
|
||||
stage_index = index
|
||||
break
|
||||
raw_stage_index = stage_index
|
||||
previous_key = str(previous_stage_key or "").strip()
|
||||
previous_index = next((index for index, item in enumerate(stages) if item["key"] == previous_key), -1)
|
||||
margin = max(0, min(200, int(hysteresis_margin or 0)))
|
||||
hysteresis_applied = False
|
||||
if previous_index >= 0 and stage_index != previous_index:
|
||||
if stage_index > previous_index:
|
||||
enter_score = int(stages[previous_index + 1]["min"]) + margin
|
||||
if score < enter_score:
|
||||
stage_index = previous_index
|
||||
hysteresis_applied = True
|
||||
else:
|
||||
exit_score = int(stages[previous_index]["min"]) - margin
|
||||
if score > exit_score:
|
||||
stage_index = previous_index
|
||||
hysteresis_applied = True
|
||||
stage = deepcopy(stages[stage_index])
|
||||
span = max(0, int(stage["max"]) - int(stage["min"]))
|
||||
within = 1.0 if span == 0 else (score - int(stage["min"])) / span
|
||||
|
|
@ -212,14 +234,22 @@ def relationship_stage_for_score(value: Any, policy: Any = None) -> dict[str, An
|
|||
"min": RELATIONSHIP_SCORE_MIN,
|
||||
"max": RELATIONSHIP_SCORE_MAX,
|
||||
"trend": "unknown",
|
||||
"previous_phase_key": previous_key,
|
||||
"raw_stage_index": raw_stage_index,
|
||||
"hysteresis_applied": hysteresis_applied,
|
||||
"authority": "private_companion.relationship_score",
|
||||
"read_only": True,
|
||||
"schema_version": "chat.relationship_projection.v1",
|
||||
}
|
||||
|
||||
|
||||
def relationship_projection_for_bridge(value: Any, policy: Any = None) -> dict[str, Any]:
|
||||
projection = relationship_stage_for_score(value, policy)
|
||||
def relationship_projection_for_bridge(
|
||||
value: Any,
|
||||
policy: Any = None,
|
||||
*,
|
||||
previous_stage_key: Any = "",
|
||||
) -> dict[str, Any]:
|
||||
projection = relationship_stage_for_score(value, policy, previous_stage_key=previous_stage_key)
|
||||
phase = projection["phase"]
|
||||
return {
|
||||
"schema_version": projection["schema_version"],
|
||||
|
|
@ -232,6 +262,7 @@ def relationship_projection_for_bridge(value: Any, policy: Any = None) -> dict[s
|
|||
"address_level": phase["address_level"],
|
||||
"proactive_care_limit": phase["proactive_care_limit"],
|
||||
"soft_behaviors": {field: bool(phase[field]) for field in _BOOL_FIELDS},
|
||||
"hysteresis_applied": bool(projection.get("hysteresis_applied")),
|
||||
}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,57 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from companion_interaction_expression import current_interaction_projection
|
||||
from interaction_dynamics import settle_interaction_dynamics
|
||||
from relationship_policy import relationship_stage_for_score
|
||||
|
||||
|
||||
class EmotionE5InteractionDynamicsTests(unittest.TestCase):
|
||||
def test_ninety_minute_boundary_has_no_ttl_cliff(self) -> None:
|
||||
state = settle_interaction_dynamics(
|
||||
{}, requested_band="hurt", event_kind="hurt", intensity=60, now=1000.0
|
||||
)
|
||||
at_89 = current_interaction_projection(state, now=1000.0 + 89 * 60)
|
||||
at_90 = current_interaction_projection(state, now=1000.0 + 90 * 60)
|
||||
self.assertEqual("hurt", at_89["expression_band"])
|
||||
self.assertEqual("hurt", at_90["expression_band"])
|
||||
self.assertLess(at_90["load"], at_89["load"])
|
||||
self.assertLess(at_89["load"] - at_90["load"], 1.0)
|
||||
|
||||
def test_repeated_hurt_is_bounded_and_apology_recovers_gradually(self) -> None:
|
||||
state: dict = {}
|
||||
for offset in range(6):
|
||||
state = settle_interaction_dynamics(
|
||||
state, requested_band="avoidant", event_kind="hurt", intensity=95, now=1000.0 + offset
|
||||
)
|
||||
self.assertLessEqual(state["load"], 100.0)
|
||||
recovered = settle_interaction_dynamics(
|
||||
state, requested_band="warm", event_kind="apology", intensity=80, now=1010.0
|
||||
)
|
||||
self.assertLess(recovered["load"], state["load"])
|
||||
self.assertGreater(recovered["load"], 0.0)
|
||||
self.assertIn(recovered["expression_band"], {"hurt", "avoidant"})
|
||||
self.assertEqual("recovering", recovered["recovery_band"])
|
||||
|
||||
def test_relationship_stage_uses_enter_and_exit_margins(self) -> None:
|
||||
self.assertEqual(
|
||||
"acquaintance",
|
||||
relationship_stage_for_score(205, previous_stage_key="acquaintance")["phase"]["key"],
|
||||
)
|
||||
self.assertEqual(
|
||||
"familiar",
|
||||
relationship_stage_for_score(220, previous_stage_key="acquaintance")["phase"]["key"],
|
||||
)
|
||||
self.assertEqual(
|
||||
"familiar",
|
||||
relationship_stage_for_score(195, previous_stage_key="familiar")["phase"]["key"],
|
||||
)
|
||||
self.assertEqual(
|
||||
"acquaintance",
|
||||
relationship_stage_for_score(179, previous_stage_key="familiar")["phase"]["key"],
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
@ -111,6 +111,7 @@ from .companion_interaction_expression import (
|
|||
expression_decision_prompt,
|
||||
)
|
||||
from .emotion_event_ledger import record_recent_emotion_event
|
||||
from .interaction_dynamics import project_interaction_dynamics, settle_interaction_dynamics
|
||||
from .planning import (
|
||||
build_daily_plan_prompt,
|
||||
build_detail_enhancement_prompt,
|
||||
|
|
@ -319,7 +320,13 @@ class UserMemoryMixin:
|
|||
if bool(getattr(self, "enable_custom_relationship_stage_policy", False))
|
||||
else None
|
||||
)
|
||||
stage = relationship_stage_for_score(score, policy)["phase"]
|
||||
stage_projection = relationship_stage_for_score(
|
||||
score,
|
||||
policy,
|
||||
previous_stage_key=user.get("relationship_phase_key", ""),
|
||||
)
|
||||
stage = stage_projection["phase"]
|
||||
user["relationship_phase_key"] = stage.get("key", "acquaintance")
|
||||
stage_key = str(stage.get("key") or "acquaintance")
|
||||
if stage_key in {"deeply_distant", "strongly_distant", "distant"}:
|
||||
level = "陌生"
|
||||
|
|
@ -4715,7 +4722,7 @@ Local classifier result:
|
|||
"updated_at": now,
|
||||
}
|
||||
|
||||
if existing.get("manual_override") and (not existing.get("expires_at") or _safe_float(existing.get("expires_at"), 0) > now):
|
||||
if not contact_active and existing.get("manual_override") and (not existing.get("expires_at") or _safe_float(existing.get("expires_at"), 0) > now):
|
||||
event_recorder = getattr(self, "_record_interaction_emotion_event", None)
|
||||
if callable(event_recorder):
|
||||
event_recorder(
|
||||
|
|
@ -4773,6 +4780,20 @@ Local classifier result:
|
|||
user["current_interaction"] = existing
|
||||
return
|
||||
|
||||
dynamics: dict[str, Any] = {}
|
||||
dynamics_kind = emotion_event if emotion_event != "neutral" else inbound_intent
|
||||
if not contact_active and dynamics_kind in {"hurt", "apology", "comfort", "praise", "intimacy", "play"}:
|
||||
dynamics = settle_interaction_dynamics(
|
||||
existing,
|
||||
requested_band=band,
|
||||
event_kind=dynamics_kind,
|
||||
intensity=intensity or pressure * 20,
|
||||
now=now,
|
||||
)
|
||||
if dynamics:
|
||||
band = str(dynamics.get("expression_band") or band)
|
||||
expires_at = _safe_float(dynamics.get("expires_at"), expires_at)
|
||||
|
||||
event_recorder = getattr(self, "_record_interaction_emotion_event", None)
|
||||
emotion_event_record = event_recorder(
|
||||
user,
|
||||
|
|
@ -4782,8 +4803,7 @@ Local classifier result:
|
|||
status="applied",
|
||||
expires_at=expires_at,
|
||||
) if callable(event_recorder) else None
|
||||
user["current_interaction"] = current_interaction_projection(
|
||||
{
|
||||
interaction_payload = {
|
||||
"expression_band": band,
|
||||
"source": "automatic",
|
||||
"reason": reason_code,
|
||||
|
|
@ -4792,7 +4812,11 @@ Local classifier result:
|
|||
"manual_override": False,
|
||||
"last_event_id": (emotion_event_record or {}).get("event_id", ""),
|
||||
"trace_id": (emotion_event_record or {}).get("trace_id", ""),
|
||||
},
|
||||
}
|
||||
if dynamics:
|
||||
interaction_payload.update(dynamics)
|
||||
user["current_interaction"] = current_interaction_projection(
|
||||
interaction_payload,
|
||||
relationship_role=role,
|
||||
relationship_mode=relationship_mode,
|
||||
relationship_score=user.get("relationship_score"),
|
||||
|
|
@ -6328,7 +6352,13 @@ bot_promises 只记录 Bot 明确承诺要提醒、记住、转述、发送或
|
|||
if bool(getattr(self, "enable_custom_relationship_stage_policy", False))
|
||||
else None
|
||||
)
|
||||
stage = relationship_stage_for_score(user.get("relationship_score", 0), policy)["phase"]
|
||||
stage_projection = relationship_stage_for_score(
|
||||
user.get("relationship_score", 0),
|
||||
policy,
|
||||
previous_stage_key=user.get("relationship_phase_key", ""),
|
||||
)
|
||||
stage = stage_projection["phase"]
|
||||
user["relationship_phase_key"] = stage.get("key", "acquaintance")
|
||||
relationship_baseline = {
|
||||
"stage_key": stage.get("key"),
|
||||
"tone": stage.get("tone"),
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用