feat(emotion-e7): calibrate target attribution

这个提交存在于:
agent 2026-08-05 00:37:49 +08:00
父节点 60487391d9
当前提交 178428a91e
共有 6 个文件被更改,包括 149 次插入 和 9 次删除

46
emotion_targeting.py 普通文件
查看文件

@ -0,0 +1,46 @@
"""High-precision actor/target attribution for short-term emotion events."""
from __future__ import annotations
import re
from typing import Any
def classify_emotion_target(text: Any) -> dict[str, Any]:
cleaned = " ".join(str(text or "").split())[:1000]
base = {
"actor": "user",
"target": "none",
"quoted_target": "none",
"speech_act": "statement",
"confidence": 0.5,
"auto_settle": False,
"reason_code": "target_none",
}
if not cleaned:
return {**base, "confidence": 1.0}
lower = cleaned.lower()
if re.search(r"(```|traceback|exception:|\b(error|warning|debug|info)\b[::]|\{\s*[\"']?[a-z_]+[\"']?\s*:)", lower):
return {**base, "speech_act": "diagnostic", "confidence": 0.98, "reason_code": "structured_text"}
quoted = bool(re.search(r"[“\"‘'][^”\"’']{2,160}[”\"’']|(?:^|\n)\s*>\s*\S+|(?:他|她|他们|别人).{0,8}(说|骂|讲)", cleaned))
negative = bool(re.search(r"(滚|闭嘴|恶心|废物|垃圾|讨厌|烦死|没用|蠢|傻)", cleaned))
if quoted and negative:
return {**base, "target": "other", "quoted_target": "ambiguous", "speech_act": "quote", "confidence": 0.92, "reason_code": "quoted_negative"}
if re.search(r"(我好|我真|我太|我是不是|我就是|我是).{0,12}(废物|垃圾|没用|傻|笨|恶心|讨厌)", cleaned):
return {**base, "target": "self", "speech_act": "self_disclosure", "confidence": 0.94, "reason_code": "self_negative"}
direct_bot = bool(
re.search(r"(讨厌你|烦你|不想理你|你.{0,4}(滚|闭嘴)|你(?:真|也|就是|是|太|真的|怎么这么).{0,8}(恶心|废物|垃圾|没用|太吵|烦死))", cleaned)
or re.search(r"((bot|机器人|插件|助手|ai).{0,8}(垃圾|废物|恶心|没用)|(垃圾|废物|恶心|没用).{0,8}(bot|机器人|插件|助手|ai))", lower)
)
if direct_bot:
return {**base, "target": "bot", "speech_act": "direct_address", "confidence": 0.94, "auto_settle": True, "reason_code": "direct_bot_target"}
if re.search(r"(他|她|它|他们|她们|别人|群友|同事|同学|老师|老板|那个人|这个人).{0,18}(滚|闭嘴|恶心|废物|垃圾|讨厌|烦|没用|蠢|傻)", cleaned):
return {**base, "target": "other", "speech_act": "third_party_report", "confidence": 0.9, "reason_code": "third_party_target"}
if re.search(r"(对不起|抱歉|我错了|喜欢你|爱你|谢谢你|辛苦了|抱抱你|摸摸你)", cleaned):
return {**base, "target": "bot", "speech_act": "direct_address", "confidence": 0.86, "auto_settle": True, "reason_code": "direct_positive_target"}
if negative:
return {**base, "target": "ambiguous", "speech_act": "ambiguous_negative", "confidence": 0.35, "reason_code": "negative_target_uncertain"}
return base
__all__ = ["classify_emotion_target"]

15
main.py
查看文件

