find_tree_node.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. """
  2. 查找树节点 Tool - 人设树节点查询
  3. 功能:
  4. 1. 获取人设树的常量节点(全局常量、局部常量)
  5. 2. 获取符合条件概率阈值的节点(按条件概率排序返回 topN)
  6. """
  7. import json
  8. import sys
  9. from pathlib import Path
  10. from typing import Any, Optional
  11. # 保证直接运行或作为包加载时都能解析 utils / tools(IDE 可跳转)
  12. _root = Path(__file__).resolve().parent.parent
  13. if str(_root) not in sys.path:
  14. sys.path.insert(0, str(_root))
  15. from utils.conditional_ratio_calc import calc_node_conditional_ratio
  16. from tools.point_match import match_derivation_to_post_points
  17. try:
  18. from agent.tools import tool, ToolResult, ToolContext
  19. except ImportError:
  20. def tool(*args, **kwargs):
  21. return lambda f: f
  22. ToolResult = None # 仅用 main() 测核心逻辑时可无 agent
  23. ToolContext = None
  24. # 相对本文件:tools -> overall_derivation,input 在 overall_derivation 下
  25. _BASE_INPUT = Path(__file__).resolve().parent.parent / "input"
  26. def _tree_dir(account_name: str) -> Path:
  27. """人设树目录:../input/{account_name}/原始数据/tree/"""
  28. return _BASE_INPUT / account_name / "原始数据" / "tree"
  29. def _load_trees(account_name: str) -> list[tuple[str, dict]]:
  30. """加载该账号下所有维度的人设树。返回 [(维度名, 根节点 dict), ...]。"""
  31. td = _tree_dir(account_name)
  32. if not td.is_dir():
  33. return []
  34. result = []
  35. for p in td.glob("*.json"):
  36. try:
  37. with open(p, "r", encoding="utf-8") as f:
  38. data = json.load(f)
  39. for dim_name, root in data.items():
  40. if isinstance(root, dict):
  41. result.append((dim_name, root))
  42. break
  43. except Exception:
  44. continue
  45. return result
  46. def _iter_all_nodes(account_name: str):
  47. """遍历该账号下所有人设树节点,产出 (节点名称, 父节点名称, 节点 dict)。"""
  48. for dim_name, root in _load_trees(account_name):
  49. def walk(parent_name: str, node_dict: dict):
  50. for name, child in (node_dict.get("children") or {}).items():
  51. if not isinstance(child, dict):
  52. continue
  53. yield (name, parent_name, child)
  54. yield from walk(name, child)
  55. yield from walk(dim_name, root)
  56. # ---------------------------------------------------------------------------
  57. # 1. 获取人设树常量节点
  58. # ---------------------------------------------------------------------------
  59. def get_constant_nodes(account_name: str) -> list[dict[str, Any]]:
  60. """
  61. 获取人设树的常量节点。
  62. - 全局常量:_is_constant=True
  63. - 局部常量:_is_local_constant=True 且 _is_constant=False
  64. 返回列表项:节点名称、概率(_ratio)、常量类型。
  65. """
  66. result = []
  67. for node_name, _parent, node in _iter_all_nodes(account_name):
  68. is_const = node.get("_is_constant") is True
  69. is_local = node.get("_is_local_constant") is True
  70. if is_const:
  71. const_type = "全局常量"
  72. elif is_local and not is_const:
  73. const_type = "局部常量"
  74. else:
  75. continue
  76. ratio = node.get("_ratio")
  77. result.append({
  78. "节点名称": node_name,
  79. "概率": ratio,
  80. "常量类型": const_type,
  81. })
  82. result.sort(key=lambda x: (x["概率"] is None, -(x["概率"] or 0)))
  83. return result
  84. # ---------------------------------------------------------------------------
  85. # 2. 获取符合条件概率阈值的节点
  86. # ---------------------------------------------------------------------------
  87. def get_nodes_by_conditional_ratio(
  88. account_name: str,
  89. derived_list: list[tuple[str, str]],
  90. threshold: float,
  91. top_n: int,
  92. ) -> list[dict[str, Any]]:
  93. """
  94. 获取人设树中条件概率 >= threshold 的节点,按条件概率降序,返回前 top_n 个。
  95. derived_list: 已推导列表,每项 (已推导的选题点, 推导来源人设树节点);为空时使用节点自身的 _ratio 作为条件概率。
  96. 返回列表项:节点名称、条件概率、父节点名称。
  97. """
  98. base_dir = _BASE_INPUT
  99. scored: list[tuple[str, float, str]] = []
  100. if not derived_list:
  101. # derived_items 为空:条件概率取节点本身的 _ratio
  102. for node_name, parent_name, node in _iter_all_nodes(account_name):
  103. ratio = node.get("_ratio")
  104. if ratio is None:
  105. ratio = 0.0
  106. else:
  107. ratio = float(ratio)
  108. if ratio >= threshold:
  109. scored.append((node_name, ratio, parent_name))
  110. else:
  111. node_to_parent: dict[str, str] = {}
  112. for node_name, parent_name, _ in _iter_all_nodes(account_name):
  113. node_to_parent[node_name] = parent_name
  114. for node_name, parent_name in node_to_parent.items():
  115. ratio = calc_node_conditional_ratio(
  116. account_name, derived_list, node_name, base_dir=base_dir
  117. )
  118. if ratio >= threshold:
  119. scored.append((node_name, ratio, parent_name))
  120. scored.sort(key=lambda x: x[1], reverse=True)
  121. top = scored[:top_n]
  122. return [
  123. {"节点名称": name, "条件概率": ratio, "父节点名称": parent}
  124. for name, ratio, parent in top
  125. ]
  126. def _parse_derived_list(derived_items: list[dict[str, str]]) -> list[tuple[str, str]]:
  127. """将 agent 传入的 [{"topic": "x", "source_node": "y"}, ...] 转为 DerivedItem 列表。"""
  128. out = []
  129. for item in derived_items:
  130. if isinstance(item, dict):
  131. topic = item.get("topic") or item.get("已推导的选题点")
  132. source = item.get("source_node") or item.get("推导来源人设树节点")
  133. if topic is not None and source is not None:
  134. out.append((str(topic).strip(), str(source).strip()))
  135. elif isinstance(item, (list, tuple)) and len(item) >= 2:
  136. out.append((str(item[0]).strip(), str(item[1]).strip()))
  137. return out
  138. # ---------------------------------------------------------------------------
  139. # Agent Tools(参考 glob_tool 封装)
  140. # ---------------------------------------------------------------------------
  141. @tool(
  142. description="获取指定账号人设树中的常量节点(全局常量、局部常量),并检查每个节点与帖子选题点的匹配情况。"
  143. "功能:根据账号名查询该账号人设树中所有常量节点,同时对每个节点判断是否匹配帖子选题点,匹配结果直接包含在返回数据中。"
  144. "参数:account_name 为账号名;post_id 为帖子ID,用于加载帖子选题点并做匹配判断。"
  145. "返回:ToolResult,output 为可读的节点列表文本,metadata.items 为列表,每项含「节点名称」「概率」「常量类型」「帖子选题点匹配」(超过阈值的匹配列表,每项含帖子选题点与匹配分数;若无匹配则为字符串'无匹配帖子选题点')。"
  146. )
  147. async def find_tree_constant_nodes(
  148. account_name: str,
  149. post_id: str,
  150. context: Optional[ToolContext] = None,
  151. ) -> ToolResult:
  152. """
  153. 获取人设树中的常量节点列表(全局常量与局部常量),并检查每个节点与帖子选题点的匹配情况。
  154. 参数
  155. -------
  156. account_name : 账号名,用于定位该账号的人设树数据。
  157. post_id : 帖子ID,用于加载帖子选题点并与各常量节点做匹配判断。
  158. context : 可选,Agent 工具上下文。
  159. 返回
  160. -------
  161. ToolResult:
  162. - title: 结果标题。
  163. - output: 可读的节点列表文本(每行:节点名称、概率、常量类型、帖子匹配情况)。
  164. - metadata: 含 account_name、count、items;items 为列表,每项为
  165. {"节点名称": str, "概率": 数值或 None, "常量类型": "全局常量"|"局部常量",
  166. "帖子选题点匹配": list[{"帖子选题点": str, "匹配分数": float}] 或 "无匹配帖子选题点"}。
  167. - 出错时 error 为错误信息。
  168. """
  169. tree_dir = _tree_dir(account_name)
  170. if not tree_dir.is_dir():
  171. return ToolResult(
  172. title="人设树目录不存在",
  173. output=f"目录不存在: {tree_dir}",
  174. error="Directory not found",
  175. )
  176. try:
  177. items = get_constant_nodes(account_name)
  178. # 批量匹配所有节点与帖子选题点
  179. if items and post_id:
  180. node_names = [x["节点名称"] for x in items]
  181. matched_results = await match_derivation_to_post_points(node_names, account_name, post_id)
  182. node_match_map: dict[str, list] = {}
  183. for m in matched_results:
  184. node_match_map.setdefault(m["推导选题点"], []).append({
  185. "帖子选题点": m["帖子选题点"],
  186. "匹配分数": m["匹配分数"],
  187. })
  188. for item in items:
  189. matches = node_match_map.get(item["节点名称"], [])
  190. item["帖子选题点匹配"] = matches if matches else "无匹配帖子选题点"
  191. if not items:
  192. output = "未找到常量节点"
  193. else:
  194. lines = []
  195. for x in items:
  196. match_info = x.get("帖子选题点匹配", "未查询")
  197. if isinstance(match_info, list):
  198. match_str = "、".join(f"{m['帖子选题点']}({m['匹配分数']})" for m in match_info)
  199. else:
  200. match_str = str(match_info)
  201. lines.append(f"- {x['节点名称']}\t概率={x['概率']}\t{x['常量类型']}\t帖子匹配={match_str}")
  202. output = "\n".join(lines)
  203. return ToolResult(
  204. title=f"常量节点 ({account_name})",
  205. output=output,
  206. metadata={"account_name": account_name, "count": len(items)},
  207. )
  208. except Exception as e:
  209. return ToolResult(
  210. title="获取常量节点失败",
  211. output=str(e),
  212. error=str(e),
  213. )
  214. @tool(
  215. description="按条件概率从人设树中筛选节点,返回达到阈值且按条件概率排序的前 topN 条,并检查每个节点与帖子选题点的匹配情况。"
  216. "功能:根据账号与已推导选题点(可选),筛选人设树中条件概率不低于阈值的节点,同时对每个节点判断是否匹配帖子选题点,匹配结果直接包含在返回数据中。"
  217. "参数:account_name 为账号名;post_id 为帖子ID,用于加载帖子选题点并做匹配判断;derived_items 为已推导选题点列表,每项含 topic(或已推导的选题点)与 source_node(或推导来源人设树节点),可为空,为空时条件概率使用节点自身的 _ratio;conditional_ratio_threshold 为条件概率阈值;top_n 为返回条数上限,默认 100。"
  218. "返回:ToolResult,output 为可读的节点列表文本,metadata.items 为列表,每项含「节点名称」「条件概率」「父节点名称」「帖子选题点匹配」(超过阈值的匹配列表,每项含帖子选题点与匹配分数;若无匹配则为字符串'无匹配帖子选题点')。"
  219. )
  220. async def find_tree_nodes_by_conditional_ratio(
  221. account_name: str,
  222. post_id: str,
  223. derived_items: list[dict[str, str]],
  224. conditional_ratio_threshold: float,
  225. top_n: int = 100,
  226. context: Optional[ToolContext] = None,
  227. ) -> ToolResult:
  228. """
  229. 按条件概率阈值从人设树筛选节点,返回最多 top_n 条(按条件概率降序),并检查每个节点与帖子选题点的匹配情况。
  230. 参数
  231. -------
  232. account_name : 账号名,用于定位该账号的人设树数据。
  233. post_id : 帖子ID,用于加载帖子选题点并与各节点做匹配判断。
  234. derived_items : 已推导选题点列表,可为空。非空时每项为字典,需含 topic(或「已推导的选题点」)与 source_node(或「推导来源人设树节点」);为空时各节点的条件概率取其自身 _ratio。
  235. conditional_ratio_threshold : 条件概率阈值,仅返回条件概率 >= 该值的节点。
  236. top_n : 返回条数上限,默认 100。
  237. context : 可选,Agent 工具上下文。
  238. 返回
  239. -------
  240. ToolResult:
  241. - title: 结果标题。
  242. - output: 可读的节点列表文本(每行:节点名称、条件概率、父节点名称、帖子匹配情况)。
  243. - metadata: 含 account_name、threshold、top_n、count、items;
  244. items 为列表,每项为 {"节点名称": str, "条件概率": float, "父节点名称": str,
  245. "帖子选题点匹配": list[{"帖子选题点": str, "匹配分数": float}] 或 "无匹配帖子选题点"}。
  246. - 出错时 error 为错误信息。
  247. """
  248. tree_dir = _tree_dir(account_name)
  249. if not tree_dir.is_dir():
  250. return ToolResult(
  251. title="人设树目录不存在",
  252. output=f"目录不存在: {tree_dir}",
  253. error="Directory not found",
  254. )
  255. try:
  256. derived_list = _parse_derived_list(derived_items or [])
  257. items = get_nodes_by_conditional_ratio(
  258. account_name, derived_list, conditional_ratio_threshold, top_n
  259. )
  260. # 批量匹配所有节点与帖子选题点
  261. if items and post_id:
  262. node_names = [x["节点名称"] for x in items]
  263. matched_results = await match_derivation_to_post_points(node_names, account_name, post_id)
  264. node_match_map: dict[str, list] = {}
  265. for m in matched_results:
  266. node_match_map.setdefault(m["推导选题点"], []).append({
  267. "帖子选题点": m["帖子选题点"],
  268. "匹配分数": m["匹配分数"],
  269. })
  270. for item in items:
  271. matches = node_match_map.get(item["节点名称"], [])
  272. item["帖子选题点匹配"] = matches if matches else "无匹配帖子选题点"
  273. if not items:
  274. output = f"未找到条件概率 >= {conditional_ratio_threshold} 的节点"
  275. else:
  276. lines = []
  277. for x in items:
  278. match_info = x.get("帖子选题点匹配", "未查询")
  279. if isinstance(match_info, list):
  280. match_str = "、".join(f"{m['帖子选题点']}({m['匹配分数']})" for m in match_info)
  281. else:
  282. match_str = str(match_info)
  283. lines.append(
  284. f"- {x['节点名称']}\t条件概率={x['条件概率']}\t父节点={x['父节点名称']}\t帖子匹配={match_str}"
  285. )
  286. output = "\n".join(lines)
  287. return ToolResult(
  288. title=f"条件概率节点 ({account_name}, 阈值={conditional_ratio_threshold})",
  289. output=output,
  290. metadata={
  291. "account_name": account_name,
  292. "threshold": conditional_ratio_threshold,
  293. "top_n": top_n,
  294. "count": len(items),
  295. },
  296. )
  297. except Exception as e:
  298. return ToolResult(
  299. title="按条件概率查询节点失败",
  300. output=str(e),
  301. error=str(e),
  302. )
  303. def main() -> None:
  304. """本地测试:用家有大志账号测常量节点与条件概率节点,有 agent 时再跑一遍 tool 接口。"""
  305. import asyncio
  306. account_name = "家有大志"
  307. post_id = "68fb6a5c000000000302e5de"
  308. derived_items = [
  309. {"topic": "分享", "source_node": "分享"},
  310. {"topic": "叙事结构", "source_node": "叙事结构"},
  311. ]
  312. conditional_ratio_threshold = 0.1
  313. top_n = 100
  314. # 1)常量节点(核心函数,无匹配)
  315. constant_nodes = get_constant_nodes(account_name)
  316. print(f"账号: {account_name} — 常量节点共 {len(constant_nodes)} 个(前 50 个):")
  317. for x in constant_nodes[:50]:
  318. print(f" - {x['节点名称']}\t概率={x['概率']}\t{x['常量类型']}")
  319. print()
  320. # 2)条件概率节点(核心函数)
  321. derived_list = _parse_derived_list(derived_items)
  322. ratio_nodes = get_nodes_by_conditional_ratio(
  323. account_name, derived_list, conditional_ratio_threshold, top_n
  324. )
  325. print(f"条件概率节点 阈值={conditional_ratio_threshold}, top_n={top_n}, 共 {len(ratio_nodes)} 个:")
  326. for x in ratio_nodes:
  327. print(f" - {x['节点名称']}\t条件概率={x['条件概率']}\t父节点={x['父节点名称']}")
  328. print()
  329. # 3)有 agent 时通过 tool 接口再跑一遍(含帖子选题点匹配)
  330. if ToolResult is not None:
  331. async def run_tools():
  332. r1 = await find_tree_constant_nodes(account_name, post_id=post_id)
  333. print("--- find_tree_constant_nodes ---")
  334. print(r1.output[:2000] + "..." if len(r1.output) > 2000 else r1.output)
  335. r2 = await find_tree_nodes_by_conditional_ratio(
  336. account_name,
  337. post_id=post_id,
  338. derived_items=derived_items,
  339. conditional_ratio_threshold=conditional_ratio_threshold,
  340. top_n=top_n,
  341. )
  342. print("\n--- find_tree_nodes_by_conditional_ratio ---")
  343. print(r2.output)
  344. asyncio.run(run_tools())
  345. if __name__ == "__main__":
  346. main()