sug_v6_1_2_11.py 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  1. import asyncio
  2. import json
  3. import os
  4. import sys
  5. import argparse
  6. from datetime import datetime
  7. from typing import Literal
  8. from agents import Agent, Runner
  9. from lib.my_trace import set_trace
  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. # ============================================================================
  17. # 数据模型
  18. # ============================================================================
  19. class Seg(BaseModel):
  20. """分词"""
  21. text: str
  22. score_with_o: float = 0.0 # 与原始问题的评分
  23. reason: str = "" # 评分理由
  24. from_o: str = "" # 原始问题
  25. class Word(BaseModel):
  26. """词"""
  27. text: str
  28. score_with_o: float = 0.0 # 与原始问题的评分
  29. from_o: str = "" # 原始问题
  30. class QFromQ(BaseModel):
  31. """Q来源信息(用于Sug中记录)"""
  32. text: str
  33. score_with_o: float = 0.0
  34. class Q(BaseModel):
  35. """查询"""
  36. text: str
  37. score_with_o: float = 0.0 # 与原始问题的评分
  38. reason: str = "" # 评分理由
  39. from_source: str = "" # seg/sug/add(加词)
  40. class Sug(BaseModel):
  41. """建议词"""
  42. text: str
  43. score_with_o: float = 0.0 # 与原始问题的评分
  44. reason: str = "" # 评分理由
  45. from_q: QFromQ | None = None # 来自的q
  46. class Seed(BaseModel):
  47. """种子"""
  48. text: str
  49. added_words: list[str] = Field(default_factory=list) # 已经增加的words
  50. from_type: str = "" # seg/sug
  51. score_with_o: float = 0.0 # 与原始问题的评分
  52. class Post(BaseModel):
  53. """帖子"""
  54. title: str = ""
  55. body_text: str = ""
  56. type: str = "normal" # video/normal
  57. images: list[str] = Field(default_factory=list) # 图片url列表,第一张为封面
  58. video: str = "" # 视频url
  59. interact_info: dict = Field(default_factory=dict) # 互动信息
  60. note_id: str = ""
  61. note_url: str = ""
  62. class Search(Sug):
  63. """搜索结果(继承Sug)"""
  64. post_list: list[Post] = Field(default_factory=list) # 搜索得到的帖子列表
  65. class RunContext(BaseModel):
  66. """运行上下文"""
  67. version: str
  68. input_files: dict[str, str]
  69. c: str # 原始需求
  70. o: str # 原始问题
  71. log_url: str
  72. log_dir: str
  73. # 每轮的数据
  74. rounds: list[dict] = Field(default_factory=list) # 每轮的详细数据
  75. # 最终结果
  76. final_output: str | None = None
  77. # ============================================================================
  78. # Agent 定义
  79. # ============================================================================
  80. # Agent 1: 分词专家
  81. class WordSegmentation(BaseModel):
  82. """分词结果"""
  83. words: list[str] = Field(..., description="分词结果列表")
  84. reasoning: str = Field(..., description="分词理由")
  85. word_segmentation_instructions = """
  86. 你是分词专家。给定一个query,将其拆分成有意义的最小单元。
  87. ## 分词原则
  88. 1. 保留有搜索意义的词汇
  89. 2. 拆分成独立的概念
  90. 3. 保留专业术语的完整性
  91. 4. 去除虚词(的、吗、呢等)
  92. ## 输出要求
  93. 返回分词列表和分词理由。
  94. """.strip()
  95. word_segmenter = Agent[None](
  96. name="分词专家",
  97. instructions=word_segmentation_instructions,
  98. model=get_model(MODEL_NAME),
  99. output_type=WordSegmentation,
  100. )
  101. # Agent 2.1: 动机维度评估专家
  102. class MotivationEvaluation(BaseModel):
  103. """动机维度评估"""
  104. motivation_score: float = Field(..., description="动机维度得分 -1~1")
  105. reason: str = Field(..., description="动机评估理由")
  106. # Agent 2.2: 品类维度评估专家
  107. class CategoryEvaluation(BaseModel):
  108. """品类维度评估"""
  109. category_score: float = Field(..., description="品类维度得分 -1~1")
  110. reason: str = Field(..., description="品类评估理由")
  111. motivation_evaluation_instructions = """
  112. # 角色定义
  113. 你是 **动机维度评估专家**。你的任务是:评估 <平台sug词条> 与 <原始问题> 的**动机匹配度**,给出 **-1 到 1 之间** 的数值评分。
  114. ## 核心任务
  115. 评估对象:<平台sug词条> 与 <原始问题> 的需求动机匹配度
  116. 核心要素:**动词** - 获取、学习、拍摄、制作、寻找等
  117. ## 如何识别核心动机
  118. **核心动机必须是动词**:
  119. ### 方法1: 显性动词直接提取
  120. 当原始问题明确包含动词时,直接提取
  121. 示例:
  122. "如何获取素材" → 核心动机 = "获取"
  123. "寻找拍摄技巧" → 核心动机 = "寻找"(或"学习")
  124. "制作视频教程" → 核心动机 = "制作"
  125. ### 方法2: 隐性动词语义推理
  126. 当原始问题没有显性动词时,需要结合上下文推理
  127. 示例:
  128. "川西秋天风光摄影" → 隐含动作="拍摄"
  129. 如果原始问题是纯名词短语,无任何动作线索:
  130. → 核心动机 = 无法识别
  131. → 得分 = 0
  132. 示例:
  133. "摄影" → 无法识别动机,得分=0
  134. "川西风光" → 无法识别动机,得分=0
  135. ## 评分标准
  136. 【正向匹配】
  137. +1.0: 核心动作完全一致
  138. - 例: 原始问题"如何获取素材" vs sug词"素材获取方法"
  139. - 特殊规则: sug词的核心动作是原始问题动作的具体化子集,也判定为完全一致
  140. · 例: 原始问题"扣除猫咪主体的方法" vs sug词"扣除猫咪眼睛的方法"
  141. +0.8~0.95: 核心动作语义相近或为同义表达
  142. - 例: 原始问题"如何获取素材" vs sug词"素材下载教程"
  143. - 同义词对: 获取≈下载≈寻找, 技巧≈方法≈教程≈攻略
  144. +0.5~0.75: 核心动作相关但非直接对应(相关实现路径)
  145. - 例: 原始问题"如何获取素材" vs sug词"素材管理整理"
  146. +0.2~0.45: 核心动作弱相关(同领域不同动作)
  147. - 例: 原始问题"如何拍摄风光" vs sug词"风光摄影欣赏"
  148. 【中性/无关】
  149. 0: 没有明确目的,动作意图无明确关联
  150. - 例: 原始问题"如何获取素材" vs sug词"摄影器材推荐"
  151. - 例: 原始问题无法识别动机 且 sug词也无明确动作 → 0
  152. 【负向偏离】
  153. -0.2~-0.05: 动作意图轻度冲突或误导
  154. - 例: 原始问题"如何获取素材" vs sug词"素材版权保护须知"
  155. -0.5~-0.25: 动作意图明显对立
  156. - 例: 原始问题"如何获取免费素材" vs sug词"如何售卖素材"
  157. -1.0~-0.55: 动作意图完全相反或产生严重负面引导
  158. - 例: 原始问题"免费素材获取" vs sug词"付费素材强制推销"
  159. ## 输出
  160. - motivation_score: -1到1的动机得分
  161. - reason: 详细评估理由(说明核心动作识别和匹配情况)
  162. """.strip()
  163. motivation_evaluator = Agent[None](
  164. name="动机维度评估专家",
  165. instructions=motivation_evaluation_instructions,
  166. model=get_model(MODEL_NAME),
  167. output_type=MotivationEvaluation,
  168. )
  169. category_evaluation_instructions = """
  170. # 角色定义
  171. 你是 **品类维度评估专家**。你的任务是:评估 <平台sug词条> 与 <原始问题> 的**品类匹配度**,给出 **-1 到 1 之间** 的数值评分。
  172. ## 核心任务
  173. 评估对象:<平台sug词条> 与 <原始问题> 的内容主体和限定词匹配度
  174. 核心要素:**名词+限定词** - 川西、秋季、风光摄影、素材
  175. ## 评分标准
  176. 【正向匹配】
  177. +1.0: 核心主体+所有关键限定词完全匹配
  178. - 例: 原始问题"川西秋季风光摄影素材" vs sug词"川西秋季风光摄影作品"
  179. +0.75~0.95: 核心主体匹配,大部分限定词匹配
  180. - 例: 原始问题"川西秋季风光摄影素材" vs sug词"川西风光摄影素材"(缺失"秋季")
  181. +0.5~0.7: 核心主体匹配,少量限定词匹配或合理泛化
  182. - 例: 原始问题"川西秋季风光摄影素材" vs sug词"四川风光摄影"
  183. +0.2~0.45: 仅主体词匹配,限定词全部缺失或错位
  184. - 例: 原始问题"川西秋季风光摄影素材" vs sug词"风光摄影入门"
  185. +0.05~0.15: 主题领域相关但品类不同
  186. - 例: 原始问题"风光摄影素材" vs sug词"人文摄影素材"
  187. 【中性/无关】
  188. 0: 主体词部分相关但类别明显不同
  189. - 例: 原始问题"川西秋季风光摄影素材" vs sug词"人像摄影素材"
  190. 【负向偏离】
  191. -0.2~-0.05: 主体词或限定词存在误导性
  192. - 例: 原始问题"免费摄影素材" vs sug词"付费摄影素材库"
  193. -0.5~-0.25: 主体词明显错位或品类冲突
  194. - 例: 原始问题"风光摄影素材" vs sug词"人像修图教程"
  195. -1.0~-0.55: 完全错误的品类或有害引导
  196. - 例: 原始问题"正版素材获取" vs sug词"盗版素材下载"
  197. ## 输出
  198. - category_score: -1到1的品类得分
  199. - reason: 详细评估理由(说明主体词和限定词匹配情况)
  200. """.strip()
  201. category_evaluator = Agent[None](
  202. name="品类维度评估专家",
  203. instructions=category_evaluation_instructions,
  204. model=get_model(MODEL_NAME),
  205. output_type=CategoryEvaluation,
  206. )
  207. # Agent 3: 加词选择专家
  208. class WordSelection(BaseModel):
  209. """加词选择结果"""
  210. selected_word: str = Field(..., description="选择的词")
  211. combined_query: str = Field(..., description="组合后的新query")
  212. reasoning: str = Field(..., description="选择理由")
  213. word_selection_instructions = """
  214. 你是加词选择专家。
  215. ## 任务
  216. 从候选词列表中选择一个最合适的词,与当前seed组合成新的query。
  217. ## 原则
  218. 1. 选择与当前seed最相关的词
  219. 2. 组合后的query要语义通顺
  220. 3. 符合搜索习惯
  221. 4. 优先选择能扩展搜索范围的词
  222. ## 输出
  223. - selected_word: 选中的词
  224. - combined_query: 组合后的新query
  225. - reasoning: 选择理由
  226. """.strip()
  227. word_selector = Agent[None](
  228. name="加词选择专家",
  229. instructions=word_selection_instructions,
  230. model=get_model(MODEL_NAME),
  231. output_type=WordSelection,
  232. )
  233. # ============================================================================
  234. # 辅助函数
  235. # ============================================================================
  236. def process_note_data(note: dict) -> Post:
  237. """处理搜索接口返回的帖子数据"""
  238. note_card = note.get("note_card", {})
  239. image_list = note_card.get("image_list", [])
  240. interact_info = note_card.get("interact_info", {})
  241. user_info = note_card.get("user", {})
  242. # 提取图片URL - 使用新的字段名 image_url
  243. images = []
  244. for img in image_list:
  245. if isinstance(img, dict):
  246. # 尝试新字段名 image_url,如果不存在则尝试旧字段名 url_default
  247. img_url = img.get("image_url") or img.get("url_default")
  248. if img_url:
  249. images.append(img_url)
  250. # 判断类型
  251. note_type = note_card.get("type", "normal")
  252. video_url = ""
  253. if note_type == "video":
  254. video_info = note_card.get("video", {})
  255. if isinstance(video_info, dict):
  256. # 尝试获取视频URL
  257. video_url = video_info.get("media", {}).get("stream", {}).get("h264", [{}])[0].get("master_url", "")
  258. return Post(
  259. note_id=note.get("id", ""),
  260. title=note_card.get("display_title", ""),
  261. body_text=note_card.get("desc", ""),
  262. type=note_type,
  263. images=images,
  264. video=video_url,
  265. interact_info={
  266. "liked_count": interact_info.get("liked_count", 0),
  267. "collected_count": interact_info.get("collected_count", 0),
  268. "comment_count": interact_info.get("comment_count", 0),
  269. "shared_count": interact_info.get("shared_count", 0)
  270. },
  271. note_url=f"https://www.xiaohongshu.com/explore/{note.get('id', '')}"
  272. )
  273. def apply_score_rules(base_score: float, motivation_score: float, category_score: float) -> float:
  274. """
  275. 应用依存性规则调整得分
  276. Args:
  277. base_score: 基础加权得分 (motivation*0.7 + category*0.3)
  278. motivation_score: 动机维度得分
  279. category_score: 品类维度得分
  280. Returns:
  281. 调整后的最终得分
  282. """
  283. # 规则A: 动机高分保护机制
  284. if motivation_score >= 0.8:
  285. # 当目的高度一致时,品类的泛化不应导致"弱相关"
  286. return max(base_score, 0.55)
  287. # 规则B: 动机低分限制机制
  288. if motivation_score <= 0.2:
  289. # 目的不符时,品类匹配的价值有限
  290. return min(base_score, 0.4)
  291. # 规则C: 动机负向决定机制
  292. if motivation_score < 0:
  293. # 动作意图冲突时,推荐具有误导性,不应为正相关
  294. return min(base_score, 0)
  295. # 无规则调整
  296. return base_score
  297. async def evaluate_with_o(text: str, o: str) -> tuple[float, str]:
  298. """评估文本与原始问题o的相关度
  299. 采用两阶段评估:
  300. 1. 动机维度评估(权重70%)
  301. 2. 品类维度评估(权重30%)
  302. Returns:
  303. tuple[float, str]: (最终相关度分数, 综合评估理由)
  304. """
  305. # 准备输入
  306. eval_input = f"""
  307. <原始问题>
  308. {o}
  309. </原始问题>
  310. <平台sug词条>
  311. {text}
  312. </平台sug词条>
  313. 请评估平台sug词条与原始问题的匹配度。
  314. """
  315. # 并发调用两个评估器
  316. motivation_task = Runner.run(motivation_evaluator, eval_input)
  317. category_task = Runner.run(category_evaluator, eval_input)
  318. motivation_result, category_result = await asyncio.gather(
  319. motivation_task,
  320. category_task
  321. )
  322. # 获取分维度评估结果
  323. motivation_eval: MotivationEvaluation = motivation_result.final_output
  324. category_eval: CategoryEvaluation = category_result.final_output
  325. # 计算基础加权得分
  326. base_score = motivation_eval.motivation_score * 0.7 + category_eval.category_score * 0.3
  327. # 应用规则调整
  328. final_score = apply_score_rules(
  329. base_score,
  330. motivation_eval.motivation_score,
  331. category_eval.category_score
  332. )
  333. # 组合评估理由
  334. combined_reason = (
  335. f"【动机维度 {motivation_eval.motivation_score:.2f}】{motivation_eval.reason}\n"
  336. f"【品类维度 {category_eval.category_score:.2f}】{category_eval.reason}\n"
  337. f"【基础得分 {base_score:.2f}】动机*0.7 + 品类*0.3\n"
  338. f"【最终得分 {final_score:.2f}】"
  339. )
  340. # 如果应用了规则,添加规则说明
  341. if final_score != base_score:
  342. if motivation_eval.motivation_score >= 0.8 and final_score > base_score:
  343. combined_reason += "(应用规则A:动机高分保护)"
  344. elif motivation_eval.motivation_score <= 0.2 and final_score < base_score:
  345. combined_reason += "(应用规则B:动机低分限制)"
  346. elif motivation_eval.motivation_score < 0 and final_score < base_score:
  347. combined_reason += "(应用规则C:动机负向决定)"
  348. return final_score, combined_reason
  349. # ============================================================================
  350. # 核心流程函数
  351. # ============================================================================
  352. async def initialize(o: str, context: RunContext) -> tuple[list[Seg], list[Word], list[Q], list[Seed]]:
  353. """
  354. 初始化阶段
  355. Returns:
  356. (seg_list, word_list_1, q_list_1, seed_list)
  357. """
  358. print(f"\n{'='*60}")
  359. print(f"初始化阶段")
  360. print(f"{'='*60}")
  361. # 1. 分词:原始问题(o) ->分词-> seg_list
  362. print(f"\n[步骤1] 分词...")
  363. result = await Runner.run(word_segmenter, o)
  364. segmentation: WordSegmentation = result.final_output
  365. seg_list = []
  366. for word in segmentation.words:
  367. seg_list.append(Seg(text=word, from_o=o))
  368. print(f"分词结果: {[s.text for s in seg_list]}")
  369. print(f"分词理由: {segmentation.reasoning}")
  370. # 2. 分词评估:seg_list -> 每个seg与o进行评分(并发)
  371. print(f"\n[步骤2] 评估每个分词与原始问题的相关度...")
  372. async def evaluate_seg(seg: Seg) -> Seg:
  373. seg.score_with_o, seg.reason = await evaluate_with_o(seg.text, o)
  374. return seg
  375. if seg_list:
  376. eval_tasks = [evaluate_seg(seg) for seg in seg_list]
  377. await asyncio.gather(*eval_tasks)
  378. for seg in seg_list:
  379. print(f" {seg.text}: {seg.score_with_o:.2f}")
  380. # 3. 构建word_list_1: seg_list -> word_list_1
  381. print(f"\n[步骤3] 构建word_list_1...")
  382. word_list_1 = []
  383. for seg in seg_list:
  384. word_list_1.append(Word(
  385. text=seg.text,
  386. score_with_o=seg.score_with_o,
  387. from_o=o
  388. ))
  389. print(f"word_list_1: {[w.text for w in word_list_1]}")
  390. # 4. 构建q_list_1:seg_list 作为 q_list_1
  391. print(f"\n[步骤4] 构建q_list_1...")
  392. q_list_1 = []
  393. for seg in seg_list:
  394. q_list_1.append(Q(
  395. text=seg.text,
  396. score_with_o=seg.score_with_o,
  397. reason=seg.reason,
  398. from_source="seg"
  399. ))
  400. print(f"q_list_1: {[q.text for q in q_list_1]}")
  401. # 5. 构建seed_list: seg_list -> seed_list
  402. print(f"\n[步骤5] 构建seed_list...")
  403. seed_list = []
  404. for seg in seg_list:
  405. seed_list.append(Seed(
  406. text=seg.text,
  407. added_words=[],
  408. from_type="seg",
  409. score_with_o=seg.score_with_o
  410. ))
  411. print(f"seed_list: {[s.text for s in seed_list]}")
  412. return seg_list, word_list_1, q_list_1, seed_list
  413. async def run_round(
  414. round_num: int,
  415. q_list: list[Q],
  416. word_list: list[Word],
  417. seed_list: list[Seed],
  418. o: str,
  419. context: RunContext,
  420. xiaohongshu_api: XiaohongshuSearchRecommendations,
  421. xiaohongshu_search: XiaohongshuSearch,
  422. sug_threshold: float = 0.7
  423. ) -> tuple[list[Word], list[Q], list[Seed], list[Search]]:
  424. """
  425. 运行一轮
  426. Args:
  427. round_num: 轮次编号
  428. q_list: 当前轮的q列表
  429. word_list: 当前的word列表
  430. seed_list: 当前的seed列表
  431. o: 原始问题
  432. context: 运行上下文
  433. xiaohongshu_api: 建议词API
  434. xiaohongshu_search: 搜索API
  435. sug_threshold: suggestion的阈值
  436. Returns:
  437. (word_list_next, q_list_next, seed_list_next, search_list)
  438. """
  439. print(f"\n{'='*60}")
  440. print(f"第{round_num}轮")
  441. print(f"{'='*60}")
  442. round_data = {
  443. "round_num": round_num,
  444. "input_q_list": [{"text": q.text, "score": q.score_with_o} for q in q_list],
  445. "input_word_list_size": len(word_list),
  446. "input_seed_list_size": len(seed_list)
  447. }
  448. # 1. 请求sug:q_list -> 每个q请求sug接口 -> sug_list_list
  449. print(f"\n[步骤1] 为每个q请求建议词...")
  450. sug_list_list = [] # list of list
  451. for q in q_list:
  452. print(f"\n 处理q: {q.text}")
  453. suggestions = xiaohongshu_api.get_recommendations(keyword=q.text)
  454. q_sug_list = []
  455. if suggestions:
  456. print(f" 获取到 {len(suggestions)} 个建议词")
  457. for sug_text in suggestions:
  458. sug = Sug(
  459. text=sug_text,
  460. from_q=QFromQ(text=q.text, score_with_o=q.score_with_o)
  461. )
  462. q_sug_list.append(sug)
  463. else:
  464. print(f" 未获取到建议词")
  465. sug_list_list.append(q_sug_list)
  466. # 2. sug评估:sug_list_list -> 每个sug与o进评分(并发)
  467. print(f"\n[步骤2] 评估每个建议词与原始问题的相关度...")
  468. # 2.1 收集所有需要评估的sug,并记录它们所属的q
  469. all_sugs = []
  470. sug_to_q_map = {} # 记录每个sug属于哪个q
  471. for i, q_sug_list in enumerate(sug_list_list):
  472. if q_sug_list:
  473. q_text = q_list[i].text
  474. for sug in q_sug_list:
  475. all_sugs.append(sug)
  476. sug_to_q_map[id(sug)] = q_text
  477. # 2.2 并发评估所有sug
  478. async def evaluate_sug(sug: Sug) -> Sug:
  479. sug.score_with_o, sug.reason = await evaluate_with_o(sug.text, o)
  480. return sug
  481. if all_sugs:
  482. eval_tasks = [evaluate_sug(sug) for sug in all_sugs]
  483. await asyncio.gather(*eval_tasks)
  484. # 2.3 打印结果并组织到sug_details
  485. sug_details = {} # 保存每个Q对应的sug列表
  486. for i, q_sug_list in enumerate(sug_list_list):
  487. if q_sug_list:
  488. q_text = q_list[i].text
  489. print(f"\n 来自q '{q_text}' 的建议词:")
  490. sug_details[q_text] = []
  491. for sug in q_sug_list:
  492. print(f" {sug.text}: {sug.score_with_o:.2f}")
  493. # 保存到sug_details
  494. sug_details[q_text].append({
  495. "text": sug.text,
  496. "score": sug.score_with_o,
  497. "reason": sug.reason
  498. })
  499. # 3. search_list构建
  500. print(f"\n[步骤3] 构建search_list(阈值>{sug_threshold})...")
  501. search_list = []
  502. high_score_sugs = [sug for sug in all_sugs if sug.score_with_o > sug_threshold]
  503. if high_score_sugs:
  504. print(f" 找到 {len(high_score_sugs)} 个高分建议词")
  505. # 并发搜索
  506. async def search_for_sug(sug: Sug) -> Search:
  507. print(f" 搜索: {sug.text}")
  508. try:
  509. search_result = xiaohongshu_search.search(keyword=sug.text)
  510. result_str = search_result.get("result", "{}")
  511. if isinstance(result_str, str):
  512. result_data = json.loads(result_str)
  513. else:
  514. result_data = result_str
  515. notes = result_data.get("data", {}).get("data", [])
  516. post_list = []
  517. for note in notes[:10]: # 只取前10个
  518. post = process_note_data(note)
  519. post_list.append(post)
  520. print(f" → 找到 {len(post_list)} 个帖子")
  521. return Search(
  522. text=sug.text,
  523. score_with_o=sug.score_with_o,
  524. from_q=sug.from_q,
  525. post_list=post_list
  526. )
  527. except Exception as e:
  528. print(f" ✗ 搜索失败: {e}")
  529. return Search(
  530. text=sug.text,
  531. score_with_o=sug.score_with_o,
  532. from_q=sug.from_q,
  533. post_list=[]
  534. )
  535. search_tasks = [search_for_sug(sug) for sug in high_score_sugs]
  536. search_list = await asyncio.gather(*search_tasks)
  537. else:
  538. print(f" 没有高分建议词,search_list为空")
  539. # 4. 构建word_list_next: word_list -> word_list_next(先直接复制)
  540. print(f"\n[步骤4] 构建word_list_next(暂时直接复制)...")
  541. word_list_next = word_list.copy()
  542. # 5. 构建q_list_next
  543. print(f"\n[步骤5] 构建q_list_next...")
  544. q_list_next = []
  545. add_word_details = {} # 保存每个seed对应的组合词列表
  546. # 5.1 对于seed_list中的每个seed,从word_list_next中选一个未加过的词
  547. print(f"\n 5.1 为每个seed加词...")
  548. for seed in seed_list:
  549. print(f"\n 处理seed: {seed.text}")
  550. # 简单过滤:找出不在seed.text中且未被添加过的词
  551. candidate_words = []
  552. for word in word_list_next:
  553. # 检查词是否已在seed中
  554. if word.text in seed.text:
  555. continue
  556. # 检查词是否已被添加过
  557. if word.text in seed.added_words:
  558. continue
  559. candidate_words.append(word)
  560. if not candidate_words:
  561. print(f" 没有可用的候选词")
  562. continue
  563. print(f" 候选词: {[w.text for w in candidate_words]}")
  564. # 使用Agent选择最合适的词
  565. selection_input = f"""
  566. <原始问题>
  567. {o}
  568. </原始问题>
  569. <当前Seed>
  570. {seed.text}
  571. </当前Seed>
  572. <候选词列表>
  573. {', '.join([w.text for w in candidate_words])}
  574. </候选词列表>
  575. 请从候选词中选择一个最合适的词,与当前seed组合成新的query。
  576. """
  577. result = await Runner.run(word_selector, selection_input)
  578. selection: WordSelection = result.final_output
  579. # 验证选择的词是否在候选列表中
  580. if selection.selected_word not in [w.text for w in candidate_words]:
  581. print(f" ✗ Agent选择的词 '{selection.selected_word}' 不在候选列表中,跳过")
  582. continue
  583. print(f" ✓ 选择词: {selection.selected_word}")
  584. print(f" ✓ 新query: {selection.combined_query}")
  585. print(f" 理由: {selection.reasoning}")
  586. # 评估新query
  587. new_q_score, new_q_reason = await evaluate_with_o(selection.combined_query, o)
  588. print(f" 新query评分: {new_q_score:.2f}")
  589. # 创建新的q
  590. new_q = Q(
  591. text=selection.combined_query,
  592. score_with_o=new_q_score,
  593. reason=new_q_reason,
  594. from_source="add"
  595. )
  596. q_list_next.append(new_q)
  597. # 更新seed的added_words
  598. seed.added_words.append(selection.selected_word)
  599. # 保存到add_word_details
  600. if seed.text not in add_word_details:
  601. add_word_details[seed.text] = []
  602. add_word_details[seed.text].append({
  603. "text": selection.combined_query,
  604. "score": new_q_score,
  605. "reason": new_q_reason,
  606. "selected_word": selection.selected_word
  607. })
  608. # 5.2 对于sug_list_list中,每个sug大于来自的query分数,加到q_list_next
  609. print(f"\n 5.2 将高分sug加入q_list_next...")
  610. for sug in all_sugs:
  611. if sug.from_q and sug.score_with_o > sug.from_q.score_with_o:
  612. new_q = Q(
  613. text=sug.text,
  614. score_with_o=sug.score_with_o,
  615. reason=sug.reason,
  616. from_source="sug"
  617. )
  618. q_list_next.append(new_q)
  619. print(f" ✓ {sug.text} (分数: {sug.score_with_o:.2f} > {sug.from_q.score_with_o:.2f})")
  620. # 6. 更新seed_list
  621. print(f"\n[步骤6] 更新seed_list...")
  622. seed_list_next = seed_list.copy() # 保留原有的seed
  623. # 对于sug_list_list中,每个sug分数大于来源query分数的,且没在seed_list中出现过的,加入
  624. existing_seed_texts = {seed.text for seed in seed_list_next}
  625. for sug in all_sugs:
  626. # 新逻辑:sug分数 > 对应query分数
  627. if sug.from_q and sug.score_with_o > sug.from_q.score_with_o and sug.text not in existing_seed_texts:
  628. new_seed = Seed(
  629. text=sug.text,
  630. added_words=[],
  631. from_type="sug",
  632. score_with_o=sug.score_with_o
  633. )
  634. seed_list_next.append(new_seed)
  635. existing_seed_texts.add(sug.text)
  636. print(f" ✓ 新seed: {sug.text} (分数: {sug.score_with_o:.2f} > 来源query: {sug.from_q.score_with_o:.2f})")
  637. # 序列化搜索结果数据(包含帖子详情)
  638. search_results_data = []
  639. for search in search_list:
  640. search_results_data.append({
  641. "text": search.text,
  642. "score_with_o": search.score_with_o,
  643. "post_list": [
  644. {
  645. "note_id": post.note_id,
  646. "note_url": post.note_url,
  647. "title": post.title,
  648. "body_text": post.body_text,
  649. "images": post.images,
  650. "interact_info": post.interact_info
  651. }
  652. for post in search.post_list
  653. ]
  654. })
  655. # 记录本轮数据
  656. round_data.update({
  657. "sug_count": len(all_sugs),
  658. "high_score_sug_count": len(high_score_sugs),
  659. "search_count": len(search_list),
  660. "total_posts": sum(len(s.post_list) for s in search_list),
  661. "q_list_next_size": len(q_list_next),
  662. "seed_list_next_size": len(seed_list_next),
  663. "word_list_next_size": len(word_list_next),
  664. "output_q_list": [{"text": q.text, "score": q.score_with_o, "reason": q.reason, "from": q.from_source} for q in q_list_next],
  665. "seed_list_next": [{"text": seed.text, "from": seed.from_type, "score": seed.score_with_o} for seed in seed_list_next], # 下一轮种子列表
  666. "sug_details": sug_details, # 每个Q对应的sug列表
  667. "add_word_details": add_word_details, # 每个seed对应的组合词列表
  668. "search_results": search_results_data # 搜索结果(包含帖子详情)
  669. })
  670. context.rounds.append(round_data)
  671. print(f"\n本轮总结:")
  672. print(f" 建议词数量: {len(all_sugs)}")
  673. print(f" 高分建议词: {len(high_score_sugs)}")
  674. print(f" 搜索数量: {len(search_list)}")
  675. print(f" 帖子总数: {sum(len(s.post_list) for s in search_list)}")
  676. print(f" 下轮q数量: {len(q_list_next)}")
  677. print(f" seed数量: {len(seed_list_next)}")
  678. return word_list_next, q_list_next, seed_list_next, search_list
  679. async def iterative_loop(
  680. context: RunContext,
  681. max_rounds: int = 2,
  682. sug_threshold: float = 0.7
  683. ):
  684. """主迭代循环"""
  685. print(f"\n{'='*60}")
  686. print(f"开始迭代循环")
  687. print(f"最大轮数: {max_rounds}")
  688. print(f"sug阈值: {sug_threshold}")
  689. print(f"{'='*60}")
  690. # 初始化
  691. seg_list, word_list, q_list, seed_list = await initialize(context.o, context)
  692. # API实例
  693. xiaohongshu_api = XiaohongshuSearchRecommendations()
  694. xiaohongshu_search = XiaohongshuSearch()
  695. # 保存初始化数据
  696. context.rounds.append({
  697. "round_num": 0,
  698. "type": "initialization",
  699. "seg_list": [{"text": s.text, "score": s.score_with_o, "reason": s.reason} for s in seg_list],
  700. "word_list_1": [{"text": w.text, "score": w.score_with_o} for w in word_list],
  701. "q_list_1": [{"text": q.text, "score": q.score_with_o, "reason": q.reason} for q in q_list],
  702. "seed_list": [{"text": s.text, "from_type": s.from_type, "score": s.score_with_o} for s in seed_list]
  703. })
  704. # 收集所有搜索结果
  705. all_search_list = []
  706. # 迭代
  707. round_num = 1
  708. while q_list and round_num <= max_rounds:
  709. word_list, q_list, seed_list, search_list = await run_round(
  710. round_num=round_num,
  711. q_list=q_list,
  712. word_list=word_list,
  713. seed_list=seed_list,
  714. o=context.o,
  715. context=context,
  716. xiaohongshu_api=xiaohongshu_api,
  717. xiaohongshu_search=xiaohongshu_search,
  718. sug_threshold=sug_threshold
  719. )
  720. all_search_list.extend(search_list)
  721. round_num += 1
  722. print(f"\n{'='*60}")
  723. print(f"迭代完成")
  724. print(f" 总轮数: {round_num - 1}")
  725. print(f" 总搜索次数: {len(all_search_list)}")
  726. print(f" 总帖子数: {sum(len(s.post_list) for s in all_search_list)}")
  727. print(f"{'='*60}")
  728. return all_search_list
  729. # ============================================================================
  730. # 主函数
  731. # ============================================================================
  732. async def main(input_dir: str, max_rounds: int = 2, sug_threshold: float = 0.7, visualize: bool = False):
  733. """主函数"""
  734. current_time, log_url = set_trace()
  735. # 读取输入
  736. input_context_file = os.path.join(input_dir, 'context.md')
  737. input_q_file = os.path.join(input_dir, 'q.md')
  738. c = read_file_as_string(input_context_file) # 原始需求
  739. o = read_file_as_string(input_q_file) # 原始问题
  740. # 版本信息
  741. version = os.path.basename(__file__)
  742. version_name = os.path.splitext(version)[0]
  743. # 日志目录
  744. log_dir = os.path.join(input_dir, "output", version_name, current_time)
  745. # 创建运行上下文
  746. run_context = RunContext(
  747. version=version,
  748. input_files={
  749. "input_dir": input_dir,
  750. "context_file": input_context_file,
  751. "q_file": input_q_file,
  752. },
  753. c=c,
  754. o=o,
  755. log_dir=log_dir,
  756. log_url=log_url,
  757. )
  758. # 执行迭代
  759. all_search_list = await iterative_loop(
  760. run_context,
  761. max_rounds=max_rounds,
  762. sug_threshold=sug_threshold
  763. )
  764. # 格式化输出
  765. output = f"原始需求:{run_context.c}\n"
  766. output += f"原始问题:{run_context.o}\n"
  767. output += f"总搜索次数:{len(all_search_list)}\n"
  768. output += f"总帖子数:{sum(len(s.post_list) for s in all_search_list)}\n"
  769. output += "\n" + "="*60 + "\n"
  770. if all_search_list:
  771. output += "【搜索结果】\n\n"
  772. for idx, search in enumerate(all_search_list, 1):
  773. output += f"{idx}. 搜索词: {search.text} (分数: {search.score_with_o:.2f})\n"
  774. output += f" 帖子数: {len(search.post_list)}\n"
  775. if search.post_list:
  776. for post_idx, post in enumerate(search.post_list[:3], 1): # 只显示前3个
  777. output += f" {post_idx}) {post.title}\n"
  778. output += f" URL: {post.note_url}\n"
  779. output += "\n"
  780. else:
  781. output += "未找到搜索结果\n"
  782. run_context.final_output = output
  783. print(f"\n{'='*60}")
  784. print("最终结果")
  785. print(f"{'='*60}")
  786. print(output)
  787. # 保存日志
  788. os.makedirs(run_context.log_dir, exist_ok=True)
  789. context_file_path = os.path.join(run_context.log_dir, "run_context.json")
  790. context_dict = run_context.model_dump()
  791. with open(context_file_path, "w", encoding="utf-8") as f:
  792. json.dump(context_dict, f, ensure_ascii=False, indent=2)
  793. print(f"\nRunContext saved to: {context_file_path}")
  794. # 保存详细的搜索结果
  795. search_results_path = os.path.join(run_context.log_dir, "search_results.json")
  796. search_results_data = [s.model_dump() for s in all_search_list]
  797. with open(search_results_path, "w", encoding="utf-8") as f:
  798. json.dump(search_results_data, f, ensure_ascii=False, indent=2)
  799. print(f"Search results saved to: {search_results_path}")
  800. # 可视化
  801. if visualize:
  802. import subprocess
  803. output_html = os.path.join(run_context.log_dir, "visualization.html")
  804. print(f"\n🎨 生成可视化HTML...")
  805. # 获取绝对路径
  806. abs_context_file = os.path.abspath(context_file_path)
  807. abs_output_html = os.path.abspath(output_html)
  808. # 运行可视化脚本
  809. result = subprocess.run([
  810. "node",
  811. "visualization/sug_v6_1_2_8/index.js",
  812. abs_context_file,
  813. abs_output_html
  814. ])
  815. if result.returncode == 0:
  816. print(f"✅ 可视化已生成: {output_html}")
  817. else:
  818. print(f"❌ 可视化生成失败")
  819. if __name__ == "__main__":
  820. parser = argparse.ArgumentParser(description="搜索query优化工具 - v6.1.2.8 轮次迭代版")
  821. parser.add_argument(
  822. "--input-dir",
  823. type=str,
  824. default="input/旅游-逸趣玩旅行/如何获取能体现川西秋季特色的高质量风光摄影素材?",
  825. help="输入目录路径,默认: input/旅游-逸趣玩旅行/如何获取能体现川西秋季特色的高质量风光摄影素材?"
  826. )
  827. parser.add_argument(
  828. "--max-rounds",
  829. type=int,
  830. default=4,
  831. help="最大轮数,默认: 2"
  832. )
  833. parser.add_argument(
  834. "--sug-threshold",
  835. type=float,
  836. default=0.7,
  837. help="suggestion阈值,默认: 0.7"
  838. )
  839. parser.add_argument(
  840. "--visualize",
  841. action="store_true",
  842. default=True,
  843. help="运行完成后自动生成可视化HTML"
  844. )
  845. args = parser.parse_args()
  846. asyncio.run(main(args.input_dir, max_rounds=args.max_rounds, sug_threshold=args.sug_threshold, visualize=args.visualize))