find_tree_node.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. """
  2. 查找树节点 Tool - 人设树节点查询
  3. 功能:
  4. 1. 获取人设树的常量节点(全局常量、局部常量)
  5. 2. 获取符合条件概率阈值的节点(按条件概率排序返回 topN)
  6. """
  7. import importlib.util
  8. import json
  9. from pathlib import Path
  10. from typing import Any, Optional
  11. try:
  12. from agent.tools import tool, ToolResult, ToolContext
  13. except ImportError:
  14. def tool(*args, **kwargs):
  15. return lambda f: f
  16. ToolResult = None # 仅用 main() 测核心逻辑时可无 agent
  17. ToolContext = None
  18. # 加载同目录层级的 conditional_ratio_calc(不依赖包结构)
  19. _utils_dir = Path(__file__).resolve().parent.parent / "utils"
  20. _cond_spec = importlib.util.spec_from_file_location(
  21. "conditional_ratio_calc",
  22. _utils_dir / "conditional_ratio_calc.py",
  23. )
  24. _cond_mod = importlib.util.module_from_spec(_cond_spec)
  25. _cond_spec.loader.exec_module(_cond_mod)
  26. calc_node_conditional_ratio = _cond_mod.calc_node_conditional_ratio
  27. # 相对本文件:tools -> overall_derivation,input 在 overall_derivation 下
  28. _BASE_INPUT = Path(__file__).resolve().parent.parent / "input"
  29. def _tree_dir(account_name: str) -> Path:
  30. """人设树目录:../input/{account_name}/原始数据/tree/"""
  31. return _BASE_INPUT / account_name / "原始数据" / "tree"
  32. def _load_trees(account_name: str) -> list[tuple[str, dict]]:
  33. """加载该账号下所有维度的人设树。返回 [(维度名, 根节点 dict), ...]。"""
  34. td = _tree_dir(account_name)
  35. if not td.is_dir():
  36. return []
  37. result = []
  38. for p in td.glob("*.json"):
  39. try:
  40. with open(p, "r", encoding="utf-8") as f:
  41. data = json.load(f)
  42. for dim_name, root in data.items():
  43. if isinstance(root, dict):
  44. result.append((dim_name, root))
  45. break
  46. except Exception:
  47. continue
  48. return result
  49. def _iter_all_nodes(account_name: str):
  50. """遍历该账号下所有人设树节点,产出 (节点名称, 父节点名称, 节点 dict)。"""
  51. for dim_name, root in _load_trees(account_name):
  52. def walk(parent_name: str, node_dict: dict):
  53. for name, child in (node_dict.get("children") or {}).items():
  54. if not isinstance(child, dict):
  55. continue
  56. yield (name, parent_name, child)
  57. yield from walk(name, child)
  58. yield from walk(dim_name, root)
  59. # ---------------------------------------------------------------------------
  60. # 1. 获取人设树常量节点
  61. # ---------------------------------------------------------------------------
  62. def get_constant_nodes(account_name: str) -> list[dict[str, Any]]:
  63. """
  64. 获取人设树的常量节点。
  65. - 全局常量:_is_constant=True
  66. - 局部常量:_is_local_constant=True 且 _is_constant=False
  67. 返回列表项:节点名称、概率(_ratio)、常量类型。
  68. """
  69. result = []
  70. for node_name, _parent, node in _iter_all_nodes(account_name):
  71. is_const = node.get("_is_constant") is True
  72. is_local = node.get("_is_local_constant") is True
  73. if is_const:
  74. const_type = "全局常量"
  75. elif is_local and not is_const:
  76. const_type = "局部常量"
  77. else:
  78. continue
  79. ratio = node.get("_ratio")
  80. result.append({
  81. "节点名称": node_name,
  82. "概率": ratio,
  83. "常量类型": const_type,
  84. })
  85. result.sort(key=lambda x: (x["概率"] is None, -(x["概率"] or 0)))
  86. return result
  87. # ---------------------------------------------------------------------------
  88. # 2. 获取符合条件概率阈值的节点
  89. # ---------------------------------------------------------------------------
  90. def get_nodes_by_conditional_ratio(
  91. account_name: str,
  92. derived_list: list[tuple[str, str]],
  93. threshold: float,
  94. top_n: int,
  95. ) -> list[dict[str, Any]]:
  96. """
  97. 获取人设树中条件概率 >= threshold 的节点,按条件概率降序,返回前 top_n 个。
  98. derived_list: 已推导列表,每项 (已推导的选题点, 推导来源人设树节点)。
  99. 返回列表项:节点名称、条件概率、父节点名称。
  100. """
  101. base_dir = _BASE_INPUT
  102. node_to_parent: dict[str, str] = {}
  103. for node_name, parent_name, _ in _iter_all_nodes(account_name):
  104. node_to_parent[node_name] = parent_name
  105. scored: list[tuple[str, float, str]] = []
  106. for node_name, parent_name in node_to_parent.items():
  107. ratio = calc_node_conditional_ratio(
  108. account_name, derived_list, node_name, base_dir=base_dir
  109. )
  110. if ratio >= threshold:
  111. scored.append((node_name, ratio, parent_name))
  112. scored.sort(key=lambda x: x[1], reverse=True)
  113. top = scored[:top_n]
  114. return [
  115. {"节点名称": name, "条件概率": ratio, "父节点名称": parent}
  116. for name, ratio, parent in top
  117. ]
  118. def _parse_derived_list(derived_items: list[dict[str, str]]) -> list[tuple[str, str]]:
  119. """将 agent 传入的 [{"topic": "x", "source_node": "y"}, ...] 转为 DerivedItem 列表。"""
  120. out = []
  121. for item in derived_items:
  122. if isinstance(item, dict):
  123. topic = item.get("topic") or item.get("已推导的选题点")
  124. source = item.get("source_node") or item.get("推导来源人设树节点")
  125. if topic is not None and source is not None:
  126. out.append((str(topic).strip(), str(source).strip()))
  127. elif isinstance(item, (list, tuple)) and len(item) >= 2:
  128. out.append((str(item[0]).strip(), str(item[1]).strip()))
  129. return out
  130. # ---------------------------------------------------------------------------
  131. # Agent Tools(参考 glob_tool 封装)
  132. # ---------------------------------------------------------------------------
  133. @tool(description="获取人设树的常量节点(全局常量、局部常量)。输入账号名,返回节点名称、概率、常量类型。")
  134. async def find_tree_constant_nodes(
  135. account_name: str,
  136. context: Optional[ToolContext] = None,
  137. ) -> ToolResult:
  138. """
  139. 获取人设树的常量节点。
  140. 读取该账号 input/{account_name}/原始数据/tree/ 下的人设树 JSON,
  141. 筛选 _is_constant=true(全局常量)或 _is_local_constant=true 且 _is_constant=false(局部常量)的节点,
  142. 返回:节点名称、概率(_ratio)、常量类型。
  143. """
  144. tree_dir = _tree_dir(account_name)
  145. if not tree_dir.is_dir():
  146. return ToolResult(
  147. title="人设树目录不存在",
  148. output=f"目录不存在: {tree_dir}",
  149. error="Directory not found",
  150. )
  151. try:
  152. items = get_constant_nodes(account_name)
  153. if not items:
  154. output = "未找到常量节点"
  155. else:
  156. lines = [f"- {x['节点名称']}\t概率={x['概率']}\t{x['常量类型']}" for x in items]
  157. output = "\n".join(lines)
  158. return ToolResult(
  159. title=f"常量节点 ({account_name})",
  160. output=output,
  161. metadata={"account_name": account_name, "count": len(items), "items": items},
  162. )
  163. except Exception as e:
  164. return ToolResult(
  165. title="获取常量节点失败",
  166. output=str(e),
  167. error=str(e),
  168. )
  169. @tool(
  170. description="获取人设树中条件概率不低于阈值的节点,按条件概率从高到低返回 topN。"
  171. "输入:账号名、已推导选题点列表、条件概率阈值、topN。"
  172. )
  173. async def find_tree_nodes_by_conditional_ratio(
  174. account_name: str,
  175. derived_items: list[dict[str, str]],
  176. conditional_ratio_threshold: float,
  177. top_n: int = 20,
  178. context: Optional[ToolContext] = None,
  179. ) -> ToolResult:
  180. """
  181. 获取人设树中符合条件概率阈值的节点。
  182. 已推导选题点 derived_items:每项为 {\"topic\": \"已推导选题点\", \"source_node\": \"推导来源人设树节点\"}。
  183. 返回:节点名称、条件概率、父节点名称,按条件概率降序最多 top_n 条。
  184. """
  185. tree_dir = _tree_dir(account_name)
  186. if not tree_dir.is_dir():
  187. return ToolResult(
  188. title="人设树目录不存在",
  189. output=f"目录不存在: {tree_dir}",
  190. error="Directory not found",
  191. )
  192. try:
  193. derived_list = _parse_derived_list(derived_items)
  194. if not derived_list:
  195. return ToolResult(
  196. title="参数无效",
  197. output="derived_items 不能为空,且每项需包含 topic 与 source_node(或 已推导的选题点 与 推导来源人设树节点)",
  198. error="Invalid derived_items",
  199. )
  200. items = get_nodes_by_conditional_ratio(
  201. account_name, derived_list, conditional_ratio_threshold, top_n
  202. )
  203. if not items:
  204. output = f"未找到条件概率 >= {conditional_ratio_threshold} 的节点"
  205. else:
  206. lines = [
  207. f"- {x['节点名称']}\t条件概率={x['条件概率']}\t父节点={x['父节点名称']}"
  208. for x in items
  209. ]
  210. output = "\n".join(lines)
  211. return ToolResult(
  212. title=f"条件概率节点 ({account_name}, 阈值={conditional_ratio_threshold})",
  213. output=output,
  214. metadata={
  215. "account_name": account_name,
  216. "threshold": conditional_ratio_threshold,
  217. "top_n": top_n,
  218. "count": len(items),
  219. "items": items,
  220. },
  221. )
  222. except Exception as e:
  223. return ToolResult(
  224. title="按条件概率查询节点失败",
  225. output=str(e),
  226. error=str(e),
  227. )
  228. def main() -> None:
  229. """本地测试:用家有大志账号测常量节点与条件概率节点,有 agent 时再跑一遍 tool 接口。"""
  230. import asyncio
  231. account_name = "家有大志"
  232. derived_items = [
  233. {"topic": "分享", "source_node": "分享"},
  234. ]
  235. conditional_ratio_threshold = 0.1
  236. top_n = 10
  237. # 1)常量节点
  238. constant_nodes = get_constant_nodes(account_name)
  239. print(f"账号: {account_name} — 常量节点共 {len(constant_nodes)} 个(前 50 个):")
  240. for x in constant_nodes[:50]:
  241. print(f" - {x['节点名称']}\t概率={x['概率']}\t{x['常量类型']}")
  242. print()
  243. # 2)条件概率节点(核心函数)
  244. derived_list = _parse_derived_list(derived_items)
  245. ratio_nodes = get_nodes_by_conditional_ratio(
  246. account_name, derived_list, conditional_ratio_threshold, top_n
  247. )
  248. print(f"条件概率节点 阈值={conditional_ratio_threshold}, top_n={top_n}, 共 {len(ratio_nodes)} 个:")
  249. for x in ratio_nodes:
  250. print(f" - {x['节点名称']}\t条件概率={x['条件概率']}\t父节点={x['父节点名称']}")
  251. print()
  252. # 3)有 agent 时通过 tool 接口再跑一遍
  253. if ToolResult is not None:
  254. async def run_tools():
  255. r1 = await find_tree_constant_nodes(account_name)
  256. print("--- find_tree_constant_nodes ---")
  257. print(r1.output[:200] + "..." if len(r1.output) > 200 else r1.output)
  258. r2 = await find_tree_nodes_by_conditional_ratio(
  259. account_name,
  260. derived_items=derived_items,
  261. conditional_ratio_threshold=conditional_ratio_threshold,
  262. top_n=top_n,
  263. )
  264. print("\n--- find_tree_nodes_by_conditional_ratio ---")
  265. print(r2.output)
  266. asyncio.run(run_tools())
  267. if __name__ == "__main__":
  268. main()