56 lines
1.8 KiB
Python
56 lines
1.8 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import re
|
||
|
|
from typing import Any
|
||
|
|
|
||
|
|
|
||
|
|
class WeChatMentionAdapter:
|
||
|
|
@staticmethod
|
||
|
|
def strip_regexes(ctx: dict[str, Any], cfg: dict[str, Any], agent_id: str) -> list[re.Pattern]:
|
||
|
|
patterns: list[re.Pattern] = []
|
||
|
|
mode = ctx.get("mode", "personal")
|
||
|
|
|
||
|
|
if mode == "mp":
|
||
|
|
patterns.append(re.compile(r"@[\u4e00-\u9fff\w]+"))
|
||
|
|
elif mode == "wecom":
|
||
|
|
agent_name = cfg.get("agent_name", "")
|
||
|
|
if agent_name:
|
||
|
|
patterns.append(re.compile(rf"@{re.escape(agent_name)}"))
|
||
|
|
patterns.append(re.compile(r"@all"))
|
||
|
|
elif mode == "personal":
|
||
|
|
patterns.append(re.compile(r"@[\u4e00-\u9fff\w]+"))
|
||
|
|
|
||
|
|
return patterns
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def strip_patterns(ctx: dict[str, Any], cfg: dict[str, Any], agent_id: str) -> list[str]:
|
||
|
|
patterns: list[str] = []
|
||
|
|
mode = ctx.get("mode", "personal")
|
||
|
|
|
||
|
|
if mode == "wecom":
|
||
|
|
agent_name = cfg.get("agent_name", "")
|
||
|
|
if agent_name:
|
||
|
|
patterns.append(f"@{agent_name}")
|
||
|
|
|
||
|
|
return patterns
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def strip_mentions(text: str, ctx: dict[str, Any], cfg: dict[str, Any], agent_id: str) -> str:
|
||
|
|
mode = ctx.get("mode", "personal")
|
||
|
|
agent_name = cfg.get("agent_name", "")
|
||
|
|
|
||
|
|
if mode == "wecom" and agent_name:
|
||
|
|
text = re.sub(rf"@{re.escape(agent_name)}\s*", "", text)
|
||
|
|
|
||
|
|
text = re.sub(r"@all\s*", "", text, flags=re.IGNORECASE)
|
||
|
|
|
||
|
|
def _wrap_other_mention(m: re.Match) -> str:
|
||
|
|
name = m.group(0).strip().lstrip("@").strip()
|
||
|
|
if mode == "wecom" and name == agent_name:
|
||
|
|
return ""
|
||
|
|
return f"<at>{name}</at>"
|
||
|
|
|
||
|
|
text = re.sub(r"@[\u4e00-\u9fff\w]+\s*", _wrap_other_mention, text)
|
||
|
|
|
||
|
|
return text.strip()
|