255 lines
11 KiB
Python
255 lines
11 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""识别客户的“收尾确认语”,避免机器人和客户无限互道“好的 / 谢谢”。
|
||
|
||
人工客服的习惯:客户回“谢谢”可以回一句“不客气”;客户接着回“好的”“嗯”“👌”或者一个
|
||
表情包,就不再接了。这里把这个判断做成确定性的规则,两条回复链路(协议引擎、视觉流程)
|
||
在调用模型之前先问一次:这轮到底要不要回。
|
||
|
||
判断只看客户这轮的文字和最近几轮历史,不依赖模型,不会误伤带实际内容的消息:
|
||
只要客户的话里有确认语以外的内容,就照常回复。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
from dataclasses import dataclass, field
|
||
from typing import Any, Iterable
|
||
|
||
# 纯确认:客户表示“知道了 / 同意”,不需要再接话。
|
||
ACK_TOKENS: tuple[str, ...] = (
|
||
"好的", "好滴", "好嘞", "好哒", "好呀", "好啊", "好吧", "好", "行的", "行吧", "行", "可以", "成",
|
||
"嗯嗯", "嗯呐", "嗯", "恩恩", "恩", "哦哦", "哦", "噢", "收到", "知道了", "知道啦", "明白了", "明白",
|
||
"了解", "清楚了", "是的", "对的", "对", "ok", "okay", "okk", "好的好的", "没问题", "没事", "没事的",
|
||
"不客气", "不用谢", "客气了", "应该的", "666", "棒", "赞", "牛", "厉害", "哈哈",
|
||
)
|
||
# 致谢 / 道别:第一次值得回一句简短的话,之后不再接。
|
||
THANKS_TOKENS: tuple[str, ...] = (
|
||
"谢谢你", "谢谢您", "谢谢啦", "谢谢", "谢啦", "谢了", "感谢", "多谢", "辛苦了", "辛苦你了", "辛苦您了",
|
||
"辛苦", "麻烦了", "麻烦你了", "麻烦您了", "thanks", "thankyou", "thx", "3q",
|
||
)
|
||
FAREWELL_TOKENS: tuple[str, ...] = (
|
||
"晚安", "再见", "拜拜", "拜", "回聊", "先这样", "先不聊了", "不打扰了", "下次聊", "有事再联系",
|
||
"我先忙", "我先忙了", "改天聊", "先去忙了", "去忙吧", "忙去吧", "睡了",
|
||
)
|
||
# 语气词和口头补字,可以附在确认语前后。
|
||
TRAILER_CHARS = set("哈呀啦哦呢嘞滴哒吧的了噢喔嗯呐哟咯嘛啊呃额噜咧嘿呵")
|
||
# 称呼,可以附在确认语后面(“谢谢医生”“好的老师”)。
|
||
ADDRESS_TOKENS: tuple[str, ...] = ("医生", "大夫", "老师", "助理", "亲", "您", "你", "小姐姐", "小哥哥", "同学")
|
||
# 每轮最多接受的确认语长度(去掉标点、表情后)。
|
||
MAX_ACK_LENGTH = 14
|
||
|
||
# 表情、企微文字表情和贴纸占位符:客户用它们表示“好 / 谢谢 / 再见”,和文字一样处理。
|
||
STICKER_PLACEHOLDER_RE = re.compile(r"[\[【]\s*(?:动画表情|表情包|表情|贴纸|sticker|emoticon)\s*[\]】]", re.IGNORECASE)
|
||
_EMOJI_TOKENS: dict[str, str] = {
|
||
**{ch: "ok" for ch in "👌👍🆗✅☑️✔️🤝😊🙂😄😁😉😀😃😆🤗🥰😍☺️🌹💐❤️🧡💛💚💙💜🩷🫶💪🎉✨🌞☀️👏🙆🌸🍀"},
|
||
**{ch: "谢谢" for ch in "🙏🫡"},
|
||
**{ch: "哈哈" for ch in "😂🤣😹"},
|
||
**{ch: "拜拜" for ch in "👋😴🌙💤"},
|
||
}
|
||
_BRACKET_TOKENS: dict[str, str] = {
|
||
**{name: "ok" for name in (
|
||
"OK", "ok", "强", "赞", "好的", "耶", "胜利", "握手", "微笑", "呲牙", "偷笑", "愉快", "可爱", "玫瑰",
|
||
"鲜花", "爱心", "心", "比心", "太阳", "拥抱", "嘿哈", "奸笑", "机智", "笑脸", "得意", "鼓掌", "OK手势",
|
||
"抱抱", "加油", "好", "666", "牛", "点赞",
|
||
)},
|
||
**{name: "谢谢" for name in ("抱拳", "合十", "感谢", "谢谢", "作揖", "拜托")},
|
||
**{name: "拜拜" for name in ("再见", "挥手", "拜拜", "睡", "月亮", "晚安", "睡觉")},
|
||
**{name: "哈哈" for name in ("捂脸", "破涕为笑", "笑哭", "大笑", "哈哈")},
|
||
}
|
||
_BRACKET_RE = re.compile(r"[\[【]([^\[\]【】]{1,8})[\]】]")
|
||
_STRIP_RE = re.compile(r"[\s,。!!??~~、,.…::;;“”\"'‘’()()\[\]【】<>《》/\\|·\-—_+*#@]+")
|
||
_NON_TEXT_RE = re.compile(r"[^一-鿿0-9a-z]")
|
||
_QUESTION_HINTS: tuple[str, ...] = (
|
||
"吗", "呢", "么", "要不要", "方便", "可以吗", "行吗", "需要", "哪", "什么时候", "啥时候", "几点",
|
||
"多少", "有没有", "是不是", "能不能", "愿不愿", "怎么样", "如何", "还是", "对吧", "请问",
|
||
)
|
||
|
||
|
||
@dataclass
|
||
class ClosingDecision:
|
||
action: str # "reply" | "skip"
|
||
kind: str = "" # "" | "ack" | "thanks" | "farewell"
|
||
reason: str = ""
|
||
hint: str = ""
|
||
consumed: list[str] = field(default_factory=list)
|
||
|
||
@property
|
||
def skip(self) -> bool:
|
||
return self.action == "skip"
|
||
|
||
|
||
def _replace_symbols(text: str) -> str:
|
||
"""Turn emoji, WeCom bracket emoji and sticker placeholders into words."""
|
||
body = STICKER_PLACEHOLDER_RE.sub(" ok ", text)
|
||
|
||
def bracket(match: re.Match) -> str:
|
||
name = match.group(1).strip()
|
||
token = _BRACKET_TOKENS.get(name) or _BRACKET_TOKENS.get(name.upper()) or _BRACKET_TOKENS.get(name.lower())
|
||
return f" {token} " if token else match.group(0)
|
||
|
||
body = _BRACKET_RE.sub(bracket, body)
|
||
return "".join(f" {_EMOJI_TOKENS[ch]} " if ch in _EMOJI_TOKENS else ch for ch in body)
|
||
|
||
|
||
def normalize(text: Any) -> str:
|
||
body = _replace_symbols(str(text or "")).strip().lower()
|
||
body = _STRIP_RE.sub("", body)
|
||
return _NON_TEXT_RE.sub("", body)
|
||
|
||
|
||
def is_reaction_only(text: Any) -> bool:
|
||
"""True when the message has no letters at all: emoji, symbols or a sticker placeholder."""
|
||
raw = str(text or "")
|
||
if STICKER_PLACEHOLDER_RE.search(raw):
|
||
rest = STICKER_PLACEHOLDER_RE.sub("", raw)
|
||
return not _NON_TEXT_RE.sub("", _STRIP_RE.sub("", rest.lower()))
|
||
stripped = _STRIP_RE.sub("", raw.lower())
|
||
if not stripped:
|
||
return False
|
||
return not _NON_TEXT_RE.sub("", stripped)
|
||
|
||
|
||
def _consume(body: str) -> tuple[str, list[str]]:
|
||
"""Greedily strip closing tokens and trailer characters; return (rest, tokens)."""
|
||
tokens: list[str] = []
|
||
ordered = sorted(THANKS_TOKENS + FAREWELL_TOKENS + ACK_TOKENS + ADDRESS_TOKENS, key=len, reverse=True)
|
||
rest = body
|
||
progress = True
|
||
while rest and progress:
|
||
progress = False
|
||
for token in ordered:
|
||
if rest.startswith(token):
|
||
tokens.append(token)
|
||
rest = rest[len(token):]
|
||
progress = True
|
||
break
|
||
if not progress and rest[0] in TRAILER_CHARS:
|
||
rest = rest[1:]
|
||
progress = True
|
||
return rest, tokens
|
||
|
||
|
||
def classify(text: Any) -> str:
|
||
""""" when the message carries real content; otherwise ack / thanks / farewell."""
|
||
raw = str(text or "")
|
||
body = normalize(raw)
|
||
if not body:
|
||
# A lone emoji/sticker we do not know is still just a reaction, not a question.
|
||
return "ack" if is_reaction_only(raw) else ""
|
||
if len(body) > MAX_ACK_LENGTH:
|
||
return ""
|
||
rest, tokens = _consume(body)
|
||
if rest:
|
||
return ""
|
||
if not tokens:
|
||
# Only trailer characters such as 哈哈哈 / 嗯嗯嗯.
|
||
return "ack" if all(ch in TRAILER_CHARS for ch in body) else ""
|
||
if all(token in ADDRESS_TOKENS for token in tokens):
|
||
return ""
|
||
if any(token in FAREWELL_TOKENS for token in tokens):
|
||
return "farewell"
|
||
if any(token in THANKS_TOKENS for token in tokens):
|
||
return "thanks"
|
||
return "ack"
|
||
|
||
|
||
def asks_question(text: Any) -> bool:
|
||
body = str(text or "").strip()
|
||
if not body:
|
||
return False
|
||
if "?" in body or "?" in body:
|
||
return True
|
||
tail = normalize(body)[-12:]
|
||
return any(hint in tail for hint in _QUESTION_HINTS)
|
||
|
||
|
||
def is_sticker_row(message: Any) -> bool:
|
||
"""Database row for a WeCom sticker (content_type 5 or a sticker placeholder body)."""
|
||
if not isinstance(message, dict):
|
||
return False
|
||
try:
|
||
if int(message.get("content_type") or 0) == 5:
|
||
return True
|
||
except (TypeError, ValueError):
|
||
pass
|
||
return bool(STICKER_PLACEHOLDER_RE.fullmatch(str(message.get("content") or "").strip()))
|
||
|
||
|
||
def is_reaction_batch(batch: Iterable[Any] | None) -> bool:
|
||
"""All unanswered rows are stickers/emoji-only, i.e. a reaction rather than a question."""
|
||
rows = [item for item in (batch or []) if isinstance(item, dict)]
|
||
return bool(rows) and all(
|
||
is_sticker_row(item) or is_reaction_only(item.get("content")) for item in rows
|
||
)
|
||
|
||
|
||
def _turns(history: Iterable[Any] | None) -> list[tuple[str, str]]:
|
||
turns: list[tuple[str, str]] = []
|
||
for item in history or []:
|
||
if isinstance(item, dict):
|
||
if "role" in item:
|
||
role = str(item.get("role") or "")
|
||
else:
|
||
role = "assistant" if item.get("is_self") else "user"
|
||
content = str(item.get("content") or "")
|
||
if role == "user" and is_sticker_row(item):
|
||
content = "[表情]"
|
||
else:
|
||
continue
|
||
if role in {"user", "assistant"} and content.strip():
|
||
turns.append((role, content))
|
||
return turns
|
||
|
||
|
||
CLOSING_HINT = (
|
||
"【本轮提示】客户正在礼貌收尾(致谢/道别),只需一句自然简短的回应,例如“不客气,有事随时找我”。"
|
||
"不要再叮嘱、提问、重复前面说过的话或展开新话题。"
|
||
)
|
||
|
||
|
||
def decide(customer_text: Any, history: Iterable[Any] | None = None) -> ClosingDecision:
|
||
"""Decide whether this customer turn deserves a reply.
|
||
|
||
``history`` is the conversation before this turn: either role/content dicts
|
||
(session archive) or database rows with ``is_self``.
|
||
"""
|
||
kind = classify(customer_text)
|
||
if not kind:
|
||
return ClosingDecision("reply")
|
||
turns = _turns(history)
|
||
assistant_turns = [content for role, content in turns if role == "assistant"]
|
||
if not assistant_turns:
|
||
# No context at all: a lone "好" may answer something we cannot see.
|
||
return ClosingDecision("reply", kind, "没有历史上下文")
|
||
last_assistant = assistant_turns[-1]
|
||
if asks_question(last_assistant):
|
||
return ClosingDecision("reply", kind, "上一句在提问,客户的确认是回答")
|
||
# Was the previous customer turn (the one our last reply answered) already a closing?
|
||
previous_customer = ""
|
||
seen_assistant = False
|
||
for role, content in reversed(turns):
|
||
if role == "assistant":
|
||
seen_assistant = True
|
||
continue
|
||
if seen_assistant:
|
||
previous_customer = content
|
||
break
|
||
if previous_customer and classify(previous_customer):
|
||
return ClosingDecision("skip", kind, "客户连续收尾确认,对话已经结束")
|
||
if kind == "ack":
|
||
return ClosingDecision("skip", kind, "客户只回了确认语或表情,不需要再接话")
|
||
return ClosingDecision("reply", kind, "客户首次致谢/道别,简短回应一句", hint=CLOSING_HINT)
|
||
|
||
|
||
def decide_for_messages(messages: Iterable[Any] | None, batch: Iterable[Any] | None) -> ClosingDecision:
|
||
"""Protocol-engine helper: ``messages`` are database rows, ``batch`` the unanswered tail."""
|
||
batch_list = [item for item in (batch or []) if isinstance(item, dict)]
|
||
if not batch_list:
|
||
return ClosingDecision("reply")
|
||
batch_keys = {id(item) for item in batch_list}
|
||
earlier = [item for item in (messages or []) if isinstance(item, dict) and id(item) not in batch_keys]
|
||
customer_text = "\n".join(
|
||
"[表情]" if is_sticker_row(item) else str(item.get("content") or "") for item in batch_list
|
||
)
|
||
return decide(customer_text, earlier)
|