Files
xieyi-weixin-/test_conversation_closing.py
T
2026-09-28 10:02:07 +08:00

234 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""收尾识别:客户只回“好的 / 谢谢”时,像人一样停下来,而不是无限接话。"""
import threading
import unittest
from unittest import mock
import conversation_closing as cc
ADVICE = [
{"role": "user", "content": "我这两天血糖有点高"},
{"role": "assistant", "content": "你也要平时多测血糖哦"},
]
class ClassifyTest(unittest.TestCase):
def test_pure_acknowledgements(self):
for text in ("好", "好的", "好的呢👌", "嗯嗯", "收到", "行", "OK", "知道了哈", "好的好的"):
self.assertEqual(cc.classify(text), "ack", text)
def test_thanks_and_farewell(self):
for text in ("谢谢", "谢谢啦😊", "好的,谢谢!", "谢谢医生", "辛苦了", "麻烦你了"):
self.assertEqual(cc.classify(text), "thanks", text)
for text in ("晚安~", "拜拜", "先这样吧", "我先忙了"):
self.assertEqual(cc.classify(text), "farewell", text)
def test_real_content_is_never_a_closing(self):
for text in ("好,那我明天去", "你是男的女的啊", "帮我查询物流到哪里了", "13", "医生", "好的 我血糖13", "",
"1", "?", "?", "。", "[图片]", "[语音] 00:05", "[发呆]", "[疑问]", "[流泪]"):
self.assertEqual(cc.classify(text), "", text)
def test_emoji_and_wecom_bracket_emoji(self):
for text in ("👌", "👍", "😊", "🙂", "👌👌👌", "好👌", "[OK]", "[强]", "[强][强]", "[微笑]", "[呲牙]", "[玫瑰]",
"哈哈", "哈哈哈", "😂", "666", "嗯嗯嗯", "ok", "OK的"):
self.assertEqual(cc.classify(text), "ack", text)
for text in ("🙏", "🙏🙏", "[抱拳]", "[合十]", "谢谢🙏", "辛苦啦", "好的谢谢🙏"):
self.assertEqual(cc.classify(text), "thanks", text)
self.assertEqual(cc.classify("我先忙了👋"), "farewell")
def test_sticker_placeholders_are_reactions(self):
for text in ("[表情]", "[动画表情]", "[表情][表情]", "【表情】"):
self.assertEqual(cc.classify(text), "ack", text)
self.assertTrue(cc.is_sticker_row({"content": "[表情]", "content_type": 5}))
self.assertTrue(cc.is_sticker_row({"content": "[表情]", "content_type": 0}))
self.assertFalse(cc.is_sticker_row({"content": "[图片]", "content_type": 3}))
self.assertTrue(cc.is_reaction_batch([{"content": "[表情]", "content_type": 5}, {"content": "👌", "content_type": 0}]))
self.assertFalse(cc.is_reaction_batch([{"content": "[图片]", "content_type": 3}]))
self.assertFalse(cc.is_reaction_batch([]))
class DecideTest(unittest.TestCase):
def test_bare_ack_after_advice_is_skipped(self):
decision = cc.decide("好", ADVICE)
self.assertTrue(decision.skip)
self.assertEqual(decision.kind, "ack")
def test_first_thanks_gets_one_brief_reply_with_hint(self):
decision = cc.decide("谢谢", ADVICE)
self.assertFalse(decision.skip)
self.assertIn("简短", decision.hint)
def test_second_closing_round_is_skipped(self):
history = ADVICE + [
{"role": "user", "content": "谢谢"},
{"role": "assistant", "content": "不客气,有事随时找我"},
]
for text in ("好的", "谢谢", "嗯嗯", "晚安"):
self.assertTrue(cc.decide(text, history).skip, text)
def test_ack_that_answers_a_question_is_replied(self):
history = [
{"role": "user", "content": "想挂号"},
{"role": "assistant", "content": "周三上午可以吗?"},
]
self.assertFalse(cc.decide("好", history).skip)
history[-1]["content"] = "那我帮您约周三上午,您看方便不"
self.assertFalse(cc.decide("好", history).skip)
def test_without_history_we_still_reply(self):
self.assertFalse(cc.decide("好", []).skip)
self.assertFalse(cc.decide("好", None).skip)
def test_content_after_closing_round_is_replied(self):
history = ADVICE + [
{"role": "user", "content": "谢谢"},
{"role": "assistant", "content": "不客气"},
]
self.assertFalse(cc.decide("好的,另外我想问下药还有吗", history).skip)
def test_reaction_rounds_after_thanks_are_skipped(self):
history = ADVICE + [
{"role": "user", "content": "谢谢"},
{"role": "assistant", "content": "不客气,有事随时找我"},
]
for text in ("👌", "🙏", "[强]", "[表情]", "哈哈", "ok"):
self.assertTrue(cc.decide(text, history).skip, text)
# A first-time emoji thanks still deserves one short reply.
first = cc.decide("🙏", ADVICE)
self.assertFalse(first.skip)
self.assertTrue(first.hint)
def test_sticker_rows_in_protocol_batch(self):
rows = [
{"is_self": False, "content": "血糖高", "content_type": 0},
{"is_self": True, "content": "多测血糖哦", "content_type": 0},
{"is_self": False, "content": "[表情]", "content_type": 5},
]
self.assertTrue(cc.decide_for_messages(rows, rows[-1:]).skip)
asked = [dict(rows[0]), {"is_self": True, "content": "周三上午方便吗?", "content_type": 0}, dict(rows[2])]
self.assertFalse(cc.decide_for_messages(asked, asked[-1:]).skip)
def test_database_rows_are_accepted(self):
rows = [
{"is_self": False, "content": "血糖高"},
{"is_self": True, "content": "多测血糖哦"},
{"is_self": False, "content": "好"},
]
self.assertTrue(cc.decide_for_messages(rows, rows[-1:]).skip)
rows.append({"is_self": False, "content": "还有个问题"})
self.assertFalse(cc.decide_for_messages(rows, rows[-2:]).skip)
class ProtocolEngineTest(unittest.TestCase):
def _bot(self):
import protocol_engine
bot = protocol_engine.ProtocolBot.__new__(protocol_engine.ProtocolBot)
bot.account = "1688856770803435"
bot._lock = threading.RLock()
bot._pending = {}
bot.reply_text = ""
return bot
def test_generate_forwards_closing_hint(self):
bot = self._bot()
context = {"account": bot.account, "conv_id": "S:conv-1", "display_name": "客户",
"messages": [{"is_self": False, "content": "谢谢", "send_time": 1}],
"closing_hint": cc.CLOSING_HINT}
with (
mock.patch("ai_config.AI_ENABLED", True),
mock.patch("ai_config.AI_JUDGE_ENABLED", False),
mock.patch("ai_chat.gateway_provider", return_value=None),
mock.patch("ai_chat.current_provider", return_value=object()),
mock.patch("ai_chat.get_ai_reply", return_value="不客气") as reply,
):
self.assertEqual(bot._generate(context), "不客气")
self.assertEqual(reply.call_args.kwargs["turn_hint"], cc.CLOSING_HINT)
class SystemPromptTest(unittest.TestCase):
def test_turn_hint_is_appended_to_system_prompt(self):
import ai_chat
base = ai_chat._system_prompt("客户 10:00\n谢谢")
with_hint = ai_chat._system_prompt_for_turn("客户 10:00\n谢谢", cc.CLOSING_HINT)
self.assertTrue(with_hint.startswith(base))
self.assertTrue(with_hint.endswith(cc.CLOSING_HINT))
self.assertEqual(ai_chat._system_prompt_for_turn("客户 10:00\n谢谢", ""), base)
class VisualFlowTest(unittest.TestCase):
def test_generate_reply_skips_bare_ack_and_clears_task(self):
from wechat_bot import WeChatBot
bot = WeChatBot.__new__(WeChatBot)
fp = b"12345678"
batch = "客户甲 7/29 10:00:01\n好的"
bot.get_session_history = mock.Mock(return_value=list(ADVICE))
bot.extract_context_for = mock.Mock(return_value=batch)
bot._stage_exchange = mock.Mock()
bot._run_ai_page_guard = mock.Mock(return_value=False)
bot._clear_reply_pending = mock.Mock()
bot.store = mock.Mock()
bot.store.has_record = mock.Mock(return_value=True)
with (
mock.patch("ai_config.AI_ENABLED", True),
mock.patch("ai_config.AI_USE_VISION", False),
mock.patch("ai_config.AI_CONTEXT_ENABLED", True),
mock.patch("ai_chat.call_ai_text", return_value="不应被调用") as call_ai,
mock.patch("wechat_bot.time.sleep"),
):
result = bot._generate_ai_reply(fp)
self.assertIsNone(result)
call_ai.assert_not_called()
bot._clear_reply_pending.assert_called_once_with(fp)
def test_generate_reply_skips_sticker_only_turn_after_closing(self):
from wechat_bot import WeChatBot
bot = WeChatBot.__new__(WeChatBot)
fp = b"12345678"
batch = "客户甲 7/29 10:00:01\n[表情]"
bot.get_session_history = mock.Mock(return_value=list(ADVICE))
bot.extract_context_for = mock.Mock(return_value=batch)
bot._stage_exchange = mock.Mock()
bot._run_ai_page_guard = mock.Mock(return_value=False)
bot._clear_reply_pending = mock.Mock()
bot.store = mock.Mock()
bot.store.has_record = mock.Mock(return_value=True)
with (
mock.patch("ai_config.AI_ENABLED", True),
mock.patch("ai_config.AI_USE_VISION", False),
mock.patch("ai_config.AI_CONTEXT_ENABLED", True),
mock.patch("ai_chat.call_ai_text", return_value="不应被调用") as call_ai,
mock.patch("wechat_bot.time.sleep"),
):
result = bot._generate_ai_reply(fp)
self.assertIsNone(result)
call_ai.assert_not_called()
bot._clear_reply_pending.assert_called_once_with(fp)
def test_generate_reply_passes_closing_hint_for_first_thanks(self):
from wechat_bot import WeChatBot
bot = WeChatBot.__new__(WeChatBot)
fp = b"12345678"
batch = "客户甲 7/29 10:00:01\n谢谢"
bot.get_session_history = mock.Mock(return_value=list(ADVICE))
bot.extract_context_for = mock.Mock(return_value=batch)
bot._stage_exchange = mock.Mock()
bot._run_ai_page_guard = mock.Mock(return_value=False)
bot.store = mock.Mock()
bot.store.has_record = mock.Mock(return_value=True)
with (
mock.patch("ai_config.AI_ENABLED", True),
mock.patch("ai_config.AI_USE_VISION", False),
mock.patch("ai_config.AI_CONTEXT_ENABLED", True),
mock.patch("ai_chat.call_ai_text", return_value="不客气") as call_ai,
mock.patch("registration_store.process_registration_reply", return_value=("不客气", None)),
mock.patch("wechat_bot.time.sleep"),
):
self.assertEqual(bot._generate_ai_reply(fp), "不客气")
self.assertEqual(call_ai.call_args.kwargs["turn_hint"], cc.CLOSING_HINT)
if __name__ == "__main__":
unittest.main()