test_search_intent.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import copy
  2. import pytest
  3. from content_agent.business_modules import search_intent
  4. from content_agent.errors import ContentAgentError
  5. from content_agent.integrations.query_prompt_config import DEFAULT_PROFILE
  6. from content_agent.run_service import RunService
  7. from content_agent.schemas import RunStartRequest
  8. from tests.p1_helpers import FakeQueryVariantClient, REAL_SOURCE_FIXTURE
  9. FORBIDDEN_FIXED_BUSINESS_TERMS = [
  10. "\u8d2a\u8150",
  11. "\u57fa\u5c42\u516c\u804c\u4eba\u5458",
  12. "\u6848\u4f8b",
  13. "\u89e3\u8bfb",
  14. "\u8b66\u793a",
  15. ]
  16. class _Runtime:
  17. def __init__(self):
  18. self.rows = {}
  19. def append_jsonl(self, _run_id, filename, rows):
  20. self.rows[filename] = rows
  21. def _seed_pack():
  22. return {
  23. "seed_terms": ["中医养生"],
  24. "query_seed_points": [
  25. {
  26. "point_text": "分享气血食疗",
  27. "point_type": "目的点",
  28. "rank": 1,
  29. "post_id": "p1",
  30. "id": "qp1",
  31. "coverage_post_count": 5,
  32. "category_id": "c1",
  33. },
  34. {
  35. "point_text": "办公室八段锦",
  36. "point_type": "灵感点",
  37. "rank": 2,
  38. "post_id": "p2",
  39. "id": "qp2",
  40. "coverage_post_count": 3,
  41. "category_id": "c1",
  42. },
  43. ],
  44. "itemset_items": ["补气血"],
  45. "category_bindings": [{"category_id": "c1"}],
  46. "element_bindings": [
  47. {
  48. "element_id": "e1",
  49. "category_id": "c1",
  50. "sample_elements": [
  51. {
  52. "id": "point_1",
  53. "name": "食疗补气血",
  54. "point_type": "目的点",
  55. "point_text": "分享气血食疗方法",
  56. "post_id": "p1",
  57. },
  58. {
  59. "id": "point_2",
  60. "name": "八段锦",
  61. "point_type": "灵感点",
  62. "point_text": "办公室八段锦",
  63. "post_id": "p2",
  64. },
  65. {
  66. "id": "point_3",
  67. "name": "日常保健",
  68. "point_type": "关键点",
  69. "point_text": "不应该进入搜索词",
  70. "post_id": "p3",
  71. },
  72. ],
  73. }
  74. ],
  75. "pattern_source_system": "pg_pattern_v2",
  76. "pattern_execution_id": 1987,
  77. "mining_config_id": 58,
  78. "source_post_id": "60219550",
  79. "matched_post_ids": ["60219550"],
  80. "itemset_ids": [1607977],
  81. "support": 0.2,
  82. "absolute_support": 31,
  83. "confidence": 0.8,
  84. }
  85. def test_search_seed_and_queries_do_not_inject_fixed_business_terms(tmp_path):
  86. service = RunService(
  87. runtime_root=tmp_path / "runtime" / "v1",
  88. query_variant_client=FakeQueryVariantClient(
  89. {
  90. "爱国情感": "家国叙事素材",
  91. "人物故事": "榜样人物素材",
  92. }
  93. ),
  94. )
  95. state = service.start_run(
  96. RunStartRequest(platform_mode="mock", source=str(REAL_SOURCE_FIXTURE), strategy_version="V1")
  97. )
  98. run_id = state["run_id"]
  99. pattern_seed_pack = service.read_json(run_id, "pattern_seed_pack.json")
  100. queries = service.read_jsonl(run_id, "search_queries.jsonl")
  101. p2_queries = [
  102. row
  103. for row in queries
  104. if row["search_query_generation_method"] in {"item_single", "llm_variant"}
  105. ]
  106. assert pattern_seed_pack["seed_terms"] == ["爱国情感", "人物故事"]
  107. assert [row["search_query_id"] for row in p2_queries] == ["q_001", "q_002", "q_003", "q_004"]
  108. assert [row["search_query"] for row in p2_queries] == [
  109. "爱国情感",
  110. "家国叙事素材",
  111. "人物故事",
  112. "榜样人物素材",
  113. ]
  114. assert [row["search_query_generation_method"] for row in p2_queries] == [
  115. "item_single",
  116. "llm_variant",
  117. "item_single",
  118. "llm_variant",
  119. ]
  120. assert p2_queries[1]["llm_variant_of"] == "q_001"
  121. assert p2_queries[3]["llm_variant_of"] == "q_003"
  122. for value in [
  123. *pattern_seed_pack["seed_terms"],
  124. *(row["search_query"] for row in p2_queries),
  125. ]:
  126. assert not any(term in value for term in FORBIDDEN_FIXED_BUSINESS_TERMS)
  127. def test_search_queries_preserve_source_terms_for_replay(tmp_path):
  128. service = RunService(
  129. runtime_root=tmp_path / "runtime" / "v1",
  130. query_variant_client=FakeQueryVariantClient(
  131. {
  132. "爱国情感": "家国叙事素材",
  133. "人物故事": "榜样人物素材",
  134. }
  135. ),
  136. )
  137. state = service.start_run(
  138. RunStartRequest(platform_mode="mock", source=str(REAL_SOURCE_FIXTURE), strategy_version="V1")
  139. )
  140. queries = service.read_jsonl(state["run_id"], "search_queries.jsonl")
  141. p2_queries = [
  142. query
  143. for query in queries
  144. if query["search_query_generation_method"] in {"item_single", "llm_variant"}
  145. ]
  146. expected_source_terms = [["爱国情感"], ["爱国情感"], ["人物故事"], ["人物故事"]]
  147. for query, source_terms in zip(p2_queries, expected_source_terms, strict=True):
  148. assert query["query_source_terms"] == source_terms
  149. assert query["query_source_fields"] == ["seed_terms"]
  150. assert query["raw_payload"]["query_source_terms"] == source_terms
  151. assert query["pattern_seed_ref"]["source_field"] == "seed_terms"
  152. assert query["pattern_seed_ref"]["seed_term"] == source_terms[0]
  153. assert query["raw_payload"]["pattern_seed_ref"]["seed_term"] == source_terms[0]
  154. llm_queries = [
  155. query
  156. for query in p2_queries
  157. if query["search_query_generation_method"] == "llm_variant"
  158. ]
  159. assert len(llm_queries) == 2
  160. for query in llm_queries:
  161. assert query["raw_payload"]["llm_prompt_version"] == "fake-query-prompt-v1"
  162. assert query["raw_payload"]["llm_generation_model"] == "fake-query-model"
  163. assert query["raw_payload"]["llm_input_evidence"]["source_field"] == "seed_terms"
  164. assert query["raw_payload"]["llm_input_evidence"]["itemset_items"]
  165. def test_search_intent_custom_evidence_fields_whitelist():
  166. client = FakeQueryVariantClient({"中医养生": "气血食疗"})
  167. client.profile = copy.deepcopy(DEFAULT_PROFILE)
  168. client.profile["evidence_fields"] = ["seed_term", "support"]
  169. runtime = _Runtime()
  170. queries = search_intent.run("run_1", "policy_1", _seed_pack(), runtime, client)
  171. llm_query = [row for row in queries if row["search_query_generation_method"] == "llm_variant"][0]
  172. assert list(llm_query["llm_input_evidence"].keys()) == ["seed_term", "support"]
  173. assert list(llm_query["raw_payload"]["llm_input_evidence"].keys()) == ["seed_term", "support"]
  174. assert llm_query["query_source_fields"] == ["seed_terms"]
  175. def test_v4_search_intent_uses_three_direct_sources_without_llm_variant():
  176. client = FakeQueryVariantClient({"中医养生": "气血食疗"})
  177. runtime = _Runtime()
  178. queries = search_intent.run(
  179. "run_1",
  180. "policy_1",
  181. _seed_pack(),
  182. runtime,
  183. client,
  184. strategy_version="V4",
  185. )
  186. assert client.calls == []
  187. # 三路首轮搜索池:seed_terms、query_seed_points、分类叶子元素;不再调 LLM 变体。
  188. assert [row["search_query"] for row in queries] == [
  189. "中医养生",
  190. "气血食疗",
  191. "办公室八段锦",
  192. "食疗补气血",
  193. "八段锦",
  194. "日常保健",
  195. ]
  196. assert [row["search_query_generation_method"] for row in queries] == [
  197. "seed_term",
  198. "query_seed_point",
  199. "query_seed_point",
  200. "category_leaf_element",
  201. "category_leaf_element",
  202. "category_leaf_element",
  203. ]
  204. assert all("llm_variant_of" not in row for row in queries)
  205. assert runtime.rows["search_queries.jsonl"] == queries
  206. first = next(row for row in queries if row["search_query"] == "气血食疗")
  207. assert first["pattern_seed_ref"]["query_source_type"] == "query_seed_point"
  208. assert first["pattern_seed_ref"]["query_source_text"] == "气血食疗"
  209. assert first["pattern_seed_ref"]["query_source_rank"] == 1
  210. source_ref = first["query_source_refs"][0]["source_ref"]
  211. assert source_ref["point_type"] == "目的点"
  212. assert source_ref["point_text"] == "分享气血食疗" # 原文不被覆盖
  213. assert source_ref["cleaned_text"] == "气血食疗"
  214. assert source_ref["qsp_rank"] == 1
  215. assert first["raw_payload"]["query_source_refs"][0]["query_source_text"] == "气血食疗"
  216. def test_v4_falls_back_to_seed_terms_when_query_seed_points_empty():
  217. runtime = _Runtime()
  218. seed_pack = _seed_pack()
  219. seed_pack["query_seed_points"] = []
  220. seed_pack["element_bindings"] = []
  221. queries = search_intent.run(
  222. "run_1",
  223. "policy_1",
  224. seed_pack,
  225. runtime,
  226. FakeQueryVariantClient(),
  227. strategy_version="V4",
  228. )
  229. assert [row["search_query"] for row in queries] == ["中医养生"]
  230. assert all(row["search_query_generation_method"] == "seed_term" for row in queries)
  231. def test_v4_search_intent_dedupes_query_seed_points():
  232. runtime = _Runtime()
  233. seed_pack = _seed_pack()
  234. seed_pack["query_seed_points"] = [
  235. {"point_text": "气血食疗", "point_type": "灵感点", "rank": 1, "post_id": "p1", "id": "x1"},
  236. {"point_text": "气血食疗", "point_type": "灵感点", "rank": 2, "post_id": "p2", "id": "x2"},
  237. ]
  238. queries = search_intent.run(
  239. "run_1",
  240. "policy_1",
  241. seed_pack,
  242. runtime,
  243. FakeQueryVariantClient(),
  244. strategy_version="V4",
  245. )
  246. matching = [row for row in queries if row["search_query"] == "气血食疗"]
  247. assert len(matching) == 1
  248. assert matching[0]["search_query_generation_method"] == "query_seed_point"
  249. def test_search_intent_custom_generic_filter_blocks_query():
  250. client = FakeQueryVariantClient({"中医养生": "禁用泛词"})
  251. client.profile = copy.deepcopy(DEFAULT_PROFILE)
  252. client.profile["generic_filter"] = {"queries": ["禁用泛词"], "tokens": []}
  253. with pytest.raises(ContentAgentError) as exc:
  254. search_intent.run("run_1", "policy_1", _seed_pack(), _Runtime(), client)
  255. assert exc.value.error_code == "QUERY_GENERATION_FAILED"
  256. assert exc.value.detail["reason"] == "llm_variant_generic"
  257. def test_search_intent_rejects_unsupported_variants_per_seed():
  258. client = FakeQueryVariantClient({"中医养生": "气血食疗"})
  259. client.profile = copy.deepcopy(DEFAULT_PROFILE)
  260. client.profile["variants_per_seed"] = 2
  261. with pytest.raises(ContentAgentError) as exc:
  262. search_intent.run("run_1", "policy_1", _seed_pack(), _Runtime(), client)
  263. assert exc.value.error_code == "QUERY_GENERATION_FAILED"
  264. assert exc.value.detail == {"reason": "variants_per_seed_unsupported", "variants_per_seed": 2}