test_intent.py 6.55 KB
"""查询理解:意图归一、降级、子问题拆分、taxonomy 驱动的维度抽取。

取代了 test_retrieval_intent_normalization.py——那套断言的是旧 prompt 里
写死的 brand/business_category/sub_business 约束段,现在这段由 taxonomy 生成。
"""
import unittest

from src.rag.retrieval import intent as intent_mod
from src.rag.retrieval.intent import IntentResult, classify_intent


class _StubChat:
    """替换 chat_once:可返回固定内容或抛异常。"""

    def __init__(self, result=None, error=None):
        self.result = result
        self.error = error
        self.prompt = None

    async def __call__(self, _model, prompt, **_kwargs):
        self.prompt = prompt
        if self.error:
            raise self.error
        return self.result


class IntentPromptTest(unittest.IsolatedAsyncioTestCase):
    async def test_prompt_declares_sub_query_and_label_rules(self):
        stub = _StubChat('{"intent":"products"}')
        intent_mod.chat_once = stub

        await classify_intent("太阳膜多少钱")

        prompt = stub.prompt
        self.assertIn("sub_queries", prompt)
        self.assertIn("单一问题返回 [] 是正确答案", prompt)
        self.assertIn("troubleshooting > policies > scripts", prompt)
        self.assertIn("太阳膜多少钱", prompt)

    async def test_label_spec_is_generated_from_taxonomy(self):
        """维度约束段由 taxonomy 生成——加一个 boost 维度,prompt 自动多问一个字段。"""
        from src.rag.ingestion.taxonomy import load_taxonomy

        stub = _StubChat('{"intent":"products"}')
        intent_mod.chat_once = stub
        await classify_intent("问界延保")

        for dim in load_taxonomy().boostable():
            self.assertIn(dim.name, stub.prompt)


class SubQueryTest(unittest.IsolatedAsyncioTestCase):
    async def test_multi_part_question_keeps_sub_queries(self):
        intent_mod.chat_once = _StubChat(
            '{"intent":"scripts","standalone_query":"太阳膜价格和免责怎么跟客户说",'
            '"sub_queries":["太阳膜价格政策","太阳膜免责条款"]}'
        )

        result = await classify_intent("价格和免责怎么跟客户说")

        self.assertEqual(result.sub_queries, ["太阳膜价格政策", "太阳膜免责条款"])

    async def test_simple_question_returns_no_sub_queries(self):
        intent_mod.chat_once = _StubChat('{"intent":"products","sub_queries":[]}')

        result = await classify_intent("太阳膜多少钱")

        self.assertEqual(result.sub_queries, [])

    async def test_sub_queries_dedupe_against_original_and_standalone(self):
        """模型把原问题复述一遍当子问题时要丢掉——那只会白跑一路检索。"""
        intent_mod.chat_once = _StubChat(
            '{"intent":"products","standalone_query":"太阳膜多少钱",'
            '"sub_queries":["太阳膜多少钱","太阳膜保修期"]}'
        )

        result = await classify_intent("太阳膜多少钱")

        self.assertEqual(result.sub_queries, ["太阳膜保修期"])

    async def test_sub_queries_capped(self):
        from src.rag.core.config import RAG_MAX_SUB_QUERIES

        many = ",".join(f'"q{i}"' for i in range(10))
        intent_mod.chat_once = _StubChat(
            '{"intent":"products","sub_queries":[' + many + "]}"
        )

        result = await classify_intent("复杂问题")

        self.assertEqual(len(result.sub_queries), RAG_MAX_SUB_QUERIES)


class QueryLabelTest(unittest.IsolatedAsyncioTestCase):
    async def test_labels_accept_only_controlled_values(self):
        intent_mod.chat_once = _StubChat(
            '{"intent":"products","labels":{"brand":"问界","business_category":"权益类"}}'
        )

        result = await classify_intent("问界延保")

        self.assertEqual(result.query_labels["brand"], "问界")
        self.assertEqual(result.query_labels["business_category"], "权益类")

    async def test_hallucinated_label_value_is_dropped(self):
        intent_mod.chat_once = _StubChat('{"intent":"products","labels":{"brand":"不存在的牌子"}}')

        result = await classify_intent("某问题")

        self.assertNotIn("brand", result.query_labels)

    async def test_non_boostable_dimension_is_ignored(self):
        intent_mod.chat_once = _StubChat('{"intent":"products","labels":{"brand_series":"鸿蒙智行"}}')

        result = await classify_intent("某问题")

        self.assertEqual(result.query_labels, {})


class DegradeTest(unittest.IsolatedAsyncioTestCase):
    """查询理解失败绝不能变成 chitchat——那会把真实问题吞成罐头问候语且零检索。"""

    async def test_garbage_response_degrades_to_retrievable_intent(self):
        intent_mod.chat_once = _StubChat("sorry, I cannot help with that")

        result = await classify_intent("问界整车延保多少钱")

        self.assertNotIn(result.intent, {"chitchat", "unsupported"})
        self.assertTrue(result.degraded)
        self.assertEqual(result.standalone_query, "问界整车延保多少钱")

    async def test_chat_exception_degrades_instead_of_raising(self):
        intent_mod.chat_once = _StubChat(error=RuntimeError("connection reset"))

        result = await classify_intent("太阳膜价格")

        self.assertNotIn(result.intent, {"chitchat", "unsupported"})
        self.assertTrue(result.degraded)
        self.assertEqual(result.confidence, 0.0)

    async def test_missing_intent_key_degrades(self):
        intent_mod.chat_once = _StubChat('{"confidence": 0.9}')

        result = await classify_intent("某个真实问题")

        self.assertTrue(result.degraded)

    async def test_normal_response_is_not_marked_degraded(self):
        intent_mod.chat_once = _StubChat('{"intent":"products","intents":["products"]}')

        result = await classify_intent("太阳膜价格")

        self.assertEqual(result.intent, "products")
        self.assertFalse(result.degraded)


class IntentNormalizationTest(unittest.IsolatedAsyncioTestCase):
    async def test_singular_alias_maps_to_canonical_plural(self):
        intent_mod.chat_once = _StubChat('{"intent":"product","intents":["product","script"]}')

        result = await classify_intent("某问题")

        self.assertEqual(result.intent, "products")
        self.assertEqual(result.intents, ["products", "scripts"])

    async def test_compliance_folds_into_policies(self):
        intent_mod.chat_once = _StubChat('{"intent":"compliance"}')

        result = await classify_intent("这个能不能说")

        self.assertEqual(result.intent, "policies")


if __name__ == "__main__":
    unittest.main()