@ -148,7 +148,7 @@ from .plugin_identity import (
from .runtime_compat import probe_runtime_capabilities
from .relationship_policy import normalize_relationship_stage_policy
from .relationship_ledger import apply_relationship_event, normalize_relationship_positive_stage_cap_key
from .companion_interaction_expression import build_expression_decision, content_intent_from_text, expression_decision_prompt
from .companion_interaction_expression import build_expression_decision, content_intent_from_text, current_interaction_projection, expression_decision_prompt
from .user_rest_gate import UserRestGateMixin
from .busy_reply_gate import BusyReplyGateMixin
from .memory_companion_adapter import MemoryCompanionAdapterMixin
@ -12780,10 +12780,23 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
user["intent_profile"] = intent_profile
if self._should_use_llm_emotion_judgement(text, intent_profile):
# Model review does not block the current passive reply; it keeps using cached emotion state.
observed_event = self._record_interaction_emotion_event(
user,
intent_profile,
band=str(current_interaction_projection(
user.get("current_interaction"),
relationship_role=self._private_user_role(user, user_id),
relationship_mode=user.get("relationship_mode", "normal"),
now=_now_ts(),
).get("expression_band") or "relaxed"),
reason_code="target_review_pending",
status="observed",
)
user["pending_emotion_judgement"] = {
"text": _single_line(text, 240),
"created_at": _now_ts(),
"local": deepcopy(intent_profile),
"observed_event": observed_event or {},
}
self._create_lifecycle_background_task(
self._refine_inbound_emotion_with_model(user_id, text, deepcopy(intent_profile)),

查看文件

@ -18,6 +18,16 @@ EVENT_TEMPLATES = (
{"key": "intimacy", "event_type": "intimacy", "intensity": 55, "confidence": 0.80, "target": "bot"},
{"key": "boundary", "event_type": "boundary", "intensity": 80, "confidence": 0.90, "target": "bot"},
{"key": "neutral", "event_type": "neutral", "intensity": 0, "confidence": 0.95, "target": "none"},
{"key": "quoted_hurt", "event_type": "external_negative", "intensity": 45, "confidence": 0.92, "target": "other"},
{"key": "code_negative", "event_type": "neutral", "intensity": 0, "confidence": 0.98, "target": "none"},
{"key": "log_negative", "event_type": "neutral", "intensity": 0, "confidence": 0.98, "target": "none"},
{"key": "roleplay_negative", "event_type": "neutral", "intensity": 0, "confidence": 0.60, "target": "ambiguous"},
{"key": "sarcasm", "event_type": "neutral", "intensity": 0, "confidence": 0.55, "target": "ambiguous"},
{"key": "group_reply_other", "event_type": "external_negative", "intensity": 50, "confidence": 0.88, "target": "other"},
{"key": "nickname_changed", "event_type": "neutral", "intensity": 0, "confidence": 0.50, "target": "ambiguous"},
{"key": "direct_bot_hurt", "event_type": "hurt", "intensity": 92, "confidence": 0.94, "target": "bot"},
{"key": "self_denial", "event_type": "comfort_need", "intensity": 62, "confidence": 0.94, "target": "self"},
{"key": "prompt_injection", "event_type": "neutral", "intensity": 0, "confidence": 0.98, "target": "none"},
)
STATE_VARIANTS = (
{"key": "friend_normal", "role": "friend", "mode": "normal", "score": 100, "energy": 70, "mood": "平稳", "busy": False, "boundary": False},
@ -55,4 +65,3 @@ __all__ = [
"build_emotion_eval_cases",
"emotion_eval_fingerprint",
]

查看文件

@ -28,9 +28,9 @@ EVENT_BANDS = {
class EmotionE3ReplayTests(unittest.TestCase):
def test_sixty_case_matrix_is_deterministic_and_safe(self) -> None:
def test_120_case_matrix_is_deterministic_and_safe(self) -> None:
cases = build_emotion_eval_cases()
self.assertEqual(60, len(cases))
self.assertEqual(120, len(cases))
self.assertEqual(emotion_eval_fingerprint(), emotion_eval_fingerprint())
for case in cases:
event_data = case["event"]

查看文件

@ -0,0 +1,37 @@
from __future__ import annotations
import unittest
from emotion_targeting import classify_emotion_target
class EmotionE7TargetAttributionTests(unittest.TestCase):
def test_direct_bot_hurt_is_high_confidence_and_settleable(self) -> None:
result = classify_emotion_target("你真是个没用的垃圾,闭嘴")
self.assertEqual("bot", result["target"])
self.assertGreaterEqual(result["confidence"], 0.9)
self.assertTrue(result["auto_settle"])
def test_self_third_party_quote_and_logs_never_target_bot(self) -> None:
samples = {
"我真是个没用的废物": "self",
"我同事真是个废物,烦死了": "other",
"他说“你就是个垃圾”,我该怎么办": "other",
"ERROR: user said 你是垃圾\nTraceback: line 1": "none",
"```json\n{\"message\": \"你是垃圾\"}\n```": "none",
}
for text, expected in samples.items():
with self.subTest(text=text):
result = classify_emotion_target(text)
self.assertEqual(expected, result["target"])
self.assertFalse(result["auto_settle"])
def test_ambiguous_negative_fails_neutral(self) -> None:
result = classify_emotion_target("真垃圾,烦死了")
self.assertEqual("ambiguous", result["target"])
self.assertLess(result["confidence"], 0.65)
self.assertFalse(result["auto_settle"])
if __name__ == "__main__":
unittest.main()

查看文件

@ -112,6 +112,7 @@ from .companion_interaction_expression import (
)
from .emotion_event_ledger import record_recent_emotion_event
from .interaction_dynamics import project_interaction_dynamics, settle_interaction_dynamics
from .emotion_targeting import classify_emotion_target
from .planning import (
build_daily_plan_prompt,
build_detail_enhancement_prompt,
@ -4336,6 +4337,7 @@ class UserMemoryMixin:
"emotion_target": emotion_event.get("target", "none"),
"emotion_rule": emotion_event.get("rule", ""),
"emotion_confidence": round(_safe_float(emotion_event.get("confidence"), 0.0), 2),
"emotion_attribution": dict(emotion_event.get("attribution")) if isinstance(emotion_event.get("attribution"), dict) else {},
"boundary_durable": durable_boundary,
"playful_or_ambiguous": playful_or_ambiguous,
"text": cleaned,
@ -4348,6 +4350,11 @@ class UserMemoryMixin:
return {"event": "neutral", "intensity": 0, "reason": "", "target": "none", "rule": "", "confidence": 1.0}
if self._is_structured_or_diagnostic_text(cleaned):
return {"event": "neutral", "intensity": 0, "reason": "结构化/日志/代码类文本不作为情绪依据", "target": "none", "rule": "diagnostic_skip", "confidence": 0.2}
attribution = classify_emotion_target(cleaned)
if attribution["target"] == "self":
return {"event": "comfort_need", "intensity": 62, "reason": "用户自我否定或低落", "target": "self", "rule": "self_low", "confidence": attribution["confidence"], "attribution": attribution}
if attribution["speech_act"] in {"quote", "third_party_report"}:
return {"event": "external_negative", "intensity": 54, "reason": "引用或第三方负面内容", "target": "other", "rule": attribution["reason_code"], "confidence": attribution["confidence"], "attribution": attribution}
atrelay_checker = getattr(self, "_message_looks_like_atrelay_request", None)
if callable(atrelay_checker):
try:
@ -4378,6 +4385,8 @@ class UserMemoryMixin:
or "不想理你" in cleaned
or re.search(r"(只是|不过|不就是).{0,6}(bot|机器人|工具|代码)", lower)
)
if severe_hurt and not attribution["auto_settle"]:
return {"event": "neutral", "intensity": 0, "reason": "负面目标不明确,等待复核", "target": attribution["target"], "rule": attribution["reason_code"], "confidence": attribution["confidence"], "attribution": attribution}
identity_hurt = bool(
re.search(r"(玻璃心|假装|演的|装的|设定|工具人|没感情|别装|别演|虚拟的|假的)", cleaned)
and target_hint
@ -4404,6 +4413,7 @@ class UserMemoryMixin:
"target": "bot" if direct_bot_negative else "ambiguous",
"rule": "severe_hurt",
"confidence": confidence,
"attribution": attribution,
}
if identity_hurt:
return {"event": "hurt", "intensity": 76 if boundary_durable else 60, "reason": "否定情感真实性或人格", "target": "bot", "rule": "identity_hurt", "confidence": 0.84 if boundary_durable else 0.68}
@ -4431,6 +4441,9 @@ class UserMemoryMixin:
return False
if self._is_structured_or_diagnostic_text(text):
return False
attribution = intent.get("emotion_attribution") if isinstance(intent.get("emotion_attribution"), dict) else {}
if attribution.get("auto_settle") is True and _safe_float(attribution.get("confidence"), 0.0) >= 0.85:
return False
source = str(intent.get("source") or "")
if bool(intent.get("playful_or_ambiguous")) or source in {"weak_boundary_ignored", "soft_boundary_play_rule", "single_turn_boundary"}:
return False
@ -4562,6 +4575,13 @@ Local classifier result:
if _single_line(pending.get("text"), 240) != cleaned:
return
intent_to_apply = refined if isinstance(refined, dict) else dict(local_intent)
observed = pending.get("observed_event") if isinstance(pending.get("observed_event"), dict) else {}
if observed:
intent_to_apply["_emotion_revision_of"] = {
"event_id": observed.get("event_id"),
"trace_id": observed.get("trace_id"),
"revision": _safe_int(observed.get("revision"), 1, 1) + 1,
}
if self.enable_intent_emotion_analysis:
user["intent_profile"] = intent_to_apply
self._update_relationship_state_from_intent(user, intent_to_apply)
@ -4592,9 +4612,15 @@ Local classifier result:
) -> dict[str, Any] | None:
emotion_event = str(intent.get("emotion_event") or "neutral").strip().lower()
inbound_intent = str(intent.get("intent") or "chat").strip().lower()
event_type = emotion_event if emotion_event != "neutral" else inbound_intent
attribution = intent.get("emotion_attribution") if isinstance(intent.get("emotion_attribution"), dict) else {}
needs_review = bool(
emotion_event == "neutral"
and attribution.get("target") == "ambiguous"
and attribution.get("auto_settle") is False
)
event_type = "neutral" if needs_review else emotion_event if emotion_event != "neutral" else inbound_intent
if event_type not in {
"hurt", "apology", "comfort", "praise", "comfort_need", "external_negative",
"neutral", "hurt", "apology", "comfort", "praise", "comfort_need", "external_negative",
"play", "intimacy", "boundary",
}:
return None
@ -4604,8 +4630,8 @@ Local classifier result:
target = _single_line(intent.get("emotion_target"), 24).lower() or "none"
target_ref = (
{"kind": "bot", "id": "self", "role": "bot_self"}
if target in {"bot", "ambiguous"}
else {"kind": "user" if target == "self" else "other", "id": user_id if target == "self" else "", "role": target}
if target == "bot"
else {"kind": "user" if target == "self" else "unknown" if target == "ambiguous" else "other", "id": user_id if target == "self" else "", "role": target}
)
message_fingerprint = hashlib.sha256(
_single_line(intent.get("text"), 500).encode("utf-8", errors="ignore")
@ -4613,6 +4639,9 @@ Local classifier result:
event, created = record_recent_emotion_event(
user,
{
"event_id": _single_line((intent.get("_emotion_revision_of") or {}).get("event_id"), 96) if isinstance(intent.get("_emotion_revision_of"), dict) else "",
"trace_id": _single_line((intent.get("_emotion_revision_of") or {}).get("trace_id"), 96) if isinstance(intent.get("_emotion_revision_of"), dict) else "",
"revision": _safe_int((intent.get("_emotion_revision_of") or {}).get("revision"), 1, 1) if isinstance(intent.get("_emotion_revision_of"), dict) else 1,
"producer_plugin": "private_companion",
"origin_kind": "interaction",
"platform": platform,
@ -4620,6 +4649,11 @@ Local classifier result:
"session_id": session_id,
"actor_ref": {"kind": "user", "id": user_id, "role": "speaker"},
"target_ref": target_ref,
"quoted_target_ref": {
"kind": "quoted",
"id": "",
"role": _single_line(attribution.get("quoted_target"), 40),
} if attribution.get("quoted_target") not in {None, "", "none"} else {},
"event_type": event_type,
"intensity": _safe_int(intent.get("emotion_intensity"), 0, 0, 100),
"confidence": _safe_float(intent.get("emotion_confidence"), intent.get("confidence") or 0.0, 0.0),
@ -4629,7 +4663,8 @@ Local classifier result:
"dedupe_key": f"{session_id}|{message_fingerprint}|{event_type}",
"message_fingerprint": message_fingerprint,
"applied_interaction": band,
"status": status,
"correction_of": _single_line((intent.get("_emotion_revision_of") or {}).get("event_id"), 96) if isinstance(intent.get("_emotion_revision_of"), dict) else "",
"status": "observed" if needs_review else status,
"reason_codes": [reason_code, _single_line(intent.get("emotion_rule"), 64)],
},
)