find_tree_node.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. """
  2. 查找树节点 Tool - 人设树节点查询
  3. 功能:
  4. 1. 获取人设树的常量节点(全局常量、局部常量)
  5. 2. 获取符合条件概率阈值的节点(按条件概率排序返回 topN)
  6. 平台库人设树(第二节输出)流水线(由 build_platform_tree_section_items 聚合):
  7. xiaohongshu/tree → 与账号相同的条件概率计算 → xiaohongshu/match_data 按匹配分过滤选题点
  8. → 剔除与账号段同名的节点。
  9. """
  10. import json
  11. import sys
  12. from pathlib import Path
  13. from typing import Any, Optional
  14. # 保证直接运行或作为包加载时都能解析 utils / tools(IDE 可跳转)
  15. _root = Path(__file__).resolve().parent.parent
  16. if str(_root) not in sys.path:
  17. sys.path.insert(0, str(_root))
  18. from utils.conditional_ratio_calc import ( # noqa: E402
  19. build_node_post_index,
  20. build_node_post_index_from_tree_dir,
  21. calc_node_conditional_ratio,
  22. load_persona_trees_from_dir,
  23. )
  24. from tools.point_match import ( # noqa: E402
  25. DEFAULT_MATCH_THRESHOLD,
  26. match_derivation_to_post_points,
  27. )
  28. try:
  29. from agent.tools import tool, ToolResult, ToolContext
  30. except ImportError:
  31. def tool(*args, **kwargs):
  32. return lambda f: f
  33. ToolResult = None # 仅用 main() 测核心逻辑时可无 agent
  34. ToolContext = None
  35. # 相对本文件:tools -> overall_derivation,input / output 在 overall_derivation 下
  36. _BASE_INPUT = Path(__file__).resolve().parent.parent / "input"
  37. _BASE_OUTPUT = Path(__file__).resolve().parent.parent / "output"
  38. def _dimension_analysis_log_dir(account_name: str, post_id: str, log_id: str) -> Path:
  39. """推导日志目录:output/{account_name}/推导日志/{post_id}/{log_id}/"""
  40. return _BASE_OUTPUT / account_name / "推导日志" / post_id / log_id
  41. def _load_derived_dim_tree_node_names(
  42. account_name: str, post_id: str, log_id: str, round: int
  43. ) -> list[str]:
  44. """
  45. 读取当前轮次对应的维度分析 JSON(优先 {round}_维度分析.json,不存在则 {round-1}_维度分析.json),
  46. 返回 derived_dims 中每项的 tree_node_name(已推导出的维度节点,人设树中层次较高)。
  47. 无可用文件时返回空列表。
  48. """
  49. if not log_id or not str(log_id).strip():
  50. return []
  51. log_dir = _dimension_analysis_log_dir(account_name, post_id, str(log_id).strip())
  52. for r in (round, round - 1):
  53. if r < 1:
  54. continue
  55. path = log_dir / f"{r}_维度分析.json"
  56. if not path.is_file():
  57. continue
  58. try:
  59. with open(path, "r", encoding="utf-8") as f:
  60. data = json.load(f)
  61. except Exception:
  62. continue
  63. dims = data.get("derived_dims") or []
  64. names: list[str] = []
  65. for d in dims:
  66. if isinstance(d, dict):
  67. tn = d.get("tree_node_name")
  68. if tn is not None and str(tn).strip():
  69. names.append(str(tn).strip())
  70. return names
  71. return []
  72. def _descendant_names_under_tree_nodes(
  73. account_name: str, anchor_node_names: list[str]
  74. ) -> tuple[set[str], dict[str, str]]:
  75. """
  76. 在每个人设维度树根上 DFS,收集所有锚点(derived_dims.tree_node_name)之下的**全部后代**(不含锚点自身)。
  77. 同时记录「所属维度」:对路径上每个后代节点,取从维度根到该节点路径上**最深的**那个锚点
  78. (与原先沿父链向上找最近 derived_dim 一致;多个锚点呈祖孙时取更深者)。
  79. """
  80. if not anchor_node_names:
  81. return set(), {}
  82. S = set(anchor_node_names)
  83. allowed: set[str] = set()
  84. dim_map: dict[str, str] = {}
  85. for dim_root_name, root in _load_trees(account_name):
  86. def dfs(node_name: str, node_dict: dict, parent_deepest_s: Optional[str]) -> None:
  87. d_self = node_name if node_name in S else parent_deepest_s
  88. for cname, cnode in (node_dict.get("children") or {}).items():
  89. if not isinstance(cnode, dict):
  90. continue
  91. if cname not in S and d_self is not None:
  92. allowed.add(cname)
  93. dim_map[cname] = d_self
  94. dfs(cname, cnode, d_self)
  95. dfs(dim_root_name, root, None)
  96. return allowed, dim_map
  97. def _tree_dir(account_name: str) -> Path:
  98. """人设树目录:../input/{account_name}/处理后数据/tree/"""
  99. return _BASE_INPUT / account_name / "处理后数据" / "tree"
  100. def _load_trees(account_name: str) -> list[tuple[str, dict]]:
  101. """加载该账号下所有维度的人设树。返回 [(维度名, 根节点 dict), ...]。"""
  102. td = _tree_dir(account_name)
  103. if not td.is_dir():
  104. return []
  105. result = []
  106. for p in td.glob("*.json"):
  107. try:
  108. with open(p, "r", encoding="utf-8") as f:
  109. data = json.load(f)
  110. for dim_name, root in data.items():
  111. if isinstance(root, dict):
  112. result.append((dim_name, root))
  113. break
  114. except Exception:
  115. continue
  116. return result
  117. def _iter_all_nodes(account_name: str):
  118. """遍历该账号下所有人设树节点,产出 (节点名称, 父节点名称, 节点 dict)。"""
  119. for dim_name, root in _load_trees(account_name):
  120. def walk(parent_name: str, node_dict: dict):
  121. for name, child in (node_dict.get("children") or {}).items():
  122. if not isinstance(child, dict):
  123. continue
  124. yield (name, parent_name, child)
  125. yield from walk(name, child)
  126. yield from walk(dim_name, root)
  127. # ---------------------------------------------------------------------------
  128. # 1. 获取人设树常量节点
  129. # ---------------------------------------------------------------------------
  130. def get_constant_nodes(account_name: str) -> list[dict[str, Any]]:
  131. """
  132. 获取人设树的常量节点。
  133. - 全局常量:_is_constant=True
  134. - 局部常量:_is_local_constant=True 且 _is_constant=False
  135. 返回列表项:节点名称、概率(_ratio)、常量类型。
  136. """
  137. result = []
  138. for node_name, _parent, node in _iter_all_nodes(account_name):
  139. is_const = node.get("_is_constant") is True
  140. is_local = node.get("_is_local_constant") is True
  141. if is_const:
  142. const_type = "全局常量"
  143. elif is_local and not is_const:
  144. const_type = "局部常量"
  145. else:
  146. continue
  147. ratio = node.get("_ratio")
  148. result.append({
  149. "节点名称": node_name,
  150. "概率": ratio,
  151. "常量类型": const_type,
  152. })
  153. result.sort(key=lambda x: (x["概率"] is None, -(x["概率"] or 0)))
  154. return result
  155. # ---------------------------------------------------------------------------
  156. # 2. 获取符合条件概率阈值的节点
  157. # ---------------------------------------------------------------------------
  158. def get_nodes_by_conditional_ratio(
  159. account_name: str,
  160. derived_list: list[tuple[str, str]],
  161. threshold: float,
  162. top_n: int,
  163. allowed_node_names: Optional[set[str]] = None,
  164. node_belonging_dim: Optional[dict[str, str]] = None,
  165. ) -> list[dict[str, Any]]:
  166. """
  167. 获取人设树中条件概率 >= threshold 的节点,按条件概率降序,返回前 top_n 个。
  168. derived_list: 已推导列表,每项 (已推导的选题点, 推导来源人设树节点);为空时使用节点自身的 _ratio 作为条件概率。
  169. allowed_node_names: 若给定,仅保留节点名称在该集合内的结果。
  170. node_belonging_dim: 与 allowed 同步生成(见 _descendant_names_under_tree_nodes),节点名 -> 所属已推导维度;不传则所属维度均为「—」。
  171. 返回列表项:节点名称、条件概率、父节点名称、所属维度。
  172. """
  173. base_dir = _BASE_INPUT
  174. node_to_parent: dict[str, str] = {}
  175. if derived_list:
  176. for n, p, _ in _iter_all_nodes(account_name):
  177. node_to_parent[n] = p
  178. def dim_for(node_name: str) -> str:
  179. if not node_belonging_dim:
  180. return "—"
  181. return node_belonging_dim.get(node_name) or "—"
  182. scored: list[tuple[str, float, str, str]] = []
  183. if not derived_list:
  184. for node_name, parent_name, node in _iter_all_nodes(account_name):
  185. if allowed_node_names is not None and node_name not in allowed_node_names:
  186. continue
  187. ratio = node.get("_ratio")
  188. if ratio is None:
  189. ratio = 0.0
  190. else:
  191. ratio = float(ratio)
  192. if ratio >= threshold:
  193. scored.append((node_name, ratio, parent_name, dim_for(node_name)))
  194. else:
  195. node_post_index = build_node_post_index(account_name, base_dir)
  196. for node_name, parent_name in node_to_parent.items():
  197. if allowed_node_names is not None and node_name not in allowed_node_names:
  198. continue
  199. ratio = calc_node_conditional_ratio(
  200. account_name,
  201. derived_list,
  202. node_name,
  203. base_dir=base_dir,
  204. node_post_index=node_post_index,
  205. target_ratio=threshold,
  206. )
  207. if ratio >= threshold:
  208. scored.append((node_name, ratio, parent_name, dim_for(node_name)))
  209. scored.sort(key=lambda x: x[1], reverse=True)
  210. top = scored[:top_n]
  211. return [
  212. {
  213. "节点名称": name,
  214. "条件概率": ratio,
  215. "父节点名称": parent,
  216. "所属维度": dim,
  217. }
  218. for name, ratio, parent, dim in top
  219. ]
  220. def _platform_tree_dir() -> Path:
  221. """平台库人设树目录:../input/xiaohongshu/tree/"""
  222. return _BASE_INPUT / "xiaohongshu" / "tree"
  223. def _collect_platform_scored_tuples(
  224. derived_list: list[tuple[str, str]],
  225. threshold: float,
  226. max_nodes: int = 12000,
  227. ) -> list[tuple[str, float, str, str]]:
  228. """
  229. 平台库人设树:条件概率 >= threshold 的节点全量收集,按条件概率降序。
  230. max_nodes 防止极端大树占满内存;截断发生在全局排序之后(保留高分段)。
  231. """
  232. tree_dir = _platform_tree_dir()
  233. if not tree_dir.is_dir():
  234. return []
  235. thr = float(threshold)
  236. scored: list[tuple[str, float, str, str]] = []
  237. if not derived_list:
  238. for dim_name, root in load_persona_trees_from_dir(tree_dir):
  239. def walk(parent_name: str, node_dict: dict) -> None:
  240. for name, child in (node_dict.get("children") or {}).items():
  241. if not isinstance(child, dict):
  242. continue
  243. ratio = child.get("_ratio")
  244. r = 0.0 if ratio is None else float(ratio)
  245. if r >= thr:
  246. scored.append((name, r, parent_name, dim_name))
  247. walk(name, child)
  248. walk(dim_name, root)
  249. else:
  250. node_post_index = build_node_post_index_from_tree_dir(tree_dir)
  251. node_to_parent_dim: dict[str, tuple[str, str]] = {}
  252. for dim_name, root in load_persona_trees_from_dir(tree_dir):
  253. def walk2(parent_name: str, node_dict: dict) -> None:
  254. for name, child in (node_dict.get("children") or {}).items():
  255. if not isinstance(child, dict):
  256. continue
  257. node_to_parent_dim[name] = (parent_name, dim_name)
  258. walk2(name, child)
  259. walk2(dim_name, root)
  260. for node_name, (parent_name, dim_name) in node_to_parent_dim.items():
  261. ratio = calc_node_conditional_ratio(
  262. "",
  263. derived_list,
  264. node_name,
  265. base_dir=_BASE_INPUT,
  266. node_post_index=node_post_index,
  267. target_ratio=thr,
  268. )
  269. if ratio >= thr:
  270. scored.append((node_name, ratio, parent_name, dim_name))
  271. scored.sort(key=lambda x: x[1], reverse=True)
  272. if max_nodes > 0 and len(scored) > max_nodes:
  273. scored = scored[:max_nodes]
  274. return scored
  275. def get_platform_nodes_by_conditional_ratio(
  276. derived_list: list[tuple[str, str]],
  277. threshold: float,
  278. top_n: int,
  279. ) -> list[dict[str, Any]]:
  280. """
  281. 平台库人设树节点条件概率筛选,计算方式与 get_nodes_by_conditional_ratio 一致
  282. (同一套 calc_node_conditional_ratio / _post_ids 规则,索引来自 xiaohongshu/tree)。
  283. derived_list 为空时用节点 _ratio。
  284. """
  285. n = max(0, int(top_n))
  286. scored = _collect_platform_scored_tuples(derived_list, threshold)
  287. top = scored[:n]
  288. return [
  289. {
  290. "节点名称": name,
  291. "条件概率": ratio,
  292. "父节点名称": parent,
  293. "所属维度": dim,
  294. }
  295. for name, ratio, parent, dim in top
  296. ]
  297. def _parse_derived_list(derived_items: list[dict[str, str]]) -> list[tuple[str, str]]:
  298. """将 agent 传入的 [{"topic": "x", "source_node": "y"}, ...] 转为 DerivedItem 列表。"""
  299. out = []
  300. for item in derived_items:
  301. if isinstance(item, dict):
  302. topic = item.get("topic") or item.get("已推导的选题点")
  303. source = item.get("source_node") or item.get("推导来源人设树节点")
  304. if topic is not None and source is not None:
  305. out.append((str(topic).strip(), str(source).strip()))
  306. elif isinstance(item, (list, tuple)) and len(item) >= 2:
  307. out.append((str(item[0]).strip(), str(item[1]).strip()))
  308. return out
  309. # ---------------------------------------------------------------------------
  310. # 3. 平台库人设树辅助节点(基于帖子与平台库人设树匹配结果)
  311. # ---------------------------------------------------------------------------
  312. def _platform_match_topics_by_node(
  313. post_id: str,
  314. match_score_threshold: float,
  315. ) -> dict[tuple[str, str], dict[str, float]]:
  316. """
  317. 读取 xiaohongshu/match_data/{post_id}_匹配_all.json,
  318. 返回 (dimension, 人设树节点名) -> {帖子选题点: 最高分},仅收录 match_score >= match_score_threshold 的对。
  319. """
  320. out: dict[tuple[str, str], dict[str, float]] = {}
  321. if not post_id:
  322. return out
  323. path = _BASE_INPUT / "xiaohongshu" / "match_data" / f"{post_id}_匹配_all.json"
  324. if not path.is_file():
  325. return out
  326. try:
  327. with open(path, "r", encoding="utf-8") as f:
  328. data = json.load(f)
  329. except Exception:
  330. return out
  331. if not isinstance(data, list):
  332. return out
  333. thr = float(match_score_threshold)
  334. for item in data:
  335. if not isinstance(item, dict):
  336. continue
  337. topic = item.get("name")
  338. matches = item.get("match_personas")
  339. if topic is None or not isinstance(matches, list):
  340. continue
  341. topic_s = str(topic).strip()
  342. if not topic_s:
  343. continue
  344. for m in matches:
  345. if not isinstance(m, dict):
  346. continue
  347. name = m.get("name")
  348. dim = m.get("dimension")
  349. score = m.get("match_score")
  350. if name is None or dim is None or score is None:
  351. continue
  352. try:
  353. s = float(score)
  354. except Exception:
  355. continue
  356. if s < thr:
  357. continue
  358. key = (str(dim).strip(), str(name).strip())
  359. bucket = out.setdefault(key, {})
  360. prev = bucket.get(topic_s)
  361. if prev is None or s > prev:
  362. bucket[topic_s] = s
  363. return out
  364. def _platform_node_belonging_dim_from_anchor_nodes(
  365. anchor_node_names: list[str],
  366. ) -> dict[str, str]:
  367. """
  368. 计算平台库人设树中:节点名 -> 所属最深 derived_dim 锚点节点名。
  369. 逻辑与账号段 _descendant_names_under_tree_nodes 保持一致(但树结构来自 xiaohongshu/tree)。
  370. """
  371. if not anchor_node_names:
  372. return {}
  373. S = set(anchor_node_names)
  374. dim_map: dict[str, str] = {}
  375. tree_dir = _platform_tree_dir()
  376. if not tree_dir.is_dir():
  377. return {}
  378. for dim_root_name, root in load_persona_trees_from_dir(tree_dir):
  379. def dfs(node_name: str, node_dict: dict, parent_deepest_s: Optional[str]) -> None:
  380. d_self = node_name if node_name in S else parent_deepest_s
  381. for cname, cnode in (node_dict.get("children") or {}).items():
  382. if not isinstance(cnode, dict):
  383. continue
  384. if cname not in S and d_self is not None:
  385. dim_map[cname] = d_self
  386. dfs(cname, cnode, d_self)
  387. dfs(dim_root_name, root, None)
  388. return dim_map
  389. def _load_platform_nodes_split(
  390. post_id: str,
  391. derived_list: list[tuple[str, str]],
  392. conditional_ratio_threshold: float,
  393. match_score_threshold: float,
  394. top_n: int,
  395. node_belonging_dim_platform: Optional[dict[str, str]] = None,
  396. ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
  397. """
  398. 平台库人设树:用 _collect_platform_scored_tuples 得到条件概率达标的节点,
  399. 再按 xiaohongshu/match_data 分为「有帖子选题点匹配 / 无匹配」两类,**两类各自按条件概率取 Top 池**(同一全局 TopN 不会挤掉另一类),
  400. 最后分别组装返回:
  401. - matched:有 match_score >= match_score_threshold 的帖子选题点匹配的节点
  402. - unmatched:无达标帖子选题点匹配的节点
  403. 两组均要求节点在 node_belonging_dim_platform 中有有效的所属维度(不为「—」)。
  404. """
  405. matched: list[dict[str, Any]] = []
  406. unmatched: list[dict[str, Any]] = []
  407. topic_map: dict[tuple[str, str], dict[str, float]] = {}
  408. if post_id:
  409. topic_map = _platform_match_topics_by_node(post_id, float(match_score_threshold))
  410. # 维度标签可能与树侧不完全一致:保留一个按节点名聚合的兜底索引,避免误判为“无匹配”。
  411. topic_map_by_name: dict[str, dict[str, float]] = {}
  412. for (_dim, n), topics in topic_map.items():
  413. bucket = topic_map_by_name.setdefault(str(n).strip(), {})
  414. for t, sc in (topics or {}).items():
  415. prev = bucket.get(t)
  416. if prev is None or sc > prev:
  417. bucket[t] = sc
  418. # 有 match_data 命中与无命中两类分开按条件概率取 Top,避免混在一个全局 TopN 里挤掉某一类。
  419. all_scored = _collect_platform_scored_tuples(
  420. derived_list,
  421. float(conditional_ratio_threshold),
  422. )
  423. if not all_scored:
  424. return matched, unmatched
  425. matched_tuples: list[tuple[str, float, str, str]] = []
  426. unmatched_tuples: list[tuple[str, float, str, str]] = []
  427. for name, ratio, parent, dim in all_scored:
  428. lookup_dim = str(dim).strip()
  429. key = (lookup_dim, str(name).strip())
  430. topics = topic_map.get(key) or topic_map_by_name.get(str(name).strip()) or {}
  431. if topics:
  432. matched_tuples.append((name, ratio, parent, dim))
  433. else:
  434. unmatched_tuples.append((name, ratio, parent, dim))
  435. _pool = max(int(top_n), min(2000, max(500, int(top_n) * 5)))
  436. matched_tuples = matched_tuples[:_pool]
  437. unmatched_tuples = unmatched_tuples[:_pool]
  438. def _emit_tuple_rows(
  439. tuples: list[tuple[str, float, str, str]],
  440. *,
  441. has_topics: bool,
  442. ) -> None:
  443. for name, ratio, parent, dim in tuples:
  444. row = {
  445. "节点名称": name,
  446. "条件概率": ratio,
  447. "父节点名称": parent,
  448. "所属维度": dim,
  449. }
  450. name_s = str(row.get("节点名称") or "").strip()
  451. out_dim = "—"
  452. if node_belonging_dim_platform is not None:
  453. out_dim = node_belonging_dim_platform.get(name_s) or "—"
  454. if node_belonging_dim_platform is not None and out_dim == "—":
  455. continue
  456. row_out = dict(row)
  457. row_out["所属维度"] = out_dim
  458. lookup_dim = str(row.get("所属维度") or "").strip()
  459. key2 = (lookup_dim, name_s)
  460. topics = topic_map.get(key2) or topic_map_by_name.get(name_s) or {}
  461. if has_topics:
  462. if not topics:
  463. continue
  464. topic_items = sorted(topics.items(), key=lambda x: x[1], reverse=True)
  465. row_out["帖子选题点匹配"] = [{"帖子选题点": t, "匹配分数": sc} for t, sc in topic_items]
  466. matched.append(row_out)
  467. else:
  468. if topics:
  469. continue
  470. row_out["帖子选题点匹配"] = "无"
  471. unmatched.append(row_out)
  472. _emit_tuple_rows(matched_tuples, has_topics=True)
  473. _emit_tuple_rows(unmatched_tuples, has_topics=False)
  474. return matched, unmatched
  475. def build_platform_tree_section_items_split(
  476. post_id: str,
  477. derived_list: list[tuple[str, str]],
  478. conditional_ratio_threshold: float,
  479. match_score_threshold: float,
  480. top_n: int,
  481. exclude_node_names: set[str],
  482. node_belonging_dim_platform: Optional[dict[str, str]] = None,
  483. ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
  484. """
  485. 平台库人设树节点:条件概率 + xiaohongshu/match_data 匹配,排除与账号段重复的节点名称,
  486. 返回 (有帖子选题点匹配的节点列表, 无帖子选题点匹配的节点列表)。
  487. 供 find_tree_nodes_by_conditional_ratio 聚合输出使用。
  488. """
  489. if not post_id:
  490. return [], []
  491. ex = {str(n).strip() for n in exclude_node_names}
  492. matched, unmatched = _load_platform_nodes_split(
  493. post_id=post_id,
  494. derived_list=derived_list,
  495. conditional_ratio_threshold=float(conditional_ratio_threshold),
  496. match_score_threshold=float(match_score_threshold),
  497. top_n=int(top_n),
  498. node_belonging_dim_platform=node_belonging_dim_platform,
  499. )
  500. matched_filtered = [p for p in matched if str(p.get("节点名称", "")).strip() not in ex]
  501. unmatched_filtered = [p for p in unmatched if str(p.get("节点名称", "")).strip() not in ex]
  502. return matched_filtered, unmatched_filtered
  503. # ---------------------------------------------------------------------------
  504. # Agent Tools(参考 glob_tool 封装)
  505. # ---------------------------------------------------------------------------
  506. @tool()
  507. async def find_tree_constant_nodes(
  508. account_name: str,
  509. post_id: str,
  510. ) -> ToolResult:
  511. """
  512. 获取人设树中的常量节点列表(全局常量与局部常量),并检查每个节点与帖子选题点的匹配情况。
  513. Args:
  514. account_name : 账号名,用于定位该账号的人设树数据。
  515. post_id : 帖子ID,用于加载帖子选题点并与各常量节点做匹配判断。
  516. Returns:
  517. ToolResult:
  518. - title: 结果标题。
  519. - output: 可读的节点列表文本(每行:节点名称、概率、常量类型、帖子匹配情况)。
  520. - 出错时 error 为错误信息。
  521. """
  522. tree_dir = _tree_dir(account_name)
  523. if not tree_dir.is_dir():
  524. return ToolResult(
  525. title="人设树目录不存在",
  526. output=f"目录不存在: {tree_dir}",
  527. error="Directory not found",
  528. )
  529. try:
  530. items = get_constant_nodes(account_name)
  531. # 批量匹配所有节点与帖子选题点
  532. if items and post_id:
  533. node_names = [x["节点名称"] for x in items]
  534. matched_results = await match_derivation_to_post_points(
  535. node_names, account_name, post_id, match_threshold=float(DEFAULT_MATCH_THRESHOLD)
  536. )
  537. node_match_map: dict[str, list] = {}
  538. for m in matched_results:
  539. node_match_map.setdefault(m["推导选题点"], []).append({
  540. "帖子选题点": m["帖子选题点"],
  541. "匹配分数": m["匹配分数"],
  542. })
  543. for item in items:
  544. matches = node_match_map.get(item["节点名称"], [])
  545. item["帖子选题点匹配"] = matches if matches else "无"
  546. if not items:
  547. output = "未找到常量节点"
  548. else:
  549. lines = []
  550. for x in items:
  551. match_info = x.get("帖子选题点匹配", "无")
  552. if isinstance(match_info, list):
  553. match_str = "、".join(f"{m['帖子选题点']}({m['匹配分数']})" for m in match_info)
  554. else:
  555. match_str = str(match_info)
  556. lines.append(f"- {x['节点名称']}\t概率={x['概率']}\t{x['常量类型']}\t帖子选题点匹配={match_str}")
  557. output = "\n".join(lines)
  558. return ToolResult(
  559. title=f"常量节点 ({account_name})",
  560. output=output,
  561. metadata={"account_name": account_name, "count": len(items)},
  562. )
  563. except Exception as e:
  564. return ToolResult(
  565. title="获取常量节点失败",
  566. output=str(e),
  567. error=str(e),
  568. )
  569. @tool()
  570. async def find_tree_nodes_by_conditional_ratio(
  571. account_name: str,
  572. post_id: str,
  573. derived_items: list[dict[str, str]],
  574. conditional_ratio_threshold: float,
  575. top_n: int = 100,
  576. round: int = 1,
  577. log_id: str = "",
  578. match_score_threshold: float = DEFAULT_MATCH_THRESHOLD,
  579. ) -> ToolResult:
  580. """
  581. 按条件概率阈值筛选节点:先账号人设树(优先使用),再平台库人设树;两段不合并。
  582. 条件概率计算对两棵树使用同一套规则(calc_node_conditional_ratio / 节点 _post_ids)。
  583. 返回结果按以下配额分配(合计 top_n 条):
  584. - 账号人设树节点占 60%,其中有帖子选题点匹配的记录和无帖子选题点匹配的记录各占一半;
  585. - 平台库人设树节点占 40%,其中有帖子选题点匹配的记录和无帖子选题点匹配的记录各占一半。
  586. 「帖子选题点匹配」仅收录匹配分 >= match_score_threshold 的选题点。
  587. Args:
  588. account_name : 账号名,用于定位该账号的人设树数据。
  589. post_id : 帖子ID,用于加载帖子选题点并与各节点做匹配判断。
  590. derived_items : 已推导选题点列表,可为空。非空时每项为字典,需含 topic(或「已推导的选题点」)与 source_node(或「推导来源人设树节点」)
  591. conditional_ratio_threshold : 条件概率阈值,仅返回条件概率 >= 该值的节点。
  592. top_n : 最终返回总条数上限,按 账号60%/平台40%、有匹配/无匹配各半 分配。
  593. round : 推导轮次。
  594. log_id : 推导日志ID
  595. match_score_threshold : 帖子选题点匹配分阈值,与 point_match 默认一致。
  596. Returns:
  597. ToolResult:
  598. - title: 结果标题。
  599. - output: 两段文本——先账号人设树,后平台库人设树;
  600. 账号侧匹配来自 input/{账号}/match_data;平台侧条件概率基于 input/xiaohongshu/tree,匹配来自 input/xiaohongshu/match_data。
  601. - 出错时 error 为错误信息。
  602. """
  603. tree_dir = _tree_dir(account_name)
  604. if not tree_dir.is_dir():
  605. return ToolResult(
  606. title="人设树目录不存在",
  607. output=f"目录不存在: {tree_dir}",
  608. error="Directory not found",
  609. )
  610. try:
  611. derived_list = _parse_derived_list(derived_items or [])
  612. allowed: Optional[set[str]] = None
  613. node_belonging_dim: dict[str, str] = {}
  614. node_belonging_dim_platform: Optional[dict[str, str]] = None
  615. dim_source = ""
  616. derived_dim_names: list[str] = []
  617. derived_items_len = len(derived_items or [])
  618. if log_id and str(log_id).strip():
  619. derived_dim_names = _load_derived_dim_tree_node_names(
  620. account_name, post_id, str(log_id).strip(), int(round)
  621. )
  622. if derived_dim_names:
  623. allowed, node_belonging_dim = _descendant_names_under_tree_nodes(
  624. account_name, derived_dim_names
  625. )
  626. node_belonging_dim_platform = _platform_node_belonging_dim_from_anchor_nodes(
  627. derived_dim_names
  628. )
  629. # 记录实际用到的维度分析文件(与读取逻辑一致)
  630. log_dir = _dimension_analysis_log_dir(account_name, post_id, str(log_id).strip())
  631. for r in (int(round), int(round) - 1):
  632. if r >= 1 and (log_dir / f"{r}_维度分析.json").is_file():
  633. dim_source = f"{r}_维度分析.json (derived_dims -> 全部后代)"
  634. break
  635. else:
  636. dim_source = "未读到 derived_dims(无对应维度分析文件或为空),未收窄"
  637. # 当 derived_items 太多时,用 derived_dim_names 作为条件概率计算锚点:
  638. # 将每个 derived_dim_names 的 name 都映射为 (topic=name, source_node=name)。
  639. if derived_items_len > 15 and derived_dim_names:
  640. derived_list = [(n, n) for n in derived_dim_names]
  641. # 1)账号人设树:按条件概率筛选;帖子选题点匹配仅走账号 match_data(match_derivation_to_post_points)
  642. items = get_nodes_by_conditional_ratio(
  643. account_name,
  644. derived_list,
  645. conditional_ratio_threshold,
  646. top_n,
  647. allowed_node_names=allowed,
  648. node_belonging_dim=node_belonging_dim if node_belonging_dim else None,
  649. )
  650. if items and post_id:
  651. node_names = [x["节点名称"] for x in items]
  652. matched_results = await match_derivation_to_post_points(
  653. node_names, account_name, post_id, match_threshold=float(match_score_threshold)
  654. )
  655. node_match_map: dict[str, list] = {}
  656. for m in matched_results:
  657. node_match_map.setdefault(m["推导选题点"], []).append({
  658. "帖子选题点": m["帖子选题点"],
  659. "匹配分数": m["匹配分数"],
  660. })
  661. for item in items:
  662. matches = node_match_map.get(item["节点名称"], [])
  663. item["帖子选题点匹配"] = matches if matches else "无"
  664. # 账号配额:占 top_n 的 60%,有/无匹配各一半
  665. account_quota = int(top_n * 0.6 + 0.5)
  666. account_with_n = account_quota // 2
  667. account_without_n = account_quota - account_with_n
  668. items_with_match = [x for x in items if isinstance(x.get("帖子选题点匹配"), list)]
  669. items_without_match = [x for x in items if not isinstance(x.get("帖子选题点匹配"), list)]
  670. items = items_with_match[:account_with_n] + items_without_match[:account_without_n]
  671. # 2)平台库人设树(条件概率 + xiaohongshu 匹配文件)
  672. # 平台配额:占 top_n 的 40%,有/无匹配各一半
  673. platform_quota = top_n - account_quota
  674. platform_with_n = platform_quota // 2
  675. platform_without_n = platform_quota - platform_with_n
  676. # 平台「有匹配」排除账号侧已有帖子选题点匹配的节点名(与账号段去重)。
  677. # 平台「无匹配」排除已在账号段输出里出现过的节点名(避免重复罗列无新信息的同名节点)。
  678. account_matched_names = {str(x.get("节点名称", "")).strip() for x in items if isinstance(x.get("帖子选题点匹配"), list)}
  679. account_all_names = {str(x.get("节点名称", "")).strip() for x in items}
  680. platform_items: list[dict[str, Any]] = []
  681. if post_id:
  682. p_matched_raw, p_unmatched_raw = _load_platform_nodes_split(
  683. post_id=post_id,
  684. derived_list=derived_list,
  685. conditional_ratio_threshold=float(conditional_ratio_threshold),
  686. match_score_threshold=float(match_score_threshold),
  687. top_n=top_n,
  688. node_belonging_dim_platform=node_belonging_dim_platform,
  689. )
  690. p_matched = [p for p in p_matched_raw if str(p.get("节点名称", "")).strip() not in account_matched_names]
  691. p_unmatched = [p for p in p_unmatched_raw if str(p.get("节点名称", "")).strip() not in account_all_names]
  692. platform_items = p_matched[:platform_with_n] + p_unmatched[:platform_without_n]
  693. def _format_node_line(x: dict[str, Any]) -> str:
  694. match_info = x.get("帖子选题点匹配", "无")
  695. if isinstance(match_info, list):
  696. match_str = "、".join(f"{m['帖子选题点']}({m['匹配分数']})" for m in match_info)
  697. else:
  698. match_str = str(match_info)
  699. dim_label = x.get("所属维度", "—")
  700. return (
  701. f"- {x['节点名称']}\t条件概率={x['条件概率']}\t所属维度={dim_label}"
  702. f"\t帖子选题点匹配={match_str}"
  703. )
  704. lines: list[str] = []
  705. lines.append(
  706. "【优先使用】第一节为账号人设树中条件概率达标的节点(占60%配额,有/无帖子匹配各半);"
  707. "第二节为平台库人设树中条件概率达标的节点(占40%配额,有/无帖子匹配各半);"
  708. )
  709. lines.append("")
  710. lines.append("—— 账号人设树节点 ——")
  711. if not items:
  712. lines.append(f"(无:未找到条件概率 >= {conditional_ratio_threshold} 的节点)")
  713. else:
  714. lines.extend(_format_node_line(x) for x in items)
  715. lines.append("")
  716. lines.append("—— 平台库人设树节点 ——")
  717. if not platform_items:
  718. lines.append(
  719. "(无:未找到条件概率达标的节点)"
  720. )
  721. else:
  722. lines.extend(_format_node_line(x) for x in platform_items)
  723. output = "\n".join(lines)
  724. return ToolResult(
  725. title=f"条件概率节点 ({account_name}, 阈值={conditional_ratio_threshold})",
  726. output=output,
  727. metadata={
  728. "account_name": account_name,
  729. "threshold": conditional_ratio_threshold,
  730. "match_score_threshold": float(match_score_threshold),
  731. "top_n": top_n,
  732. "quota": {
  733. "account_quota": account_quota,
  734. "account_with_match": len([x for x in items if isinstance(x.get("帖子选题点匹配"), list)]),
  735. "account_without_match": len([x for x in items if not isinstance(x.get("帖子选题点匹配"), list)]),
  736. "platform_quota": platform_quota,
  737. "platform_with_match": len([x for x in platform_items if isinstance(x.get("帖子选题点匹配"), list)]),
  738. "platform_without_match": len([x for x in platform_items if not isinstance(x.get("帖子选题点匹配"), list)]),
  739. },
  740. "account_tree_count": len(items),
  741. "platform_tree_count": len(platform_items),
  742. "count": len(items) + len(platform_items),
  743. "round": int(round),
  744. "log_id": str(log_id).strip() if log_id else "",
  745. "dimension_filter": {
  746. "derived_dim_nodes": derived_dim_names,
  747. "allowed_descendant_count": len(allowed) if allowed is not None else None,
  748. "source": dim_source or ("未提供 log_id,未按维度收窄" if not (log_id and str(log_id).strip()) else ""),
  749. },
  750. },
  751. )
  752. except Exception as e:
  753. return ToolResult(
  754. title="按条件概率查询节点失败",
  755. output=str(e),
  756. error=str(e),
  757. )
  758. def main() -> None:
  759. """本地测试:用家有大志账号测常量节点与条件概率节点,有 agent 时再跑一遍 tool 接口。"""
  760. import asyncio
  761. account_name = "家有大志"
  762. post_id = "68fb6a5c000000000302e5de"
  763. log_id = "20260319134630"
  764. round = 4
  765. # derived_items = [
  766. # {"topic": "分享", "source_node": "分享"},
  767. # {"topic": "叙事结构", "source_node": "叙事结构"},
  768. # ]
  769. derived_items = [{"topic":"推广","source_node":"推广"},{"topic":"视觉调性","source_node":"视觉调性"}]
  770. conditional_ratio_threshold = 0.2
  771. top_n = 200
  772. # # 1)常量节点(核心函数,无匹配)
  773. # constant_nodes = get_constant_nodes(account_name)
  774. # print(f"账号: {account_name} — 常量节点共 {len(constant_nodes)} 个(前 50 个):")
  775. # for x in constant_nodes[:50]:
  776. # print(f" - {x['节点名称']}\t概率={x['概率']}\t{x['常量类型']}")
  777. # print()
  778. #
  779. # # 2)条件概率节点(核心函数)
  780. # derived_list = _parse_derived_list(derived_items)
  781. # ratio_nodes = get_nodes_by_conditional_ratio(
  782. # account_name, derived_list, conditional_ratio_threshold, top_n
  783. # )
  784. # print(f"条件概率节点 阈值={conditional_ratio_threshold}, top_n={top_n}, 共 {len(ratio_nodes)} 个:")
  785. # for x in ratio_nodes:
  786. # print(f" - {x['节点名称']}\t条件概率={x['条件概率']}\t父节点={x['父节点名称']}")
  787. # print()
  788. # 3)有 agent 时通过 tool 接口再跑一遍(含帖子选题点匹配)
  789. if ToolResult is not None:
  790. async def run_tools():
  791. r1 = await find_tree_constant_nodes(account_name, post_id=post_id)
  792. print("--- find_tree_constant_nodes ---")
  793. print(r1.output[:2000] + "..." if len(r1.output) > 2000 else r1.output)
  794. r2 = await find_tree_nodes_by_conditional_ratio(
  795. account_name,
  796. post_id=post_id,
  797. derived_items=derived_items,
  798. conditional_ratio_threshold=conditional_ratio_threshold,
  799. top_n=top_n,
  800. round=round,
  801. log_id=log_id,
  802. )
  803. print("\n--- find_tree_nodes_by_conditional_ratio ---")
  804. print(r2.output)
  805. asyncio.run(run_tools())
  806. if __name__ == "__main__":
  807. main()