sug_v6_1_2_3.py 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  1. import asyncio
  2. import json
  3. import os
  4. import sys
  5. import argparse
  6. from datetime import datetime
  7. from agents import Agent, Runner
  8. from lib.my_trace import set_trace
  9. from typing import Literal
  10. from pydantic import BaseModel, Field
  11. from lib.utils import read_file_as_string
  12. from lib.client import get_model
  13. MODEL_NAME = "google/gemini-2.5-flash"
  14. from script.search_recommendations.xiaohongshu_search_recommendations import XiaohongshuSearchRecommendations
  15. from script.search.xiaohongshu_search import XiaohongshuSearch
  16. class RunContext(BaseModel):
  17. version: str = Field(..., description="当前运行的脚本版本(文件名)")
  18. input_files: dict[str, str] = Field(..., description="输入文件路径映射")
  19. q_with_context: str
  20. q_context: str
  21. q: str
  22. log_url: str
  23. log_dir: str
  24. # 步骤化日志
  25. steps: list[dict] = Field(default_factory=list, description="执行步骤的详细记录")
  26. # 探索阶段记录(保留用于向后兼容)
  27. keywords: list[str] | None = Field(default=None, description="提取的关键词")
  28. exploration_levels: list[dict] = Field(default_factory=list, description="每一层的探索结果")
  29. level_analyses: list[dict] = Field(default_factory=list, description="每一层的主Agent分析")
  30. # 最终结果
  31. final_candidates: list[str] | None = Field(default=None, description="最终选出的候选query")
  32. evaluation_results: list[dict] | None = Field(default=None, description="候选query的评估结果")
  33. optimization_result: dict | None = Field(default=None, description="最终优化结果对象")
  34. final_output: str | None = Field(default=None, description="最终输出结果(格式化文本)")
  35. # ============================================================================
  36. # Agent 1: 关键词提取专家
  37. # ============================================================================
  38. keyword_extraction_instructions = """
  39. 你是关键词提取专家。给定一个搜索问题(含上下文),提取出**最细粒度的关键概念**。
  40. ## 提取原则
  41. 1. **细粒度优先**:拆分成最小的有意义单元
  42. - 不要保留完整的长句
  43. - 拆分成独立的、有搜索意义的词或短语
  44. 2. **保留核心维度**:
  45. - 地域/对象
  46. - 时间
  47. - 行为/意图:获取、教程、推荐、如何等
  48. - 主题/领域
  49. - 质量/属性
  50. 3. **去掉无意义的虚词**:的、吗、呢等
  51. 4. **保留领域专有词**:不要过度拆分专业术语
  52. - 如果是常见的组合词,保持完整
  53. ## 输出要求
  54. 输出关键词列表,按重要性排序(最核心的在前)。
  55. """.strip()
  56. class KeywordList(BaseModel):
  57. """关键词列表"""
  58. keywords: list[str] = Field(..., description="提取的关键词,按重要性排序")
  59. reasoning: str = Field(..., description="提取理由")
  60. keyword_extractor = Agent[None](
  61. name="关键词提取专家",
  62. instructions=keyword_extraction_instructions,
  63. model=get_model(MODEL_NAME),
  64. output_type=KeywordList,
  65. )
  66. # ============================================================================
  67. # Agent 2: 层级探索分析专家
  68. # ============================================================================
  69. level_analysis_instructions = """
  70. 你是搜索空间探索分析专家。基于当前层级的探索结果,决定下一步行动。
  71. ## 你的任务
  72. 分析当前已探索的词汇空间,判断:
  73. 1. **发现了什么有价值的信号?**
  74. 2. **是否已经可以评估候选了?**
  75. 3. **如果还不够,下一层应该探索什么组合?**
  76. ## 分析维度
  77. ### 1. 信号识别(最重要)
  78. 看推荐词里**出现了什么主题**:
  79. **关键问题:**
  80. - 哪些推荐词**最接近原始需求**?
  81. - 哪些推荐词**揭示了有价值的方向**(即使不完全匹配)?
  82. - 哪些推荐词可以作为**下一层探索的桥梁**?
  83. - 系统对哪些概念理解得好?哪些理解偏了?
  84. ### 2. 组合策略
  85. 基于发现的信号,设计下一层探索:
  86. **组合类型:**
  87. a) **关键词直接组合**
  88. - 两个关键词组合成新query
  89. b) **利用推荐词作为桥梁**(重要!)
  90. - 发现某个推荐词很有价值 → 直接探索这个推荐词
  91. - 或在推荐词基础上加其他关键词
  92. c) **跨层级组合**
  93. - 结合多层发现的有价值推荐词
  94. - 组合成更复杂的query
  95. ### 3. 停止条件
  96. **何时可以评估候选?**
  97. 满足以下之一:
  98. - 推荐词中出现了**明确包含原始需求多个核心要素的query**
  99. - 已经探索到**足够复杂的组合**(3-4个关键词),且推荐词相关
  100. - 探索了**3-4层**,信息已经足够丰富
  101. **何时继续探索?**
  102. - 当前推荐词太泛,没有接近原始需求
  103. - 发现了有价值的信号,但需要进一步组合验证
  104. - 层数还少(< 3层)
  105. ## 输出要求
  106. ### 1. key_findings
  107. 总结当前层发现的关键信息,包括:
  108. - 哪些推荐词最有价值?
  109. - 系统对哪些概念理解得好/不好?
  110. - 发现了什么意外的方向?
  111. ### 2. promising_signals
  112. 列出最有价值的推荐词(来自任何已探索的query),每个说明为什么有价值
  113. ### 3. should_evaluate_now
  114. 是否已经可以开始评估候选了?true/false
  115. ### 4. candidates_to_evaluate
  116. 如果should_evaluate_now=true,列出应该评估的候选query
  117. - 可以是推荐词
  118. - 可以是自己构造的组合
  119. ### 5. next_combinations
  120. 如果should_evaluate_now=false,列出下一层应该探索的query组合
  121. ### 6. reasoning
  122. 详细的推理过程
  123. ## 重要原则
  124. 1. **不要过早评估**:至少探索2层,除非第一层就发现了完美匹配
  125. 2. **充分利用推荐词**:推荐词是系统给的提示,要善用
  126. 3. **保持探索方向的多样性**:不要只盯着一个方向
  127. 4. **识别死胡同**:如果某个方向的推荐词一直不相关,果断放弃
  128. """.strip()
  129. class PromisingSignal(BaseModel):
  130. """有价值的推荐词信号"""
  131. query: str = Field(..., description="推荐词")
  132. from_level: int = Field(..., description="来自哪一层")
  133. reason: str = Field(..., description="为什么有价值")
  134. class LevelAnalysis(BaseModel):
  135. """层级分析结果"""
  136. key_findings: str = Field(..., description="当前层的关键发现")
  137. promising_signals: list[PromisingSignal] = Field(..., description="有价值的推荐词信号")
  138. should_evaluate_now: bool = Field(..., description="是否应该开始评估候选")
  139. candidates_to_evaluate: list[str] = Field(default_factory=list, description="如果should_evaluate_now=true,要评估的候选query列表")
  140. next_combinations: list[str] = Field(default_factory=list, description="如果should_evaluate_now=false,下一层要探索的query组合")
  141. reasoning: str = Field(..., description="详细的推理过程")
  142. level_analyzer = Agent[None](
  143. name="层级探索分析专家",
  144. instructions=level_analysis_instructions,
  145. model=get_model(MODEL_NAME),
  146. output_type=LevelAnalysis,
  147. )
  148. # ============================================================================
  149. # Agent 3: 评估专家(简化版:意图匹配 + 相关性评分)
  150. # ============================================================================
  151. eval_instructions = """
  152. 你是搜索query评估专家。给定原始问题和推荐query,评估两个维度。
  153. ## 评估目标
  154. 用这个推荐query搜索,能否找到满足原始需求的内容?
  155. ## 两层评分
  156. ### 1. intent_match(意图匹配)= true/false
  157. 推荐query的**使用意图**是否与原问题一致?
  158. **核心问题:用户搜索这个推荐词,想做什么?**
  159. **判断标准:**
  160. - 原问题意图:找方法?找教程?找资源/素材?找工具?看作品?
  161. - 推荐词意图:如果用户搜索这个词,他的目的是什么?
  162. **示例:**
  163. - 原问题意图="找素材"
  164. - ✅ true: "素材下载"、"素材网站"、"免费素材"(都是获取素材)
  165. - ❌ false: "素材制作教程"、"如何制作素材"(意图变成学习了)
  166. - 原问题意图="学教程"
  167. - ✅ true: "教程视频"、"教学步骤"、"入门指南"
  168. - ❌ false: "成品展示"、"作品欣赏"(意图变成看作品了)
  169. **评分:**
  170. - true = 意图一致,搜索推荐词能达到原问题的目的
  171. - false = 意图改变,搜索推荐词无法达到原问题的目的
  172. ### 2. relevance_score(相关性)= 0-1 连续分数
  173. 推荐query在**主题、要素、属性**上与原问题的相关程度?
  174. **评估维度:**
  175. - 主题相关:核心主题是否匹配?(如:摄影、旅游、美食)
  176. - 要素覆盖:关键要素保留了多少?(如:地域、时间、对象、工具)
  177. - 属性匹配:质量、风格、特色等属性是否保留?
  178. **评分参考:**
  179. - 0.9-1.0 = 几乎完美匹配,所有核心要素都保留
  180. - 0.7-0.8 = 高度相关,核心要素保留,少数次要要素缺失
  181. - 0.5-0.6 = 中度相关,主题匹配但多个要素缺失
  182. - 0.3-0.4 = 低度相关,只有部分主题相关
  183. - 0-0.2 = 基本不相关
  184. ## 评估策略
  185. 1. **先判断 intent_match**:意图不匹配直接 false,无论相关性多高
  186. 2. **再评估 relevance_score**:在意图匹配的前提下,计算相关性
  187. ## 输出要求
  188. - intent_match: true/false
  189. - relevance_score: 0-1 的浮点数
  190. - reason: 详细的评估理由,需要说明:
  191. - 原问题的意图是什么
  192. - 推荐词的意图是什么
  193. - 为什么判断意图匹配/不匹配
  194. - 相关性分数的依据(哪些要素保留/缺失)
  195. """.strip()
  196. class RelevanceEvaluation(BaseModel):
  197. """评估反馈模型 - 意图匹配 + 相关性"""
  198. intent_match: bool = Field(..., description="意图是否匹配")
  199. relevance_score: float = Field(..., description="相关性分数 0-1,分数越高越相关")
  200. reason: str = Field(..., description="评估理由,需说明意图判断和相关性依据")
  201. evaluator = Agent[None](
  202. name="评估专家",
  203. instructions=eval_instructions,
  204. model=get_model(MODEL_NAME),
  205. output_type=RelevanceEvaluation,
  206. )
  207. # ============================================================================
  208. # Agent 4: 单个帖子需求满足度评估专家
  209. # ============================================================================
  210. note_evaluation_instructions = """
  211. 你是帖子需求满足度评估专家。给定原始问题和一个搜索到的帖子(标题+描述),判断这个帖子能否满足用户的需求。
  212. ## 你的任务
  213. 评估单个帖子的标题和描述,判断用户点开这个帖子后,能否找到满足原始需求的内容。
  214. ## 评估维度
  215. ### 1. 标题相关性(title_relevance)= 0-1 连续分数
  216. **评估标准:**
  217. - 标题是否与原始问题的主题相关?
  218. - 标题是否包含原始问题的关键要素?
  219. - 标题是否表明内容能解决用户的问题?
  220. **评分参考:**
  221. - 0.9-1.0 = 标题高度相关,明确表明能解决问题
  222. - 0.7-0.8 = 标题相关,包含核心要素
  223. - 0.5-0.6 = 标题部分相关,有关联但不明确
  224. - 0.3-0.4 = 标题相关性较低
  225. - 0-0.2 = 标题基本不相关
  226. ### 2. 内容预期(content_expectation)= 0-1 连续分数
  227. **评估标准:**
  228. - 从描述看,内容是否可能包含用户需要的信息?
  229. - 描述是否展示了相关的要素或细节?
  230. - 描述的方向是否与用户需求一致?
  231. **评分参考:**
  232. - 0.9-1.0 = 描述明确表明内容高度符合需求
  233. - 0.7-0.8 = 描述显示内容可能符合需求
  234. - 0.5-0.6 = 描述有一定相关性,但不确定
  235. - 0.3-0.4 = 描述相关性较低
  236. - 0-0.2 = 描述基本不相关
  237. ### 3. 需求满足度(need_satisfaction)= true/false
  238. **核心问题:用户点开这个帖子后,能否找到他需要的内容?**
  239. **判断标准:**
  240. - 综合标题和描述,内容是否大概率能满足需求?
  241. - 如果 title_relevance >= 0.7 且 content_expectation >= 0.6,一般判断为 true
  242. - 否则判断为 false
  243. ### 4. 综合置信度(confidence_score)= 0-1 连续分数
  244. **计算方式:**
  245. - 可以是 title_relevance 和 content_expectation 的加权平均
  246. - 标题权重通常更高(如 0.6 * title + 0.4 * content)
  247. ## 输出要求
  248. - title_relevance: 0-1 的浮点数
  249. - content_expectation: 0-1 的浮点数
  250. - need_satisfaction: true/false
  251. - confidence_score: 0-1 的浮点数
  252. - reason: 详细的评估理由,需要说明:
  253. - 标题与原问题的相关性分析
  254. - 描述的内容预期分析
  255. - 为什么判断能/不能满足需求
  256. - 置信度分数的依据
  257. ## 重要原则
  258. 1. **独立评估**:只评估这一个帖子,不考虑其他帖子
  259. 2. **用户视角**:问"我会点开这个帖子吗?点开后能找到答案吗?"
  260. 3. **标题优先**:标题是用户决定是否点击的关键
  261. 4. **保守判断**:不确定时,倾向于给较低的分数
  262. """.strip()
  263. class NoteEvaluation(BaseModel):
  264. """单个帖子评估模型"""
  265. title_relevance: float = Field(..., description="标题相关性 0-1")
  266. content_expectation: float = Field(..., description="内容预期 0-1")
  267. need_satisfaction: bool = Field(..., description="是否满足需求")
  268. confidence_score: float = Field(..., description="综合置信度 0-1")
  269. reason: str = Field(..., description="详细的评估理由")
  270. note_evaluator = Agent[None](
  271. name="帖子需求满足度评估专家",
  272. instructions=note_evaluation_instructions,
  273. model=get_model(MODEL_NAME),
  274. output_type=NoteEvaluation,
  275. )
  276. # ============================================================================
  277. # Agent 5: 答案生成专家
  278. # ============================================================================
  279. answer_generation_instructions = """
  280. 你是答案生成专家。基于一组满足需求的帖子,为原始问题生成一个全面、准确、有价值的答案。
  281. ## 你的任务
  282. 根据用户的原始问题和一组相关帖子(包含标题、描述、置信度评分),生成一个高质量的答案。
  283. ## 输入信息
  284. 1. **原始问题**:用户提出的具体问题
  285. 2. **相关帖子列表**:每个帖子包含
  286. - 序号(索引)
  287. - 标题
  288. - 描述
  289. - 置信度分数
  290. ## 答案要求
  291. ### 1. 内容要求
  292. - **直接回答问题**:开门见山,第一段就给出核心答案
  293. - **结构清晰**:使用标题、列表、分段等组织内容
  294. - **综合多个来源**:整合多个帖子的信息,不要只依赖一个
  295. - **信息准确**:基于帖子内容,不要编造信息
  296. - **实用性**:提供可操作的建议或具体的信息
  297. ### 2. 引用规范
  298. - **必须标注来源**:每个关键信息都要标注帖子索引
  299. - **引用格式**:使用 `[1]`、`[2]` 等标注帖子序号
  300. - **多来源引用**:如果多个帖子支持同一观点,使用 `[1,2,3]`
  301. - **引用位置**:在相关句子或段落的末尾标注
  302. ### 3. 置信度使用
  303. - **优先高置信度**:优先引用置信度高的帖子
  304. - **交叉验证**:如果多个帖子提到相同信息,可以提高可信度
  305. - **标注不确定性**:如果信息来自低置信度帖子,适当标注
  306. ### 4. 答案结构建议
  307. ```
  308. 【核心答案】
  309. 直接回答用户的问题,给出最核心的信息。[引用]
  310. 【详细说明】
  311. 1. 第一个方面/要点 [引用]
  312. - 具体内容
  313. - 相关细节
  314. 2. 第二个方面/要点 [引用]
  315. - 具体内容
  316. - 相关细节
  317. 【补充建议/注意事项】(可选)
  318. 其他有价值的信息或提醒。[引用]
  319. 【参考帖子】
  320. 列出所有引用的帖子编号和标题。
  321. ```
  322. ## 输出格式
  323. {
  324. "answer": "生成的答案内容(Markdown格式)",
  325. "cited_note_indices": [1, 2, 3], # 引用的帖子序号列表
  326. "confidence": 0.85, # 答案的整体置信度 (0-1)
  327. "summary": "一句话总结答案的核心内容"
  328. }
  329. ## 重要原则
  330. 1. **忠于原文**:不要添加帖子中没有的信息
  331. 2. **引用透明**:让用户知道每个信息来自哪个帖子
  332. 3. **综合性**:尽可能整合多个帖子的信息
  333. 4. **可读性**:使用清晰的Markdown格式
  334. 5. **质量优先**:如果帖子质量不够,可以说明信息有限
  335. """.strip()
  336. class AnswerGeneration(BaseModel):
  337. """答案生成模型"""
  338. answer: str = Field(..., description="生成的答案内容(Markdown格式)")
  339. cited_note_indices: list[int] = Field(..., description="引用的帖子序号列表")
  340. confidence: float = Field(..., description="答案的整体置信度 0-1")
  341. summary: str = Field(..., description="一句话总结答案的核心内容")
  342. answer_generator = Agent[None](
  343. name="答案生成专家",
  344. instructions=answer_generation_instructions,
  345. model=get_model(MODEL_NAME),
  346. output_type=AnswerGeneration,
  347. )
  348. # ============================================================================
  349. # 日志辅助函数
  350. # ============================================================================
  351. def add_step(context: RunContext, step_name: str, step_type: str, data: dict):
  352. """添加步骤记录"""
  353. step = {
  354. "step_number": len(context.steps) + 1,
  355. "step_name": step_name,
  356. "step_type": step_type,
  357. "timestamp": datetime.now().isoformat(),
  358. "data": data
  359. }
  360. context.steps.append(step)
  361. return step
  362. # ============================================================================
  363. # 核心函数
  364. # ============================================================================
  365. async def extract_keywords(q: str, context: RunContext) -> KeywordList:
  366. """提取关键词"""
  367. print("\n[步骤 1] 正在提取关键词...")
  368. result = await Runner.run(keyword_extractor, q)
  369. keyword_list: KeywordList = result.final_output
  370. print(f"提取的关键词:{keyword_list.keywords}")
  371. print(f"提取理由:{keyword_list.reasoning}")
  372. # 记录步骤
  373. add_step(context, "提取关键词", "keyword_extraction", {
  374. "input_question": q,
  375. "keywords": keyword_list.keywords,
  376. "reasoning": keyword_list.reasoning
  377. })
  378. return keyword_list
  379. async def explore_level(queries: list[str], level_num: int, context: RunContext) -> dict:
  380. """探索一个层级(并发获取所有query的推荐词)"""
  381. step_num = len(context.steps) + 1
  382. print(f"\n{'='*60}")
  383. print(f"[步骤 {step_num}] Level {level_num} 探索:{len(queries)} 个query")
  384. print(f"{'='*60}")
  385. xiaohongshu_api = XiaohongshuSearchRecommendations()
  386. # 并发获取所有推荐词
  387. async def get_single_sug(query: str):
  388. print(f" 探索: {query}")
  389. suggestions = xiaohongshu_api.get_recommendations(keyword=query)
  390. print(f" → {len(suggestions) if suggestions else 0} 个推荐词")
  391. return {
  392. "query": query,
  393. "suggestions": suggestions or []
  394. }
  395. results = await asyncio.gather(*[get_single_sug(q) for q in queries])
  396. level_data = {
  397. "level": level_num,
  398. "timestamp": datetime.now().isoformat(),
  399. "queries": results
  400. }
  401. context.exploration_levels.append(level_data)
  402. # 记录步骤
  403. add_step(context, f"Level {level_num} 探索", "level_exploration", {
  404. "level": level_num,
  405. "input_queries": queries,
  406. "query_count": len(queries),
  407. "results": results,
  408. "total_suggestions": sum(len(r['suggestions']) for r in results)
  409. })
  410. return level_data
  411. async def analyze_level(level_data: dict, all_levels: list[dict], original_question: str, context: RunContext) -> LevelAnalysis:
  412. """分析当前层级,决定下一步"""
  413. step_num = len(context.steps) + 1
  414. print(f"\n[步骤 {step_num}] 正在分析 Level {level_data['level']}...")
  415. # 构造输入
  416. analysis_input = f"""
  417. <原始问题>
  418. {original_question}
  419. </原始问题>
  420. <已探索的所有层级>
  421. {json.dumps(all_levels, ensure_ascii=False, indent=2)}
  422. </已探索的所有层级>
  423. <当前层级>
  424. Level {level_data['level']}
  425. {json.dumps(level_data['queries'], ensure_ascii=False, indent=2)}
  426. </当前层级>
  427. 请分析当前探索状态,决定下一步行动。
  428. """
  429. result = await Runner.run(level_analyzer, analysis_input)
  430. analysis: LevelAnalysis = result.final_output
  431. print(f"\n分析结果:")
  432. print(f" 关键发现:{analysis.key_findings}")
  433. print(f" 有价值的信号:{len(analysis.promising_signals)} 个")
  434. print(f" 是否评估:{analysis.should_evaluate_now}")
  435. if analysis.should_evaluate_now:
  436. print(f" 候选query:{analysis.candidates_to_evaluate}")
  437. else:
  438. print(f" 下一层探索:{analysis.next_combinations}")
  439. # 保存分析结果
  440. context.level_analyses.append({
  441. "level": level_data['level'],
  442. "timestamp": datetime.now().isoformat(),
  443. "analysis": analysis.model_dump()
  444. })
  445. # 记录步骤
  446. add_step(context, f"Level {level_data['level']} 分析", "level_analysis", {
  447. "level": level_data['level'],
  448. "key_findings": analysis.key_findings,
  449. "promising_signals_count": len(analysis.promising_signals),
  450. "promising_signals": [s.model_dump() for s in analysis.promising_signals],
  451. "should_evaluate_now": analysis.should_evaluate_now,
  452. "candidates_to_evaluate": analysis.candidates_to_evaluate if analysis.should_evaluate_now else [],
  453. "next_combinations": analysis.next_combinations if not analysis.should_evaluate_now else [],
  454. "reasoning": analysis.reasoning
  455. })
  456. return analysis
  457. async def evaluate_candidates(candidates: list[str], original_question: str, context: RunContext) -> list[dict]:
  458. """评估候选query(含实际搜索验证)"""
  459. step_num = len(context.steps) + 1
  460. print(f"\n{'='*60}")
  461. print(f"[步骤 {step_num}] 评估 {len(candidates)} 个候选query")
  462. print(f"{'='*60}")
  463. xiaohongshu_api = XiaohongshuSearchRecommendations()
  464. xiaohongshu_search = XiaohongshuSearch()
  465. # 创建搜索结果保存目录
  466. search_results_dir = os.path.join(context.log_dir, "search_results")
  467. os.makedirs(search_results_dir, exist_ok=True)
  468. async def evaluate_single_candidate(candidate: str, candidate_index: int):
  469. print(f"\n评估候选:{candidate}")
  470. # 为当前候选创建子目录
  471. # 清理候选名称,移除不适合作为目录名的字符
  472. safe_candidate_name = "".join(c if c.isalnum() or c in (' ', '_', '-') else '_' for c in candidate)
  473. candidate_dir = os.path.join(search_results_dir, f"candidate_{candidate_index+1}_{safe_candidate_name[:50]}")
  474. os.makedirs(candidate_dir, exist_ok=True)
  475. # 1. 获取推荐词
  476. suggestions = xiaohongshu_api.get_recommendations(keyword=candidate)
  477. print(f" 获取到 {len(suggestions) if suggestions else 0} 个推荐词")
  478. if not suggestions:
  479. return {
  480. "candidate": candidate,
  481. "suggestions": [],
  482. "evaluations": []
  483. }
  484. # 2. 评估每个推荐词(意图匹配 + 相关性)
  485. async def eval_single_sug(sug: str, sug_index: int):
  486. # 2.1 先进行意图和相关性评估
  487. eval_input = f"""
  488. <原始问题>
  489. {original_question}
  490. </原始问题>
  491. <待评估的推荐query>
  492. {sug}
  493. </待评估的推荐query>
  494. 请评估该推荐query:
  495. 1. intent_match: 意图是否匹配(true/false)
  496. 2. relevance_score: 相关性分数(0-1)
  497. 3. reason: 详细的评估理由
  498. """
  499. result = await Runner.run(evaluator, eval_input)
  500. evaluation: RelevanceEvaluation = result.final_output
  501. eval_result = {
  502. "query": sug,
  503. "intent_match": evaluation.intent_match,
  504. "relevance_score": evaluation.relevance_score,
  505. "reason": evaluation.reason,
  506. }
  507. # 2.2 如果意图匹配且相关性足够高,进行实际搜索验证
  508. if evaluation.intent_match and evaluation.relevance_score >= 0.7:
  509. print(f" → 合格候选,进行实际搜索验证: {sug}")
  510. try:
  511. search_result = xiaohongshu_search.search(keyword=sug)
  512. # 解析result字段(它是JSON字符串,需要先解析)
  513. result_str = search_result.get("result", "{}")
  514. if isinstance(result_str, str):
  515. result_data = json.loads(result_str)
  516. else:
  517. result_data = result_str
  518. # 格式化搜索结果:将result字段解析后再保存
  519. formatted_search_result = {
  520. "success": search_result.get("success"),
  521. "result": result_data, # 保存解析后的数据
  522. "tool_name": search_result.get("tool_name"),
  523. "call_type": search_result.get("call_type"),
  524. "query": sug,
  525. "timestamp": datetime.now().isoformat()
  526. }
  527. # 保存格式化后的搜索结果到文件
  528. safe_sug_name = "".join(c if c.isalnum() or c in (' ', '_', '-') else '_' for c in sug)
  529. search_result_file = os.path.join(candidate_dir, f"sug_{sug_index+1}_{safe_sug_name[:30]}.json")
  530. with open(search_result_file, 'w', encoding='utf-8') as f:
  531. json.dump(formatted_search_result, f, ensure_ascii=False, indent=2)
  532. print(f" 搜索结果已保存: {os.path.basename(search_result_file)}")
  533. # 提取搜索结果的标题和描述
  534. # 正确的数据路径: result.data.data[]
  535. notes = result_data.get("data", {}).get("data", [])
  536. if notes:
  537. print(f" 开始评估 {len(notes)} 个帖子...")
  538. # 对每个帖子进行独立评估
  539. note_evaluations = []
  540. for note_idx, note in enumerate(notes[:10], 1): # 只评估前10条
  541. note_card = note.get("note_card", {})
  542. title = note_card.get("display_title", "")
  543. desc = note_card.get("desc", "")
  544. note_id = note.get("id", "")
  545. # 构造评估输入
  546. eval_input = f"""
  547. <原始问题>
  548. {original_question}
  549. </原始问题>
  550. <帖子信息>
  551. 标题: {title}
  552. 描述: {desc}
  553. </帖子信息>
  554. 请评估这个帖子能否满足用户需求。
  555. """
  556. # 调用评估Agent
  557. eval_result_run = await Runner.run(note_evaluator, eval_input)
  558. note_eval: NoteEvaluation = eval_result_run.final_output
  559. note_evaluation_record = {
  560. "note_index": note_idx,
  561. "note_id": note_id,
  562. "title": title,
  563. "desc": desc[:200], # 只保存前200字
  564. "evaluation": {
  565. "title_relevance": note_eval.title_relevance,
  566. "content_expectation": note_eval.content_expectation,
  567. "need_satisfaction": note_eval.need_satisfaction,
  568. "confidence_score": note_eval.confidence_score,
  569. "reason": note_eval.reason
  570. }
  571. }
  572. note_evaluations.append(note_evaluation_record)
  573. # 简单打印进度
  574. if note_idx % 3 == 0 or note_idx == len(notes[:10]):
  575. print(f" 已评估 {note_idx}/{len(notes[:10])} 个帖子")
  576. # 统计满足需求的帖子数量
  577. satisfied_count = sum(1 for ne in note_evaluations if ne["evaluation"]["need_satisfaction"])
  578. avg_confidence = sum(ne["evaluation"]["confidence_score"] for ne in note_evaluations) / len(note_evaluations) if note_evaluations else 0
  579. eval_result["search_verification"] = {
  580. "total_notes": len(notes),
  581. "evaluated_notes": len(note_evaluations),
  582. "satisfied_count": satisfied_count,
  583. "average_confidence": round(avg_confidence, 2),
  584. "note_evaluations": note_evaluations,
  585. "search_result_file": search_result_file
  586. }
  587. print(f" 评估完成: {satisfied_count}/{len(note_evaluations)} 个帖子满足需求, "
  588. f"平均置信度={avg_confidence:.2f}")
  589. else:
  590. eval_result["search_verification"] = {
  591. "total_notes": 0,
  592. "evaluated_notes": 0,
  593. "satisfied_count": 0,
  594. "average_confidence": 0.0,
  595. "note_evaluations": [],
  596. "search_result_file": search_result_file,
  597. "reason": "搜索无结果"
  598. }
  599. print(f" 搜索无结果")
  600. except Exception as e:
  601. print(f" 搜索验证出错: {e}")
  602. eval_result["search_verification"] = {
  603. "error": str(e)
  604. }
  605. return eval_result
  606. evaluations = await asyncio.gather(*[eval_single_sug(s, i) for i, s in enumerate(suggestions)])
  607. return {
  608. "candidate": candidate,
  609. "suggestions": suggestions,
  610. "evaluations": evaluations
  611. }
  612. results = await asyncio.gather(*[evaluate_single_candidate(c, i) for i, c in enumerate(candidates)])
  613. # 生成搜索结果汇总文件
  614. summary_data = {
  615. "original_question": original_question,
  616. "timestamp": datetime.now().isoformat(),
  617. "total_candidates": len(candidates),
  618. "candidates": []
  619. }
  620. for i, result in enumerate(results):
  621. candidate_summary = {
  622. "index": i + 1,
  623. "candidate": result["candidate"],
  624. "suggestions_count": len(result["suggestions"]),
  625. "verified_queries": []
  626. }
  627. for eval_item in result.get("evaluations", []):
  628. if "search_verification" in eval_item and "search_result_file" in eval_item["search_verification"]:
  629. sv = eval_item["search_verification"]
  630. candidate_summary["verified_queries"].append({
  631. "query": eval_item["query"],
  632. "intent_match": eval_item["intent_match"],
  633. "relevance_score": eval_item["relevance_score"],
  634. "verification": {
  635. "total_notes": sv.get("total_notes", 0),
  636. "evaluated_notes": sv.get("evaluated_notes", 0),
  637. "satisfied_count": sv.get("satisfied_count", 0),
  638. "average_confidence": sv.get("average_confidence", 0.0)
  639. },
  640. "search_result_file": sv["search_result_file"]
  641. })
  642. summary_data["candidates"].append(candidate_summary)
  643. # 保存汇总文件
  644. summary_file = os.path.join(search_results_dir, "summary.json")
  645. with open(summary_file, 'w', encoding='utf-8') as f:
  646. json.dump(summary_data, f, ensure_ascii=False, indent=2)
  647. print(f"\n搜索结果汇总已保存: {summary_file}")
  648. context.evaluation_results = results
  649. # 构建详细的步骤记录数据
  650. step_data = {
  651. "candidate_count": len(candidates),
  652. "candidates": candidates,
  653. "total_evaluations": sum(len(r['evaluations']) for r in results),
  654. "verified_queries": sum(
  655. 1 for r in results
  656. for e in r.get('evaluations', [])
  657. if 'search_verification' in e
  658. ),
  659. "search_results_dir": search_results_dir,
  660. "summary_file": summary_file,
  661. "detailed_results": []
  662. }
  663. # 为每个候选记录详细信息
  664. for result in results:
  665. candidate_detail = {
  666. "candidate": result["candidate"],
  667. "suggestions": result["suggestions"],
  668. "evaluations": []
  669. }
  670. for eval_item in result.get("evaluations", []):
  671. eval_detail = {
  672. "query": eval_item["query"],
  673. "intent_match": eval_item["intent_match"],
  674. "relevance_score": eval_item["relevance_score"],
  675. "reason": eval_item["reason"]
  676. }
  677. # 如果有搜索验证,添加详细信息
  678. if "search_verification" in eval_item:
  679. verification = eval_item["search_verification"]
  680. eval_detail["search_verification"] = {
  681. "performed": True,
  682. "total_notes": verification.get("total_notes", 0),
  683. "evaluated_notes": verification.get("evaluated_notes", 0),
  684. "satisfied_count": verification.get("satisfied_count", 0),
  685. "average_confidence": verification.get("average_confidence", 0.0),
  686. "search_result_file": verification.get("search_result_file"),
  687. "has_error": "error" in verification
  688. }
  689. if "error" in verification:
  690. eval_detail["search_verification"]["error"] = verification["error"]
  691. # 保存每个帖子的评估详情
  692. if "note_evaluations" in verification:
  693. eval_detail["search_verification"]["note_evaluations"] = verification["note_evaluations"]
  694. else:
  695. eval_detail["search_verification"] = {
  696. "performed": False,
  697. "reason": "未达到搜索验证阈值(intent_match=False 或 relevance_score<0.7)"
  698. }
  699. candidate_detail["evaluations"].append(eval_detail)
  700. step_data["detailed_results"].append(candidate_detail)
  701. # 记录步骤
  702. add_step(context, "评估候选query", "candidate_evaluation", step_data)
  703. return results
  704. # ============================================================================
  705. # 新的独立步骤函数(方案A)
  706. # ============================================================================
  707. async def step_evaluate_query_suggestions(candidates: list[str], original_question: str, context: RunContext) -> list[dict]:
  708. """
  709. 步骤1: 评估候选query的推荐词
  710. 输入:
  711. - candidates: 候选query列表
  712. - original_question: 原始问题
  713. - context: 运行上下文
  714. 输出:
  715. - 每个候选的评估结果列表,包含:
  716. - candidate: 候选query
  717. - suggestions: 推荐词列表
  718. - evaluations: 每个推荐词的意图匹配和相关性评分
  719. """
  720. step_num = len(context.steps) + 1
  721. print(f"\n{'='*60}")
  722. print(f"[步骤 {step_num}] 评估 {len(candidates)} 个候选query的推荐词")
  723. print(f"{'='*60}")
  724. xiaohongshu_api = XiaohongshuSearchRecommendations()
  725. async def evaluate_single_candidate(candidate: str):
  726. print(f"\n评估候选:{candidate}")
  727. # 1. 获取推荐词
  728. suggestions = xiaohongshu_api.get_recommendations(keyword=candidate)
  729. print(f" 获取到 {len(suggestions) if suggestions else 0} 个推荐词")
  730. if not suggestions:
  731. return {
  732. "candidate": candidate,
  733. "suggestions": [],
  734. "evaluations": []
  735. }
  736. # 2. 评估每个推荐词(只做意图匹配和相关性评分)
  737. async def eval_single_sug(sug: str):
  738. eval_input = f"""
  739. <原始问题>
  740. {original_question}
  741. </原始问题>
  742. <待评估的推荐query>
  743. {sug}
  744. </待评估的推荐query>
  745. 请评估该推荐query:
  746. 1. intent_match: 意图是否匹配(true/false)
  747. 2. relevance_score: 相关性分数(0-1)
  748. 3. reason: 详细的评估理由
  749. """
  750. result = await Runner.run(evaluator, eval_input)
  751. evaluation: RelevanceEvaluation = result.final_output
  752. return {
  753. "query": sug,
  754. "intent_match": evaluation.intent_match,
  755. "relevance_score": evaluation.relevance_score,
  756. "reason": evaluation.reason
  757. }
  758. evaluations = await asyncio.gather(*[eval_single_sug(s) for s in suggestions])
  759. return {
  760. "candidate": candidate,
  761. "suggestions": suggestions,
  762. "evaluations": evaluations
  763. }
  764. results = await asyncio.gather(*[evaluate_single_candidate(c) for c in candidates])
  765. # 记录步骤
  766. add_step(context, "评估候选query的推荐词", "query_suggestion_evaluation", {
  767. "candidate_count": len(candidates),
  768. "candidates": candidates,
  769. "results": results,
  770. "total_evaluations": sum(len(r['evaluations']) for r in results),
  771. "qualified_count": sum(
  772. 1 for r in results
  773. for e in r['evaluations']
  774. if e['intent_match'] and e['relevance_score'] >= 0.7
  775. )
  776. })
  777. return results
  778. def step_filter_qualified_queries(evaluation_results: list[dict], context: RunContext, min_relevance_score: float = 0.7) -> list[dict]:
  779. """
  780. 步骤1.5: 筛选合格的推荐词
  781. 输入:
  782. - evaluation_results: 步骤1的评估结果
  783. 输出:
  784. - 合格的query列表,每个包含:
  785. - query: 推荐词
  786. - from_candidate: 来源候选
  787. - intent_match: 意图匹配
  788. - relevance_score: 相关性分数
  789. - reason: 评估理由
  790. """
  791. step_num = len(context.steps) + 1
  792. print(f"\n{'='*60}")
  793. print(f"[步骤 {step_num}] 筛选合格的推荐词")
  794. print(f"{'='*60}")
  795. qualified_queries = []
  796. all_queries = [] # 保存所有查询,包括不合格的
  797. for result in evaluation_results:
  798. candidate = result["candidate"]
  799. for eval_item in result.get("evaluations", []):
  800. query_data = {
  801. "query": eval_item["query"],
  802. "from_candidate": candidate,
  803. "intent_match": eval_item["intent_match"],
  804. "relevance_score": eval_item["relevance_score"],
  805. "reason": eval_item["reason"]
  806. }
  807. # 判断是否合格
  808. is_qualified = (eval_item['intent_match'] is True
  809. and eval_item['relevance_score'] >= min_relevance_score)
  810. query_data["is_qualified"] = is_qualified
  811. all_queries.append(query_data)
  812. if is_qualified:
  813. qualified_queries.append(query_data)
  814. # 按相关性分数降序排列
  815. qualified_queries.sort(key=lambda x: x['relevance_score'], reverse=True)
  816. all_queries.sort(key=lambda x: x['relevance_score'], reverse=True)
  817. print(f"\n找到 {len(qualified_queries)} 个合格的推荐词 (共评估 {len(all_queries)} 个)")
  818. if qualified_queries:
  819. print(f"相关性分数范围: {qualified_queries[0]['relevance_score']:.2f} ~ {qualified_queries[-1]['relevance_score']:.2f}")
  820. print("\n合格的推荐词:")
  821. for idx, q in enumerate(qualified_queries[:5], 1):
  822. print(f" {idx}. {q['query']} (分数: {q['relevance_score']:.2f})")
  823. if len(qualified_queries) > 5:
  824. print(f" ... 还有 {len(qualified_queries) - 5} 个")
  825. # 记录步骤 - 保存所有查询数据
  826. add_step(context, "筛选合格的推荐词", "filter_qualified_queries", {
  827. "input_evaluation_count": len(all_queries),
  828. "min_relevance_score": min_relevance_score,
  829. "qualified_count": len(qualified_queries),
  830. "qualified_queries": qualified_queries,
  831. "all_queries": all_queries # 新增:保存所有查询数据
  832. })
  833. return qualified_queries
  834. async def step_search_qualified_queries(qualified_queries: list[dict], context: RunContext) -> dict:
  835. """
  836. 步骤2: 搜索合格的推荐词
  837. 输入:
  838. - qualified_queries: 步骤1.5筛选出的合格query列表,每个包含:
  839. - query: 推荐词
  840. - from_candidate: 来源候选
  841. - intent_match, relevance_score, reason
  842. 输出:
  843. - 搜索结果字典,包含:
  844. - searches: 每个query的搜索结果列表
  845. - search_results_dir: 搜索结果保存目录
  846. """
  847. step_num = len(context.steps) + 1
  848. print(f"\n{'='*60}")
  849. print(f"[步骤 {step_num}] 搜索 {len(qualified_queries)} 个合格的推荐词")
  850. print(f"{'='*60}")
  851. if not qualified_queries:
  852. add_step(context, "搜索合格的推荐词", "search_qualified_queries", {
  853. "qualified_count": 0,
  854. "searches": []
  855. })
  856. return {"searches": [], "search_results_dir": None}
  857. # 创建搜索结果保存目录
  858. search_results_dir = os.path.join(context.log_dir, "search_results")
  859. os.makedirs(search_results_dir, exist_ok=True)
  860. xiaohongshu_search = XiaohongshuSearch()
  861. # 搜索每个合格的query
  862. async def search_single_query(query_info: dict, query_index: int):
  863. query = query_info['query']
  864. print(f"\n搜索 [{query_index+1}/{len(qualified_queries)}]: {query}")
  865. try:
  866. # 执行搜索
  867. search_result = xiaohongshu_search.search(keyword=query)
  868. # 解析result字段
  869. result_str = search_result.get("result", "{}")
  870. if isinstance(result_str, str):
  871. result_data = json.loads(result_str)
  872. else:
  873. result_data = result_str
  874. # 格式化搜索结果
  875. formatted_search_result = {
  876. "success": search_result.get("success"),
  877. "result": result_data,
  878. "tool_name": search_result.get("tool_name"),
  879. "call_type": search_result.get("call_type"),
  880. "query": query,
  881. "timestamp": datetime.now().isoformat()
  882. }
  883. # 保存到文件
  884. safe_query_name = "".join(c if c.isalnum() or c in (' ', '_', '-') else '_' for c in query)
  885. query_dir = os.path.join(search_results_dir, f"query_{query_index+1}_{safe_query_name[:50]}")
  886. os.makedirs(query_dir, exist_ok=True)
  887. search_result_file = os.path.join(query_dir, "search_result.json")
  888. with open(search_result_file, 'w', encoding='utf-8') as f:
  889. json.dump(formatted_search_result, f, ensure_ascii=False, indent=2)
  890. # 提取帖子列表
  891. notes = result_data.get("data", {}).get("data", [])
  892. print(f" → 搜索成功,获得 {len(notes)} 个帖子")
  893. # ⭐ 提取帖子摘要信息用于steps.json
  894. notes_summary = []
  895. for note in notes[:10]: # 只保存前10个
  896. note_card = note.get("note_card", {})
  897. image_list = note_card.get("image_list", [])
  898. interact_info = note_card.get("interact_info", {})
  899. user_info = note_card.get("user", {})
  900. notes_summary.append({
  901. "note_id": note.get("id", ""),
  902. "title": note_card.get("display_title", ""),
  903. "desc": note_card.get("desc", "")[:200],
  904. "cover_image": image_list[0] if image_list else {},
  905. "interact_info": {
  906. "liked_count": interact_info.get("liked_count", 0),
  907. "collected_count": interact_info.get("collected_count", 0),
  908. "comment_count": interact_info.get("comment_count", 0),
  909. "shared_count": interact_info.get("shared_count", 0)
  910. },
  911. "user": {
  912. "nickname": user_info.get("nickname", ""),
  913. "user_id": user_info.get("user_id", "")
  914. },
  915. "type": note_card.get("type", "normal")
  916. })
  917. return {
  918. "query": query,
  919. "from_candidate": query_info['from_candidate'],
  920. "intent_match": query_info['intent_match'],
  921. "relevance_score": query_info['relevance_score'],
  922. "reason": query_info['reason'],
  923. "search_result_file": search_result_file,
  924. "note_count": len(notes),
  925. "notes": notes[:10], # 只保存前10个用于评估
  926. "notes_summary": notes_summary # ⭐ 保存到steps.json
  927. }
  928. except Exception as e:
  929. print(f" → 搜索失败: {e}")
  930. return {
  931. "query": query,
  932. "from_candidate": query_info['from_candidate'],
  933. "intent_match": query_info['intent_match'],
  934. "relevance_score": query_info['relevance_score'],
  935. "reason": query_info['reason'],
  936. "error": str(e),
  937. "note_count": 0,
  938. "notes": []
  939. }
  940. search_results = await asyncio.gather(*[search_single_query(q, i) for i, q in enumerate(qualified_queries)])
  941. # 记录步骤
  942. add_step(context, "搜索合格的推荐词", "search_qualified_queries", {
  943. "qualified_count": len(qualified_queries),
  944. "search_results": [
  945. {
  946. "query": sr['query'],
  947. "from_candidate": sr['from_candidate'],
  948. "note_count": sr['note_count'],
  949. "search_result_file": sr.get('search_result_file'),
  950. "has_error": 'error' in sr,
  951. "notes_summary": sr.get('notes_summary', []) # ⭐ 包含帖子摘要
  952. }
  953. for sr in search_results
  954. ],
  955. "search_results_dir": search_results_dir
  956. })
  957. return {
  958. "searches": search_results,
  959. "search_results_dir": search_results_dir
  960. }
  961. async def step_evaluate_search_notes(search_data: dict, original_question: str, context: RunContext) -> dict:
  962. """
  963. 步骤3: 评估搜索到的帖子
  964. 输入:
  965. - search_data: 步骤2的搜索结果,包含:
  966. - searches: 搜索结果列表
  967. - search_results_dir: 结果目录
  968. 输出:
  969. - 帖子评估结果字典,包含:
  970. - note_evaluations: 每个query的帖子评估列表
  971. """
  972. step_num = len(context.steps) + 1
  973. print(f"\n{'='*60}")
  974. print(f"[步骤 {step_num}] 评估搜索到的帖子")
  975. print(f"{'='*60}")
  976. search_results = search_data['searches']
  977. if not search_results:
  978. add_step(context, "评估搜索到的帖子", "evaluate_search_notes", {
  979. "query_count": 0,
  980. "total_notes": 0,
  981. "evaluated_notes": 0,
  982. "note_evaluations": []
  983. })
  984. return {"note_evaluations": []}
  985. # 对每个query的帖子进行评估
  986. async def evaluate_query_notes(search_result: dict, query_index: int):
  987. query = search_result['query']
  988. notes = search_result.get('notes', [])
  989. if not notes or 'error' in search_result:
  990. return {
  991. "query": query,
  992. "from_candidate": search_result['from_candidate'],
  993. "note_count": 0,
  994. "evaluated_notes": [],
  995. "satisfied_count": 0,
  996. "average_confidence": 0.0
  997. }
  998. print(f"\n评估query [{query_index+1}]: {query} ({len(notes)} 个帖子)")
  999. # 评估每个帖子
  1000. note_evaluations = []
  1001. for note_idx, note in enumerate(notes, 1):
  1002. note_card = note.get("note_card", {})
  1003. title = note_card.get("display_title", "")
  1004. desc = note_card.get("desc", "")
  1005. note_id = note.get("id", "")
  1006. # ⭐ 提取完整帖子信息用于可视化
  1007. image_list = note_card.get("image_list", [])
  1008. cover_image = image_list[0] if image_list else {}
  1009. interact_info = note_card.get("interact_info", {})
  1010. user_info = note_card.get("user", {})
  1011. # 调用评估Agent
  1012. eval_input = f"""
  1013. <原始问题>
  1014. {original_question}
  1015. </原始问题>
  1016. <帖子信息>
  1017. 标题: {title}
  1018. 描述: {desc}
  1019. </帖子信息>
  1020. 请评估这个帖子能否满足用户需求。
  1021. """
  1022. eval_result_run = await Runner.run(note_evaluator, eval_input)
  1023. note_eval: NoteEvaluation = eval_result_run.final_output
  1024. note_evaluations.append({
  1025. "note_index": note_idx,
  1026. "note_id": note_id,
  1027. "title": title,
  1028. "desc": desc[:200],
  1029. # ⭐ 新增:完整帖子信息
  1030. "image_list": image_list,
  1031. "cover_image": cover_image,
  1032. "interact_info": {
  1033. "liked_count": interact_info.get("liked_count", 0),
  1034. "collected_count": interact_info.get("collected_count", 0),
  1035. "comment_count": interact_info.get("comment_count", 0),
  1036. "shared_count": interact_info.get("shared_count", 0)
  1037. },
  1038. "user": {
  1039. "nickname": user_info.get("nickname", ""),
  1040. "user_id": user_info.get("user_id", "")
  1041. },
  1042. "type": note_card.get("type", "normal"),
  1043. "note_url": f"https://www.xiaohongshu.com/explore/{note_id}",
  1044. "evaluation": {
  1045. "title_relevance": note_eval.title_relevance,
  1046. "content_expectation": note_eval.content_expectation,
  1047. "need_satisfaction": note_eval.need_satisfaction,
  1048. "confidence_score": note_eval.confidence_score,
  1049. "reason": note_eval.reason
  1050. }
  1051. })
  1052. if note_idx % 3 == 0 or note_idx == len(notes):
  1053. print(f" 已评估 {note_idx}/{len(notes)} 个帖子")
  1054. # 统计
  1055. satisfied_count = sum(1 for ne in note_evaluations if ne["evaluation"]["need_satisfaction"])
  1056. avg_confidence = sum(ne["evaluation"]["confidence_score"] for ne in note_evaluations) / len(note_evaluations) if note_evaluations else 0
  1057. print(f" → 完成:{satisfied_count}/{len(note_evaluations)} 个帖子满足需求")
  1058. return {
  1059. "query": query,
  1060. "from_candidate": search_result['from_candidate'],
  1061. "note_count": len(notes),
  1062. "evaluated_notes": note_evaluations,
  1063. "satisfied_count": satisfied_count,
  1064. "average_confidence": round(avg_confidence, 2)
  1065. }
  1066. # 并发评估所有query的帖子
  1067. all_evaluations = await asyncio.gather(*[evaluate_query_notes(sr, i) for i, sr in enumerate(search_results, 1)])
  1068. # 记录步骤
  1069. total_notes = sum(e['note_count'] for e in all_evaluations)
  1070. total_satisfied = sum(e['satisfied_count'] for e in all_evaluations)
  1071. add_step(context, "评估搜索到的帖子", "evaluate_search_notes", {
  1072. "query_count": len(search_results),
  1073. "total_notes": total_notes,
  1074. "total_satisfied": total_satisfied,
  1075. "note_evaluations": all_evaluations
  1076. })
  1077. return {"note_evaluations": all_evaluations}
  1078. def step_collect_satisfied_notes(note_evaluation_data: dict) -> list[dict]:
  1079. """
  1080. 步骤4: 汇总所有满足需求的帖子
  1081. 输入:
  1082. - note_evaluation_data: 步骤3的帖子评估结果
  1083. 输出:
  1084. - 所有满足需求的帖子列表,按置信度降序排列
  1085. """
  1086. print(f"\n{'='*60}")
  1087. print(f"汇总满足需求的帖子")
  1088. print(f"{'='*60}")
  1089. all_satisfied_notes = []
  1090. for query_eval in note_evaluation_data['note_evaluations']:
  1091. for note in query_eval['evaluated_notes']:
  1092. if note['evaluation']['need_satisfaction']:
  1093. all_satisfied_notes.append({
  1094. "query": query_eval['query'],
  1095. "from_candidate": query_eval['from_candidate'],
  1096. "note_id": note['note_id'],
  1097. "title": note['title'],
  1098. "desc": note['desc'],
  1099. # ⭐ 保留完整帖子信息
  1100. "image_list": note.get('image_list', []),
  1101. "cover_image": note.get('cover_image', {}),
  1102. "interact_info": note.get('interact_info', {}),
  1103. "user": note.get('user', {}),
  1104. "type": note.get('type', 'normal'),
  1105. "note_url": note.get('note_url', ''),
  1106. # 评估结果
  1107. "title_relevance": note['evaluation']['title_relevance'],
  1108. "content_expectation": note['evaluation']['content_expectation'],
  1109. "confidence_score": note['evaluation']['confidence_score'],
  1110. "reason": note['evaluation']['reason']
  1111. })
  1112. # 按置信度降序排列
  1113. all_satisfied_notes.sort(key=lambda x: x['confidence_score'], reverse=True)
  1114. print(f"\n共收集到 {len(all_satisfied_notes)} 个满足需求的帖子")
  1115. if all_satisfied_notes:
  1116. print(f"置信度范围: {all_satisfied_notes[0]['confidence_score']:.2f} ~ {all_satisfied_notes[-1]['confidence_score']:.2f}")
  1117. return all_satisfied_notes
  1118. async def step_generate_answer(satisfied_notes: list[dict], original_question: str, context: RunContext) -> dict:
  1119. """
  1120. 步骤5: 基于满足需求的帖子生成答案
  1121. 输入:
  1122. - satisfied_notes: 步骤4收集的满足需求的帖子列表
  1123. - original_question: 原始问题
  1124. - context: 运行上下文
  1125. 输出:
  1126. - 生成的答案及相关信息
  1127. - answer: 答案内容(Markdown格式)
  1128. - cited_note_indices: 引用的帖子索引
  1129. - confidence: 答案置信度
  1130. - summary: 答案摘要
  1131. - cited_notes: 被引用的帖子详情
  1132. """
  1133. step_num = len(context.steps) + 1
  1134. print(f"\n{'='*60}")
  1135. print(f"[步骤 {step_num}] 基于 {len(satisfied_notes)} 个帖子生成答案")
  1136. print(f"{'='*60}")
  1137. if not satisfied_notes:
  1138. print("\n⚠️ 没有满足需求的帖子,无法生成答案")
  1139. result = {
  1140. "answer": "抱歉,未找到能够回答该问题的相关内容。",
  1141. "cited_note_indices": [],
  1142. "confidence": 0.0,
  1143. "summary": "无可用信息",
  1144. "cited_notes": []
  1145. }
  1146. add_step(context, "生成答案", "answer_generation", {
  1147. "original_question": original_question,
  1148. "input_notes_count": 0,
  1149. "result": result
  1150. })
  1151. return result
  1152. # 构建Agent输入
  1153. notes_info = []
  1154. for idx, note in enumerate(satisfied_notes, 1):
  1155. notes_info.append(f"""
  1156. 【帖子 {idx}】
  1157. 标题: {note['title']}
  1158. 描述: {note['desc']}
  1159. 置信度: {note['confidence_score']:.2f}
  1160. """.strip())
  1161. agent_input = f"""
  1162. <原始问题>
  1163. {original_question}
  1164. </原始问题>
  1165. <相关帖子>
  1166. {chr(10).join(notes_info)}
  1167. </相关帖子>
  1168. 请基于以上帖子,为原始问题生成一个全面、准确的答案。
  1169. 记得在答案中使用 [1], [2] 等标注引用的帖子序号。
  1170. """.strip()
  1171. print(f"\n📝 调用答案生成Agent...")
  1172. print(f" - 可用帖子: {len(satisfied_notes)} 个")
  1173. print(f" - 平均置信度: {sum(n['confidence_score'] for n in satisfied_notes) / len(satisfied_notes):.2f}")
  1174. # 调用Agent生成答案
  1175. result_run = await Runner.run(answer_generator, agent_input)
  1176. answer_result: AnswerGeneration = result_run.final_output
  1177. # 提取被引用的帖子详情
  1178. cited_notes = []
  1179. for idx in answer_result.cited_note_indices:
  1180. if 1 <= idx <= len(satisfied_notes):
  1181. note = satisfied_notes[idx - 1]
  1182. cited_notes.append({
  1183. "index": idx,
  1184. "note_id": note['note_id'],
  1185. "title": note['title'],
  1186. "desc": note['desc'],
  1187. "confidence_score": note['confidence_score'],
  1188. # ⭐ 新增:完整帖子信息用于可视化
  1189. "cover_image": note.get('cover_image', {}),
  1190. "interact_info": note.get('interact_info', {}),
  1191. "user": note.get('user', {}),
  1192. "note_url": note.get('note_url', ''),
  1193. # ⭐ 新增:评估详情
  1194. "title_relevance": note.get('title_relevance', 0),
  1195. "content_expectation": note.get('content_expectation', 0),
  1196. "reason": note.get('reason', '')
  1197. })
  1198. result = {
  1199. "answer": answer_result.answer,
  1200. "cited_note_indices": answer_result.cited_note_indices,
  1201. "confidence": answer_result.confidence,
  1202. "summary": answer_result.summary,
  1203. "cited_notes": cited_notes
  1204. }
  1205. # 打印结果
  1206. print(f"\n✅ 答案生成完成")
  1207. print(f" - 引用帖子数: {len(answer_result.cited_note_indices)} 个")
  1208. print(f" - 答案置信度: {answer_result.confidence:.2f}")
  1209. print(f" - 答案摘要: {answer_result.summary}")
  1210. # 记录步骤
  1211. add_step(context, "生成答案", "answer_generation", {
  1212. "original_question": original_question,
  1213. "input_notes_count": len(satisfied_notes),
  1214. "result": result,
  1215. "agent_input_preview": agent_input[:500] + "..." if len(agent_input) > 500 else agent_input
  1216. })
  1217. return result
  1218. def find_qualified_queries(evaluation_results: list[dict], min_relevance_score: float = 0.7) -> list[dict]:
  1219. """
  1220. 查找所有合格的query(旧函数,保留兼容性)
  1221. 筛选标准:
  1222. 1. intent_match = True(必须满足)
  1223. 2. relevance_score >= min_relevance_score
  1224. 返回:按 relevance_score 降序排列
  1225. """
  1226. all_qualified = []
  1227. for result in evaluation_results:
  1228. for eval_item in result.get("evaluations", []):
  1229. if (eval_item['intent_match'] is True
  1230. and eval_item['relevance_score'] >= min_relevance_score):
  1231. all_qualified.append({
  1232. "from_candidate": result["candidate"],
  1233. **eval_item
  1234. })
  1235. # 按relevance_score降序排列
  1236. return sorted(all_qualified, key=lambda x: x['relevance_score'], reverse=True)
  1237. # ============================================================================
  1238. # 主流程
  1239. # ============================================================================
  1240. async def progressive_exploration(context: RunContext, max_levels: int = 4) -> dict:
  1241. """
  1242. 渐进式探索流程 - 使用独立步骤
  1243. 流程:
  1244. 1. 提取关键词 + 渐进式探索(复用旧流程)
  1245. 2. 步骤1: 评估候选query的推荐词
  1246. 3. 步骤2: 搜索合格的推荐词
  1247. 4. 步骤3: 评估搜索到的帖子
  1248. 5. 步骤4: 汇总满足需求的帖子
  1249. 6. 步骤5: 生成答案
  1250. Args:
  1251. context: 运行上下文
  1252. max_levels: 最大探索层数,默认4
  1253. 返回格式:
  1254. {
  1255. "success": True/False,
  1256. "final_answer": {...}, # 生成的答案
  1257. "satisfied_notes": [...], # 满足需求的帖子
  1258. "message": "..."
  1259. }
  1260. """
  1261. # ========== 阶段1:渐进式探索(复用旧流程找到候选query)==========
  1262. # 1.1 提取关键词
  1263. keyword_result = await extract_keywords(context.q, context)
  1264. context.keywords = keyword_result.keywords
  1265. # 1.2 渐进式探索各层级
  1266. current_level = 1
  1267. candidates_to_evaluate = []
  1268. # Level 1:单个关键词
  1269. level_1_queries = context.keywords[:7]
  1270. level_1_data = await explore_level(level_1_queries, current_level, context)
  1271. analysis_1 = await analyze_level(level_1_data, context.exploration_levels, context.q, context)
  1272. if analysis_1.should_evaluate_now:
  1273. candidates_to_evaluate.extend(analysis_1.candidates_to_evaluate)
  1274. # Level 2及以后:迭代探索
  1275. for level_num in range(2, max_levels + 1):
  1276. prev_analysis: LevelAnalysis = context.level_analyses[-1]["analysis"]
  1277. prev_analysis = LevelAnalysis(**prev_analysis)
  1278. if not prev_analysis.next_combinations:
  1279. print(f"\nLevel {level_num-1} 分析后无需继续探索")
  1280. break
  1281. level_data = await explore_level(prev_analysis.next_combinations, level_num, context)
  1282. analysis = await analyze_level(level_data, context.exploration_levels, context.q, context)
  1283. if analysis.should_evaluate_now:
  1284. candidates_to_evaluate.extend(analysis.candidates_to_evaluate)
  1285. if not candidates_to_evaluate:
  1286. return {
  1287. "success": False,
  1288. "final_answer": None,
  1289. "satisfied_notes": [],
  1290. "message": "渐进式探索未找到候选query"
  1291. }
  1292. print(f"\n{'='*60}")
  1293. print(f"渐进式探索完成,找到 {len(candidates_to_evaluate)} 个候选query")
  1294. print(f"{'='*60}")
  1295. # ========== 阶段2:新的独立步骤流程 ==========
  1296. # 步骤1: 评估候选query的推荐词
  1297. evaluation_results = await step_evaluate_query_suggestions(
  1298. candidates_to_evaluate,
  1299. context.q,
  1300. context
  1301. )
  1302. # 步骤1.5: 筛选合格的推荐词
  1303. qualified_queries = step_filter_qualified_queries(
  1304. evaluation_results,
  1305. context,
  1306. min_relevance_score=0.7
  1307. )
  1308. if not qualified_queries:
  1309. return {
  1310. "success": False,
  1311. "final_answer": None,
  1312. "satisfied_notes": [],
  1313. "message": "没有合格的推荐词"
  1314. }
  1315. # 步骤2: 搜索合格的推荐词
  1316. search_results = await step_search_qualified_queries(
  1317. qualified_queries,
  1318. context
  1319. )
  1320. if not search_results.get('searches'):
  1321. return {
  1322. "success": False,
  1323. "final_answer": None,
  1324. "satisfied_notes": [],
  1325. "message": "搜索失败"
  1326. }
  1327. # 步骤3: 评估搜索到的帖子
  1328. note_evaluation_data = await step_evaluate_search_notes(
  1329. search_results,
  1330. context.q,
  1331. context
  1332. )
  1333. # 步骤4: 汇总满足需求的帖子
  1334. satisfied_notes = step_collect_satisfied_notes(note_evaluation_data)
  1335. if not satisfied_notes:
  1336. return {
  1337. "success": False,
  1338. "final_answer": None,
  1339. "satisfied_notes": [],
  1340. "message": "未找到满足需求的帖子"
  1341. }
  1342. # 步骤5: 生成答案
  1343. final_answer = await step_generate_answer(
  1344. satisfied_notes,
  1345. context.q,
  1346. context
  1347. )
  1348. # ========== 返回最终结果 ==========
  1349. return {
  1350. "success": True,
  1351. "final_answer": final_answer,
  1352. "satisfied_notes": satisfied_notes,
  1353. "message": f"成功找到 {len(satisfied_notes)} 个满足需求的帖子,并生成答案"
  1354. }
  1355. # ============================================================================
  1356. # 输出格式化
  1357. # ============================================================================
  1358. def format_output(optimization_result: dict, context: RunContext) -> str:
  1359. """
  1360. 格式化输出结果 - 用于独立步骤流程
  1361. 包含:
  1362. - 生成的答案
  1363. - 引用的帖子详情
  1364. - 满足需求的帖子统计
  1365. """
  1366. final_answer = optimization_result.get("final_answer")
  1367. satisfied_notes = optimization_result.get("satisfied_notes", [])
  1368. output = f"原始问题:{context.q}\n"
  1369. output += f"提取的关键词:{', '.join(context.keywords or [])}\n"
  1370. output += f"探索层数:{len(context.exploration_levels)}\n"
  1371. output += f"找到满足需求的帖子:{len(satisfied_notes)} 个\n"
  1372. output += "\n" + "="*60 + "\n"
  1373. if final_answer:
  1374. output += "【生成的答案】\n\n"
  1375. output += final_answer.get("answer", "")
  1376. output += "\n\n" + "="*60 + "\n"
  1377. output += f"答案置信度:{final_answer.get('confidence', 0):.2f}\n"
  1378. output += f"答案摘要:{final_answer.get('summary', '')}\n"
  1379. output += f"引用帖子数:{len(final_answer.get('cited_note_indices', []))} 个\n"
  1380. output += "\n" + "="*60 + "\n"
  1381. output += "【引用的帖子详情】\n\n"
  1382. for cited_note in final_answer.get("cited_notes", []):
  1383. output += f"[{cited_note['index']}] {cited_note['title']}\n"
  1384. output += f" 置信度: {cited_note['confidence_score']:.2f}\n"
  1385. output += f" 描述: {cited_note['desc'][:100]}...\n"
  1386. output += f" note_id: {cited_note['note_id']}\n\n"
  1387. else:
  1388. output += "未能生成答案\n"
  1389. return output
  1390. # ============================================================================
  1391. # 主函数
  1392. # ============================================================================
  1393. async def main(input_dir: str, max_levels: int = 4, visualize: bool = False):
  1394. """
  1395. 主函数 - 使用独立步骤流程(方案A)
  1396. """
  1397. current_time, log_url = set_trace()
  1398. # 从目录中读取固定文件名
  1399. input_context_file = os.path.join(input_dir, 'context.md')
  1400. input_q_file = os.path.join(input_dir, 'q.md')
  1401. q_context = read_file_as_string(input_context_file)
  1402. q = read_file_as_string(input_q_file)
  1403. q_with_context = f"""
  1404. <需求上下文>
  1405. {q_context}
  1406. </需求上下文>
  1407. <当前问题>
  1408. {q}
  1409. </当前问题>
  1410. """.strip()
  1411. # 获取当前文件名作为版本
  1412. version = os.path.basename(__file__)
  1413. version_name = os.path.splitext(version)[0]
  1414. # 日志保存目录
  1415. log_dir = os.path.join(input_dir, "output", version_name, current_time)
  1416. run_context = RunContext(
  1417. version=version,
  1418. input_files={
  1419. "input_dir": input_dir,
  1420. "context_file": input_context_file,
  1421. "q_file": input_q_file,
  1422. },
  1423. q_with_context=q_with_context,
  1424. q_context=q_context,
  1425. q=q,
  1426. log_dir=log_dir,
  1427. log_url=log_url,
  1428. )
  1429. # 执行渐进式探索
  1430. optimization_result = await progressive_exploration(run_context, max_levels=max_levels)
  1431. # 格式化输出
  1432. final_output = format_output(optimization_result, run_context)
  1433. print(f"\n{'='*60}")
  1434. print("最终结果")
  1435. print(f"{'='*60}")
  1436. print(final_output)
  1437. # 保存结果
  1438. run_context.optimization_result = optimization_result
  1439. run_context.final_output = final_output
  1440. # 记录最终输出步骤(新格式)
  1441. final_answer = optimization_result.get("final_answer")
  1442. satisfied_notes = optimization_result.get("satisfied_notes", [])
  1443. add_step(run_context, "生成最终结果", "final_result", {
  1444. "success": optimization_result["success"],
  1445. "message": optimization_result["message"],
  1446. "satisfied_notes_count": len(satisfied_notes),
  1447. "final_answer": final_answer,
  1448. "satisfied_notes_summary": [
  1449. {
  1450. "note_id": note["note_id"],
  1451. "title": note["title"],
  1452. "confidence_score": note["confidence_score"]
  1453. }
  1454. for note in satisfied_notes[:10] # 只保存前10个摘要
  1455. ] if satisfied_notes else [],
  1456. "final_output": final_output
  1457. })
  1458. # 保存 RunContext 到 log_dir(不包含 steps,steps 单独保存)
  1459. os.makedirs(run_context.log_dir, exist_ok=True)
  1460. context_file_path = os.path.join(run_context.log_dir, "run_context.json")
  1461. context_dict = run_context.model_dump()
  1462. context_dict.pop('steps', None) # 移除 steps,避免数据冗余
  1463. with open(context_file_path, "w", encoding="utf-8") as f:
  1464. json.dump(context_dict, f, ensure_ascii=False, indent=2)
  1465. print(f"\nRunContext saved to: {context_file_path}")
  1466. # 保存步骤化日志
  1467. steps_file_path = os.path.join(run_context.log_dir, "steps.json")
  1468. with open(steps_file_path, "w", encoding="utf-8") as f:
  1469. json.dump(run_context.steps, f, ensure_ascii=False, indent=2)
  1470. print(f"Steps log saved to: {steps_file_path}")
  1471. # 如果需要生成可视化
  1472. if visualize:
  1473. import subprocess
  1474. output_html = os.path.join(run_context.log_dir, "visualization.html")
  1475. print(f"\n🎨 生成可视化HTML...")
  1476. result = subprocess.run([
  1477. "python", "visualize_steps.py",
  1478. steps_file_path,
  1479. "-o", output_html
  1480. ])
  1481. if result.returncode == 0:
  1482. print(f"✅ 可视化已生成: {output_html}")
  1483. else:
  1484. print(f"❌ 可视化生成失败")
  1485. if __name__ == "__main__":
  1486. parser = argparse.ArgumentParser(description="搜索query优化工具 - v6.1.2.3 独立步骤+答案生成版")
  1487. parser.add_argument(
  1488. "--input-dir",
  1489. type=str,
  1490. default="input/简单扣图",
  1491. help="输入目录路径,默认: input/简单扣图"
  1492. )
  1493. parser.add_argument(
  1494. "--max-levels",
  1495. type=int,
  1496. default=4,
  1497. help="最大探索层数,默认: 4"
  1498. )
  1499. parser.add_argument(
  1500. "--visualize",
  1501. action="store_true",
  1502. default=True,
  1503. help="运行完成后自动生成可视化HTML(默认开启)"
  1504. )
  1505. parser.add_argument(
  1506. "--no-visualize",
  1507. action="store_false",
  1508. dest="visualize",
  1509. help="关闭自动生成可视化"
  1510. )
  1511. parser.add_argument(
  1512. "--visualize-only",
  1513. action="store_true",
  1514. help="只生成可视化,不运行搜索流程。自动查找input-dir下最新的输出目录"
  1515. )
  1516. args = parser.parse_args()
  1517. # 如果只是生成可视化
  1518. if args.visualize_only:
  1519. import subprocess
  1520. import glob
  1521. # 获取版本名称
  1522. version_name = os.path.splitext(os.path.basename(__file__))[0]
  1523. output_base = os.path.join(args.input_dir, "output", version_name)
  1524. # 查找最新的输出目录
  1525. if not os.path.exists(output_base):
  1526. print(f"❌ 找不到输出目录: {output_base}")
  1527. sys.exit(1)
  1528. # 获取所有日期目录
  1529. date_dirs = glob.glob(os.path.join(output_base, "*", "*"))
  1530. if not date_dirs:
  1531. print(f"❌ 在 {output_base} 中没有找到输出目录")
  1532. sys.exit(1)
  1533. # 按修改时间排序,获取最新的
  1534. latest_dir = max(date_dirs, key=os.path.getmtime)
  1535. steps_json = os.path.join(latest_dir, "steps.json")
  1536. if not os.path.exists(steps_json):
  1537. print(f"❌ 找不到 steps.json: {steps_json}")
  1538. sys.exit(1)
  1539. output_html = os.path.join(latest_dir, "visualization.html")
  1540. print(f"🎨 找到最新输出目录: {latest_dir}")
  1541. print(f"🎨 生成可视化: {steps_json} -> {output_html}")
  1542. result = subprocess.run([
  1543. "python", "visualize_steps.py",
  1544. steps_json,
  1545. "-o", output_html
  1546. ])
  1547. sys.exit(result.returncode)
  1548. asyncio.run(main(args.input_dir, max_levels=args.max_levels, visualize=args.visualize))