sug_v6_1_2_116.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645
  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, ModelSettings
  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 TeeLogger:
  20. """同时输出到控制台和日志文件的工具类"""
  21. def __init__(self, stdout, log_file):
  22. self.stdout = stdout
  23. self.log_file = log_file
  24. def write(self, message):
  25. self.stdout.write(message)
  26. self.log_file.write(message)
  27. self.log_file.flush() # 实时写入,避免丢失日志
  28. def flush(self):
  29. self.stdout.flush()
  30. self.log_file.flush()
  31. # ============================================================================
  32. # 数据模型
  33. # ============================================================================
  34. class Seg(BaseModel):
  35. """分词"""
  36. text: str
  37. score_with_o: float = 0.0 # 与原始问题的评分
  38. reason: str = "" # 评分理由
  39. from_o: str = "" # 原始问题
  40. class Word(BaseModel):
  41. """词"""
  42. text: str
  43. score_with_o: float = 0.0 # 与原始问题的评分
  44. from_o: str = "" # 原始问题
  45. class QFromQ(BaseModel):
  46. """Q来源信息(用于Sug中记录)"""
  47. text: str
  48. score_with_o: float = 0.0
  49. class Q(BaseModel):
  50. """查询"""
  51. text: str
  52. score_with_o: float = 0.0 # 与原始问题的评分
  53. reason: str = "" # 评分理由
  54. from_source: str = "" # seg/sug/add(加词)
  55. class Sug(BaseModel):
  56. """建议词"""
  57. text: str
  58. score_with_o: float = 0.0 # 与原始问题的评分
  59. reason: str = "" # 评分理由
  60. from_q: QFromQ | None = None # 来自的q
  61. class Seed(BaseModel):
  62. """种子"""
  63. text: str
  64. added_words: list[str] = Field(default_factory=list) # 已经增加的words
  65. from_type: str = "" # seg/sug/add
  66. score_with_o: float = 0.0 # 与原始问题的评分
  67. class Post(BaseModel):
  68. """帖子"""
  69. title: str = ""
  70. body_text: str = ""
  71. type: str = "normal" # video/normal
  72. images: list[str] = Field(default_factory=list) # 图片url列表,第一张为封面
  73. video: str = "" # 视频url
  74. interact_info: dict = Field(default_factory=dict) # 互动信息
  75. note_id: str = ""
  76. note_url: str = ""
  77. class Search(Sug):
  78. """搜索结果(继承Sug)"""
  79. post_list: list[Post] = Field(default_factory=list) # 搜索得到的帖子列表
  80. class RunContext(BaseModel):
  81. """运行上下文"""
  82. version: str
  83. input_files: dict[str, str]
  84. c: str # 原始需求
  85. o: str # 原始问题
  86. log_url: str
  87. log_dir: str
  88. # 每轮的数据
  89. rounds: list[dict] = Field(default_factory=list) # 每轮的详细数据
  90. # 最终结果
  91. final_output: str | None = None
  92. # 评估缓存:避免重复评估相同文本
  93. evaluation_cache: dict[str, tuple[float, str]] = Field(default_factory=dict)
  94. # key: 文本, value: (score, reason)
  95. # ============================================================================
  96. # Agent 定义
  97. # ============================================================================
  98. # Agent 1: 分词专家
  99. class WordSegmentation(BaseModel):
  100. """分词结果"""
  101. words: list[str] = Field(..., description="分词结果列表")
  102. reasoning: str = Field(..., description="分词理由")
  103. word_segmentation_instructions = """
  104. 你是分词专家。给定一个query,将其拆分成有意义的最小单元,目标是通过分词的不断递进组合来检索到问题来源问题的相关知识
  105. ## 分词原则
  106. 1. 保留有搜索意义的词汇
  107. 2. 拆分成独立的概念
  108. 3. 保留专业术语的完整性
  109. 4. 去除虚词(的、吗、呢等)
  110. 如果是双标行为,单独分词 不拆分,如果有如何两个字 不要
  111. ## 输出要求
  112. 返回分词列表和分词理由。
  113. """.strip()
  114. word_segmenter = Agent[None](
  115. name="分词专家",
  116. instructions=word_segmentation_instructions,
  117. model=get_model(MODEL_NAME),
  118. output_type=WordSegmentation,
  119. )
  120. # Agent 2: 动机维度评估专家 + 品类维度评估专家(两阶段评估)
  121. # 动机评估的嵌套模型
  122. class CoreMotivationExtraction(BaseModel):
  123. """核心动机提取"""
  124. 简要说明核心动机: str = Field(..., description="核心动机说明")
  125. class MotivationEvaluation(BaseModel):
  126. """动机维度评估"""
  127. 原始问题核心动机提取: CoreMotivationExtraction = Field(..., description="原始问题核心动机提取")
  128. 动机维度得分: float = Field(..., description="动机维度得分 -1~1")
  129. 简要说明动机维度相关度理由: str = Field(..., description="动机维度相关度理由")
  130. class CategoryEvaluation(BaseModel):
  131. """品类维度评估"""
  132. 品类维度得分: float = Field(..., description="品类维度得分 -1~1")
  133. 简要说明品类维度相关度理由: str = Field(..., description="品类维度相关度理由")
  134. # 动机评估 prompt - 第一轮版本(来自 sug_v6_1_2_115.py)
  135. motivation_evaluation_instructions_round1 = """
  136. #角色
  137. 你是一个 **专业的语言专家和语义相关性评判专家**。你的任务是:判断我给你的 <平台sug词条> 与 <原始问题> 的需求动机匹配度,给出 **-1 到 1 之间** 的数值评分。
  138. ---
  139. # 核心概念与方法论
  140. ## 评估维度
  141. 本评估系统围绕 **动机维度** 进行:
  142. ### 1. 动机维度
  143. **定义:** 用户"想要做什么",即原始问题的行为意图和目的
  144. - 核心是 **动词**:获取、学习、拍摄、制作、寻找等
  145. - 包括:核心动作 + 使用场景 + 最终目的
  146. ---
  147. ## 如何识别原始问题的核心动机
  148. **核心动机必须是动词**,识别方法如下:
  149. ### 方法1: 显性动词直接提取
  150. 当原始问题明确包含动词时,直接提取
  151. 示例:
  152. "如何获取素材" → 核心动机 = "获取"
  153. "寻找拍摄技巧" → 核心动机 = "寻找"(或"学习")
  154. "制作视频教程" → 核心动机 = "制作"
  155. ### 方法2: 隐性动词语义推理
  156. 当原始问题没有显性动词时,需要结合上下文推理
  157. 示例:
  158. 例: "川西秋天风光摄影" → 隐含动作="拍摄"
  159. → 需结合上下文判断
  160. 如果原始问题是纯名词短语,无任何动作线索:
  161. → 核心动机 = 无法识别
  162. → 在此情况下,动机维度得分应为 0。
  163. 示例:
  164. "摄影" → 无法识别动机,动机维度得分 = 0
  165. "川西风光" → 无法识别动机,动机维度得分 = 0
  166. ---
  167. # 输入信息
  168. 你将接收到以下输入:
  169. - **<原始问题>**:用户的初始查询问题,代表用户的真实需求意图。
  170. - **<平台sug词条>**:平台推荐的词条列表,每个词条需要单独评估。
  171. #判定流程
  172. #评估架构
  173. 输入: <原始问题> + <平台sug词条>
  174. 【动机维度相关性判定】
  175. ├→ 步骤1: 评估<sug词条>与<原始问题>的需求动机匹配度
  176. └→ 输出: -1到1之间的数值 + 判定依据
  177. 相关度评估维度详解
  178. 维度1: 动机维度评估
  179. 评估对象: <平台sug词条> 与 <原始问题> 的需求动机匹配度
  180. 说明: 核心动作是用户需求的第一优先级,决定了推荐的基本有效性
  181. 评分标准:
  182. 【正向匹配】
  183. +0.95~1.0: 核心动作完全一致
  184. - 例: 原始问题"如何获取素材" vs sug词"素材获取方法"
  185. - 特殊规则: 如果sug词的核心动作是原始问题动作的**具体化子集**,也判定为完全一致
  186. · 例: 原始问题"扣除猫咪主体的方法" vs sug词"扣除猫咪眼睛的方法"(子集但目的一致)
  187. +0.75~0.95: 核心动作语义相近或为同义表达
  188. - 例: 原始问题"如何获取素材" vs sug词"如何下载素材"
  189. - 同义词对: 获取≈下载≈寻找, 技巧≈方法≈教程≈攻略
  190. +0.5~0.75: 核心动作相关但非直接对应(相关实现路径)
  191. - 例: 原始问题"如何获取素材" vs sug词"素材管理整理"
  192. +0.2~0.45: 核心动作弱相关(同领域不同动作)
  193. - 例: 原始问题"如何拍摄风光" vs sug词"风光摄影欣赏"
  194. 【中性/无关】
  195. 0: 没有明确目的,动作意图无明确关联
  196. - 例: 原始问题"如何获取素材" vs sug词"摄影器材推荐"
  197. - 例: 原始问题无法识别动机 且 sug词也无明确动作 → 0
  198. - 如果原始问题无法识别动机,则动机维度得分为0。
  199. 【负向偏离】
  200. -0.2~-0.05: 动作意图轻度冲突或误导
  201. - 例: 原始问题"如何获取素材" vs sug词"素材版权保护须知"
  202. -0.5~-0.25: 动作意图明显对立
  203. - 例: 原始问题"如何获取免费素材" vs sug词"如何售卖素材"
  204. -1.0~-0.55: 动作意图完全相反或产生严重负面引导
  205. - 例: 原始问题"免费素材获取" vs sug词"付费素材强制推销"
  206. ---
  207. # 输出要求
  208. 输出结果必须为一个 **JSON 格式**,包含以下内容:
  209. ```json
  210. {
  211. "原始问题核心动机提取": {
  212. "简要说明核心动机": ""
  213. },
  214. "动机维度得分": "-1到1之间的小数",
  215. "简要说明动机维度相关度理由": "评估该sug词条与原始问题动机匹配程度的理由"
  216. }
  217. **输出约束(非常重要)**:
  218. 1. **字符串长度限制**:\"简要说明动机维度相关度理由\"字段必须控制在**150字以内**
  219. 2. **JSON格式规范**:必须生成完整的JSON格式,确保字符串用双引号包裹且正确闭合
  220. 3. **引号使用**:字符串中如需表达引用,请使用《》或「」代替单引号或双引号
  221. #注意事项:
  222. 始终围绕动机维度:所有评估都基于"动机"维度,不偏离
  223. 核心动机必须是动词:在评估前,必须先提取原始问题的核心动机(动词),这是整个评估的基础
  224. 严格标准一致性:对所有用例使用相同的评估标准,避免评分飘移
  225. 负分使用原则:仅当sug词条对原始问题动机产生误导、冲突或有害引导时给予负分
  226. 零分使用原则:当sug词条与原始问题动机无明确关联,既不相关也不冲突时给予零分,或原始问题无法识别动机时。
  227. """.strip()
  228. # 动机评估 prompt - 后续轮次版本(当前 116 版本)
  229. motivation_evaluation_instructions = """
  230. #角色
  231. 你是一个 **专业的语言专家和语义相关性评判专家**。你的任务是:判断我给你的 <平台sug词条> 与 <原始问题> 的需求动机匹配度,给出 **-1 到 1 之间** 的数值评分。
  232. ---
  233. # 动机评估核心原则(必读)
  234. ### 动机 = 动作 + 对象 + 场景
  235. 评估时必须同时考虑三要素,不能只看动词:
  236. - **动作**:制定、规划、获取、拍摄等
  237. - **对象**:旅行行程 vs 每日计划、风光照片 vs 证件照
  238. - **场景**:旅游 vs 日常、摄影 vs 办公
  239. ### 关键判断:动词相同 ≠ 动机匹配
  240. 错误:只看动词相同就给高分
  241. - "制定旅行行程" vs "制定每日计划" → 给0.95 错误
  242. - "拍摄风光" vs "拍摄证件照" → 给0.95 错误
  243. 正确:检查对象和场景是否匹配
  244. - 对象不同领域 → 降至0.3左右
  245. - 场景不同 → 降至0.3左右
  246. # 核心概念与方法论
  247. ## 评估维度
  248. 本评估系统围绕 **动机维度** 进行:
  249. # 维度独立性警告
  250. 【严格约束】本评估**只评估动机维度**:
  251. **禁止使用"主题相关"作为评分依据**:评分理由中不得出现"主题"、"内容"、"话题"等词
  252. ### 1. 动机维度
  253. **定义:** 用户"想要做什么",即原始问题的行为意图和目的
  254. - 核心是 **动词**:获取、学习、拍摄、制作、寻找等
  255. - 包括:核心动作 + 使用场景 + 最终目的
  256. ---
  257. 如果原始问题是纯名词短语,无任何动作线索:
  258. → 核心动机 = 无法识别
  259. → 在此情况下,动机维度得分应为 0。
  260. 示例:
  261. "摄影" → 无法识别动机,动机维度得分 = 0
  262. "川西风光" → 无法识别动机,动机维度得分 = 0
  263. ---
  264. # 输入信息
  265. 你将接收到以下输入:
  266. - **<原始问题>**:用户的初始查询问题,代表用户的真实需求意图。
  267. - **<平台sug词条>**:平台推荐的词条列表,每个词条需要单独评估。
  268. #判定流程
  269. #评估架构
  270. 输入: <原始问题> + <平台sug词条>
  271. 【动机维度相关性判定】
  272. ├→ 步骤1: 评估<sug词条>与<原始问题>的需求动机匹配度
  273. └→ 输出: -1到1之间的数值 + 判定依据
  274. 相关度评估维度详解
  275. 维度1: 动机维度评估
  276. 评估对象: <平台sug词条> 与 <原始问题> 的需求动机匹配度
  277. 说明: 核心动作是用户需求的第一优先级,决定了推荐的基本有效性
  278. 评分标准:
  279. 【正向匹配】
  280. +0.95~1.0: 动作+对象+场景完全一致
  281. - 要求:动词、对象、场景都必须匹配,不能只看动词
  282. - "制定旅行行程" vs "制定每日计划"
  283. 虽然动词相同,但对象和场景完全不同,不属于高分
  284. - 特殊规则: 如果sug词的核心动作是原始问题动作在动作+对象+场景一致下的**具体化子集**,也判定为完全一致
  285. +0.75~0.95: 核心动作语义相近或为同义表达
  286. - 例: 原始问题"如何获取素材" vs sug词"如何下载素材"
  287. - 同义词对: 获取≈下载≈寻找, 技巧≈方法≈教程≈攻略
  288. +0.5~0.75: 核心动作相关但非直接对应(相关实现路径)
  289. - 例: 原始问题"如何获取素材" vs sug词"素材管理整理"
  290. +0.25~0.4: 动词相同但对象或场景明显不同(弱相关)
  291. - 判断要点:动词一致,但对象不同领域或场景不同
  292. - 关键:不要因为动词相同就给0.95,必须检查对象!
  293. 【中性/无关】
  294. 0: 没有明确目的,动作意图无明确关联
  295. - 例: 原始问题"如何获取素材" vs sug词"摄影器材推荐"
  296. - 例: 原始问题无法识别动机 且 sug词也无明确动作 → 0
  297. - 如果原始问题无法识别动机,则动机维度得分为0
  298. 特别注意 - 禁止的错误理由:
  299. - 禁止: "虽然没有动作,但主题相关,所以给0.2"
  300. - 禁止:"内容有参考价值,所以给0.15"
  301. - 禁止: "都提到了XX(名词),所以不是完全无关"
  302. - 正确理由:"sug词条无动作意图,与原始问题的'XX'动机完全无关"
  303. 【负向偏离】
  304. -0.2~-0.05: 动作意图轻度冲突或误导
  305. - 例: 原始问题"如何获取素材" vs sug词"素材版权保护须知"
  306. -0.5~-0.25: 动作意图明显对立
  307. - 例: 原始问题"如何获取免费素材" vs sug词"如何售卖素材"
  308. -1.0~-0.55: 动作意图完全相反或产生严重负面引导
  309. - 例: 原始问题"免费素材获取" vs sug词"付费素材强制推销"
  310. ---
  311. # 输出要求
  312. 输出结果必须为一个 **JSON 格式**,包含以下内容:
  313. ```json
  314. {
  315. "原始问题核心动机提取": {
  316. "简要说明核心动机": ""
  317. },
  318. "动机维度得分": "-1到1之间的小数",
  319. "简要说明动机维度相关度理由": "评估该sug词条与原始问题动机匹配程度的理由"
  320. }
  321. **输出约束(非常重要)**:
  322. 1. **字符串长度限制**:\"简要说明动机维度相关度理由\"字段必须控制在**150字以内**
  323. 2. **JSON格式规范**:必须生成完整的JSON格式,确保字符串用双引号包裹且正确闭合
  324. 3. **引号使用**:字符串中如需表达引用,请使用《》或「」代替单引号或双引号
  325. #注意事项:
  326. 始终围绕动机维度:所有评估都基于"动机"维度,不偏离
  327. 核心动机必须是动词:在评估前,必须先提取原始问题的核心动机(动词),这是整个评估的基础
  328. 严格标准一致性:对所有用例使用相同的评估标准,避免评分飘移
  329. 负分使用原则:仅当sug词条对原始问题动机产生误导、冲突或有害引导时给予负分
  330. 零分使用原则:当sug词条与原始问题动机无明确关联,既不相关也不冲突时给予零分,或原始问题无法识别动机时。
  331. """.strip()
  332. # 品类评估 prompt
  333. category_evaluation_instructions = """
  334. #角色
  335. 你是一个 **专业的语言专家和语义相关性评判专家**。你的任务是:判断我给你的 <平台sug词条> 与 <原始问题> 的内容主体和限定词匹配度,给出 **-1 到 1 之间** 的数值评分。
  336. ---
  337. # 核心概念与方法论
  338. ## 评估维度
  339. 本评估系统围绕 **品类维度** 进行:
  340. # 维度独立性警告
  341. 【严格约束】本评估**只评估品类维度**,,必须遵守以下规则:
  342. 1. **只看名词和限定词**:评估时只考虑主体、限定词的匹配度
  343. 2. **完全忽略动词**:动作意图、目的等动机信息对本维度评分无影响
  344. ### 品类维度
  345. **定义:** 用户"关于什么内容",即原始问题的主题对象和限定词
  346. - 核心是 **名词+限定词**:川西秋季风光摄影素材
  347. - 包括:核心主体 + 地域限定 + 时间限定 + 质量限定等
  348. ## ⚠️ 品类评估核心原则(必读)
  349. ### 原则1:只看词条表面,禁止联想推演
  350. - 只能基于sug词实际包含的词汇评分
  351. - 禁止推测"可能包含"、"可以理解为"
  352. **错误示例:**
  353. 原始问题:"川西旅行行程" vs sug词:"每日计划"
  354. - 错误 "每日计划可以包含旅行规划,所以有关联" → 这是不允许的联想
  355. - 正确: "sug词只有'每日计划',无'旅行'字眼,品类不匹配" → 正确判断
  356. ### 原则2:通用概念 ≠ 特定概念
  357. - **通用**:计划、方法、技巧、素材(无领域限定)
  358. - **特定**:旅行行程、摄影技巧、烘焙方法(有明确领域)
  359. IF sug词是通用 且 原始问题是特定:
  360. → 品类不匹配 → 评分0.05~0.1
  361. 关键:通用概念不等于特定概念,不能因为"抽象上都是规划"就给分
  362. ---
  363. # 输入信息
  364. 你将接收到以下输入:
  365. - **<原始问题>**:用户的初始查询问题,代表用户的真实需求意图。
  366. - **<平台sug词条>**:平台推荐的词条列表,每个词条需要单独评估。
  367. #判定流程
  368. #评估架构
  369. 输入: <原始问题> + <平台sug词条>
  370. 【品类维度相关性判定】
  371. ├→ 步骤1: 评估<sug词条>与<原始问题>的内容主体和限定词匹配度
  372. └→ 输出: -1到1之间的数值 + 判定依据
  373. 相关度评估维度详解
  374. 维度2: 品类维度评估
  375. 评估对象: <平台sug词条> 与 <原始问题> 的内容主体和限定词匹配度
  376. 评分标准:
  377. 【正向匹配】
  378. +0.95~1.0: 核心主体+所有关键限定词完全匹配
  379. - 例: 原始问题"川西秋季风光摄影素材" vs sug词"川西秋季风光摄影作品"
  380. +0.75~0.95: 核心主体匹配,存在限定词匹配
  381. - 例: 原始问题"川西秋季风光摄影素材" vs sug词"川西风光摄影素材"(缺失"秋季")
  382. +0.5~0.75: 核心主体匹配,无限定词匹配或合理泛化
  383. - 例: 原始问题"川西秋季风光摄影素材" vs sug词"四川风光摄影"
  384. +0.3~0.5: 核心主体匹配,但限定词缺失或存在语义错位
  385. - 特别注意"语义身份"差异,主体词出现但上下文语义不同
  386. - 例:
  387. · "猫咪的XX行为"(猫咪是行为者)
  388. · vs "用猫咪表达XX的梗图"(猫咪是媒介)
  389. · 虽都含"猫咪+XX",但语义角色不同
  390. +0.2~0.3: 主体词不匹配,限定词缺失或错位
  391. - 例: 原始问题"川西秋季风光摄影素材" vs sug词"风光摄影入门"
  392. +0.05~0.2: 主体词过度泛化或仅抽象相似
  393. - 例: sug词是通用概念,原始问题是特定概念
  394. sug词"每日计划"(通用)vs 原始问题 "川西旅行行程"(特定)
  395. → 评分:0.08
  396. 【中性/无关】
  397. 0: 类别明显不同,没有明确目的,无明确关联
  398. - 例: 原始问题"川西秋季风光摄影素材" vs sug词"人像摄影素材"
  399. - 例: 原始问题无法识别动机 且 sug词也无明确动作 → 0
  400. 【负向偏离】
  401. -0.2~-0.05: 主体词或限定词存在误导性
  402. - 例: 原始问题"免费摄影素材" vs sug词"付费摄影素材库"
  403. -0.5~-0.25: 主体词明显错位或品类冲突
  404. - 例: 原始问题"风光摄影素材" vs sug词"人像修图教程"
  405. -1.0~-0.55: 完全错误的品类或有害引导
  406. - 例: 原始问题"正版素材获取" vs sug词"盗版素材下载"
  407. ---
  408. # 输出要求
  409. 输出结果必须为一个 **JSON 格式**,包含以下内容:
  410. ```json
  411. {
  412. "品类维度得分": "-1到1之间的小数",
  413. "简要说明品类维度相关度理由": "评估该sug词条与原始问题品类匹配程度的理由"
  414. }
  415. ---
  416. **输出约束(非常重要)**:
  417. 1. **字符串长度限制**:\"简要说明品类维度相关度理由\"字段必须控制在**150字以内**
  418. 2. **JSON格式规范**:必须生成完整的JSON格式,确保字符串用双引号包裹且正确闭合
  419. 3. **引号使用**:字符串中如需表达引用,请使用《》或「」代替单引号或双引号
  420. ---
  421. #注意事项:
  422. 始终围绕品类维度:所有评估都基于"品类"维度,不偏离
  423. 严格标准一致性:对所有用例使用相同的评估标准,避免评分飘移
  424. 负分使用原则:仅当sug词条对原始问题品类产生误导、冲突或有害引导时给予负分
  425. 零分使用原则:当sug词条与原始问题品类无明确关联,既不相关也不冲突时给予零分
  426. """.strip()
  427. # 创建评估 Agent - 第一轮使用
  428. motivation_evaluator_round1 = Agent[None](
  429. name="动机维度评估专家(第一轮)",
  430. instructions=motivation_evaluation_instructions_round1,
  431. model=get_model(MODEL_NAME),
  432. output_type=MotivationEvaluation)
  433. # 创建评估 Agent - 后续轮次使用
  434. motivation_evaluator = Agent[None](
  435. name="动机维度评估专家(后续轮次)",
  436. instructions=motivation_evaluation_instructions,
  437. model=get_model(MODEL_NAME),
  438. output_type=MotivationEvaluation)
  439. category_evaluator = Agent[None](
  440. name="品类维度评估专家",
  441. instructions=category_evaluation_instructions,
  442. model=get_model(MODEL_NAME),
  443. output_type=CategoryEvaluation
  444. )
  445. # Agent 3: 加词选择专家
  446. class WordCombination(BaseModel):
  447. """单个词组合"""
  448. selected_word: str = Field(..., description="选择的词")
  449. combined_query: str = Field(..., description="组合后的新query")
  450. reasoning: str = Field(..., description="选择理由")
  451. class WordSelectionTop5(BaseModel):
  452. """加词选择结果(Top 5)"""
  453. combinations: list[WordCombination] = Field(
  454. ...,
  455. description="选择的Top 5组合(不足5个则返回所有)",
  456. min_items=1,
  457. max_items=5
  458. )
  459. overall_reasoning: str = Field(..., description="整体选择思路")
  460. word_selection_instructions = """
  461. 你是加词组合专家。
  462. ## 任务
  463. 从候选词列表中选择5个最合适的词,分别与当前seed组合成新的query。如果候选词不足5个,则返回所有。
  464. ## 选择原则
  465. 1. **相关性**:选择与当前seed最相关的词
  466. 2. **语义通顺**:组合后的query要符合搜索习惯
  467. 3. **扩展范围**:优先选择能扩展搜索范围的词
  468. 4. **多样性**:5个词应该覆盖不同的方面(如:时间、地点、类型、用途等)
  469. ## 组合约束(严格执行)
  470. **CRITICAL: 以下约束必须100%遵守,违反任何一条都是错误**
  471. 1. **必须完整保留seed的所有文本内容**
  472. - seed的每一个字都必须出现在组合结果中
  473. - 禁止删除、省略、替换seed中的任何部分
  474. - 即使某些字看起来不重要,也必须保留
  475. 2. **必须完整保留word的所有文本内容**
  476. - word的每一个字都必须出现在组合结果中
  477. - 禁止删除、省略、替换word中的任何部分
  478. 3. **禁止添加任何额外内容**
  479. - 不能添加连接词(如"的"、"和"、"与"、"在"等)
  480. - 不能添加任何其他词或字符
  481. 4. **组合方式仅限以下三种**
  482. - seed在前:seed的文本 + word的文本(如:制作梗图 + 猫咪 = 制作梗图猫咪)
  483. - word在前:word的文本 + seed的文本(如:猫咪 + 制作梗图 = 猫咪制作梗图)
  484. - word插入:将word插入seed中间合适位置(如:制作 + 猫咪 + 梗图 = 制作猫咪梗图)
  485. 5. **验证检查清单**(在输出前必须自查)
  486. ☑ 组合结果包含seed的所有字符?
  487. ☑ 组合结果包含word的所有字符?
  488. ☑ 组合结果没有额外的字符?
  489. ☑ 只使用了三种组合方式之一?
  490. ## 正确示例(必须参考)
  491. ✓ seed="制作梗图" + word="猫咪" → "制作梗图猫咪"(seed在前)
  492. ✓ seed="制作梗图" + word="猫咪" → "猫咪制作梗图"(word在前)
  493. ✓ seed="制作梗图" + word="猫咪" → "制作猫咪梗图"(word插入中间)
  494. ✓ seed="川西" + word="秋季" → "川西秋季"(seed在前)
  495. ✓ seed="川西" + word="秋季" → "秋季川西"(word在前)
  496. ✓ seed="摄影" + word="技巧" → "摄影技巧"(seed在前)
  497. ✓ seed="摄影" + word="技巧" → "技巧摄影"(word在前)
  498. ## 错误示例(严禁出现)
  499. ✗ seed="制作梗图" + word="猫咪" → "猫咪梗图"(❌ 缺少"制作")
  500. ✗ seed="制作梗图" + word="猫咪" → "梗图猫咪"(❌ 缺少"制作")
  501. ✗ seed="制作梗图" + word="猫咪" → "制作猫咪表情包"(❌ 加了"表情包")
  502. ✗ seed="川西" + word="秋季" → "川西的秋季"(❌ 加了"的")
  503. ✗ seed="川西" + word="秋季" → "川西秋季风光"(❌ 加了"风光")
  504. ✗ seed="摄影" + word="技巧" → "摄影拍摄技巧"(❌ 加了"拍摄")
  505. ✗ seed="摄影" + word="技巧" → "影技巧"(❌ 缺少"摄")
  506. ## 输出要求
  507. - 最多返回5个组合(如果候选词不足5个,返回所有)
  508. - 每个组合包含:
  509. * selected_word: 选择的词(必须在候选词列表中)
  510. * combined_query: 组合后的新query(只包含seed和word的原始文本,不多不少)
  511. * reasoning: 选择理由(说明为什么选这个词)
  512. - overall_reasoning: 整体选择思路(说明这5个词的选择逻辑)
  513. ## JSON输出规范
  514. 1. **格式要求**:必须输出标准的、完整的JSON格式
  515. 2. **字符限制**:不要在JSON中使用任何不可见的特殊字符或控制字符
  516. 3. **引号规范**:字符串中如需表达引用或强调,使用书名号《》或单书名号「」,不要使用英文引号或中文引号""
  517. 4. **编码规范**:所有文本使用UTF-8编码,不要包含二进制或转义序列
  518. 5. **完整性**:确保JSON的开始和结束括号完整匹配,所有字段都正确闭合
  519. """.strip()
  520. word_selector = Agent[None](
  521. name="加词组合专家",
  522. instructions=word_selection_instructions,
  523. model=get_model(MODEL_NAME),
  524. output_type=WordSelectionTop5,
  525. )
  526. # ============================================================================
  527. # 辅助函数
  528. # ============================================================================
  529. def calculate_final_score(motivation_score: float, category_score: float) -> float:
  530. """
  531. 应用依存性规则计算最终得分
  532. 步骤1: 基础加权计算
  533. base_score = motivation_score * 0.7 + category_score * 0.3
  534. 步骤2: 极值保护规则
  535. Args:
  536. motivation_score: 动机维度得分 -1~1
  537. category_score: 品类维度得分 -1~1
  538. Returns:
  539. 最终得分 -1~1
  540. """
  541. # 基础加权得分
  542. base_score = motivation_score * 0.7 + category_score * 0.3
  543. # 规则C: 动机负向决定机制(最高优先级)
  544. if motivation_score < 0:
  545. return 0.0
  546. # 规则A: 动机高分保护机制
  547. if motivation_score >= 0.8:
  548. # 当目的高度一致时,品类的泛化不应导致"弱相关"
  549. return max(base_score, 0.7)
  550. # 规则B: 动机低分限制机制
  551. if motivation_score <= 0.2:
  552. # 目的不符时,品类匹配的价值有限
  553. return min(base_score, 0.5)
  554. # 无规则调整,返回基础得分
  555. return base_score
  556. def clean_json_string(text: str) -> str:
  557. """清理JSON中的非法控制字符(保留 \t \n \r)"""
  558. import re
  559. # 移除除了 \t(09) \n(0A) \r(0D) 之外的所有控制字符
  560. return re.sub(r'[\x00-\x08\x0B\x0C\x0E-\x1F]', '', text)
  561. def process_note_data(note: dict) -> Post:
  562. """处理搜索接口返回的帖子数据"""
  563. note_card = note.get("note_card", {})
  564. image_list = note_card.get("image_list", [])
  565. interact_info = note_card.get("interact_info", {})
  566. user_info = note_card.get("user", {})
  567. # ========== 调试日志 START ==========
  568. note_id = note.get("id", "")
  569. raw_title = note_card.get("display_title") # 不提供默认值
  570. raw_body = note_card.get("desc")
  571. raw_type = note_card.get("type")
  572. # 打印原始值类型和内容
  573. print(f"\n[DEBUG] 处理帖子 {note_id}:")
  574. print(f" raw_title 类型: {type(raw_title).__name__}, 值: {repr(raw_title)}")
  575. print(f" raw_body 类型: {type(raw_body).__name__}, 值: {repr(raw_body)[:100] if raw_body else repr(raw_body)}")
  576. print(f" raw_type 类型: {type(raw_type).__name__}, 值: {repr(raw_type)}")
  577. # 检查是否为 None
  578. if raw_title is None:
  579. print(f" ⚠️ WARNING: display_title 是 None!")
  580. if raw_body is None:
  581. print(f" ⚠️ WARNING: desc 是 None!")
  582. if raw_type is None:
  583. print(f" ⚠️ WARNING: type 是 None!")
  584. # ========== 调试日志 END ==========
  585. # 提取图片URL - 使用新的字段名 image_url
  586. images = []
  587. for img in image_list:
  588. if isinstance(img, dict):
  589. # 尝试新字段名 image_url,如果不存在则尝试旧字段名 url_default
  590. img_url = img.get("image_url") or img.get("url_default")
  591. if img_url:
  592. images.append(img_url)
  593. # 判断类型
  594. note_type = note_card.get("type", "normal")
  595. video_url = ""
  596. if note_type == "video":
  597. video_info = note_card.get("video", {})
  598. if isinstance(video_info, dict):
  599. # 尝试获取视频URL
  600. video_url = video_info.get("media", {}).get("stream", {}).get("h264", [{}])[0].get("master_url", "")
  601. return Post(
  602. note_id=note.get("id") or "",
  603. title=note_card.get("display_title") or "",
  604. body_text=note_card.get("desc") or "",
  605. type=note_type,
  606. images=images,
  607. video=video_url,
  608. interact_info={
  609. "liked_count": interact_info.get("liked_count", 0),
  610. "collected_count": interact_info.get("collected_count", 0),
  611. "comment_count": interact_info.get("comment_count", 0),
  612. "shared_count": interact_info.get("shared_count", 0)
  613. },
  614. note_url=f"https://www.xiaohongshu.com/explore/{note.get('id', '')}"
  615. )
  616. async def evaluate_with_o(text: str, o: str, cache: dict[str, tuple[float, str]] | None = None, round_num: int = 1) -> tuple[float, str]:
  617. """评估文本与原始问题o的相关度
  618. 采用两阶段评估 + 代码计算规则:
  619. 1. 动机维度评估(权重70%)
  620. 2. 品类维度评估(权重30%)
  621. 3. 应用规则A/B/C调整得分
  622. Args:
  623. text: 待评估的文本
  624. o: 原始问题
  625. cache: 评估缓存(可选),用于避免重复评估
  626. round_num: 轮次编号,第一轮使用 round1 prompt,后续使用标准 prompt
  627. Returns:
  628. tuple[float, str]: (最终相关度分数, 综合评估理由)
  629. """
  630. # 检查缓存
  631. if cache is not None and text in cache:
  632. cached_score, cached_reason = cache[text]
  633. print(f" ⚡ 缓存命中: {text} -> {cached_score:.2f}")
  634. return cached_score, cached_reason
  635. # 准备输入
  636. eval_input = f"""
  637. <原始问题>
  638. {o}
  639. </原始问题>
  640. <平台sug词条>
  641. {text}
  642. </平台sug词条>
  643. 请评估平台sug词条与原始问题的匹配度。
  644. """
  645. # 添加重试机制
  646. max_retries = 2
  647. last_error = None
  648. for attempt in range(max_retries):
  649. try:
  650. # 根据轮次选择不同的 motivation evaluator
  651. # 第一轮使用 round1 版本,后续使用标准版本
  652. selected_motivation_evaluator = motivation_evaluator_round1 if round_num == 1 else motivation_evaluator
  653. # 并发调用两个评估器
  654. motivation_task = Runner.run(selected_motivation_evaluator, eval_input)
  655. category_task = Runner.run(category_evaluator, eval_input)
  656. motivation_result, category_result = await asyncio.gather(
  657. motivation_task,
  658. category_task
  659. )
  660. # 获取评估结果
  661. motivation_eval: MotivationEvaluation = motivation_result.final_output
  662. category_eval: CategoryEvaluation = category_result.final_output
  663. # 提取得分
  664. motivation_score = motivation_eval.动机维度得分
  665. category_score = category_eval.品类维度得分
  666. # 计算基础得分
  667. base_score = motivation_score * 0.7 + category_score * 0.3
  668. # 应用规则计算最终得分
  669. final_score = calculate_final_score(motivation_score, category_score)
  670. # 组合评估理由
  671. core_motivation = motivation_eval.原始问题核心动机提取.简要说明核心动机
  672. motivation_reason = motivation_eval.简要说明动机维度相关度理由
  673. category_reason = category_eval.简要说明品类维度相关度理由
  674. combined_reason = (
  675. f"【核心动机】{core_motivation}\n"
  676. f"【动机维度 {motivation_score:.2f}】{motivation_reason}\n"
  677. f"【品类维度 {category_score:.2f}】{category_reason}\n"
  678. f"【基础得分 {base_score:.2f}】= 动机({motivation_score:.2f})*0.7 + 品类({category_score:.2f})*0.3\n"
  679. f"【最终得分 {final_score:.2f}】"
  680. )
  681. # 如果应用了规则,添加规则说明
  682. if final_score != base_score:
  683. if motivation_score < 0:
  684. combined_reason += "(应用规则C:动机负向决定机制)"
  685. elif motivation_score >= 0.8:
  686. combined_reason += "(应用规则A:动机高分保护机制)"
  687. elif motivation_score <= 0.2:
  688. combined_reason += "(应用规则B:动机低分限制机制)"
  689. # 存入缓存
  690. if cache is not None:
  691. cache[text] = (final_score, combined_reason)
  692. return final_score, combined_reason
  693. except Exception as e:
  694. last_error = e
  695. error_msg = str(e)
  696. if attempt < max_retries - 1:
  697. print(f" ⚠️ 评估失败 (尝试 {attempt+1}/{max_retries}): {error_msg[:150]}")
  698. print(f" 正在重试...")
  699. await asyncio.sleep(1) # 等待1秒后重试
  700. else:
  701. print(f" ❌ 评估失败 (已达最大重试次数): {error_msg[:150]}")
  702. # 所有重试失败后,返回默认值
  703. fallback_reason = f"评估失败(重试{max_retries}次): {str(last_error)[:200]}"
  704. print(f" 使用默认值: score=0.0, reason={fallback_reason[:100]}...")
  705. return 0.0, fallback_reason
  706. # ============================================================================
  707. # 核心流程函数
  708. # ============================================================================
  709. async def initialize(o: str, context: RunContext) -> tuple[list[Seg], list[Word], list[Q], list[Seed]]:
  710. """
  711. 初始化阶段
  712. Returns:
  713. (seg_list, word_list_1, q_list_1, seed_list)
  714. """
  715. print(f"\n{'='*60}")
  716. print(f"初始化阶段")
  717. print(f"{'='*60}")
  718. # 1. 分词:原始问题(o) ->分词-> seg_list
  719. print(f"\n[步骤1] 分词...")
  720. result = await Runner.run(word_segmenter, o)
  721. segmentation: WordSegmentation = result.final_output
  722. seg_list = []
  723. for word in segmentation.words:
  724. seg_list.append(Seg(text=word, from_o=o))
  725. print(f"分词结果: {[s.text for s in seg_list]}")
  726. print(f"分词理由: {segmentation.reasoning}")
  727. # 2. 分词评估:seg_list -> 每个seg与o进行评分(使用信号量限制并发数)
  728. print(f"\n[步骤2] 评估每个分词与原始问题的相关度...")
  729. MAX_CONCURRENT_SEG_EVALUATIONS = 5
  730. seg_semaphore = asyncio.Semaphore(MAX_CONCURRENT_SEG_EVALUATIONS)
  731. async def evaluate_seg(seg: Seg) -> Seg:
  732. async with seg_semaphore:
  733. # 初始化阶段的分词评估使用第一轮 prompt (round_num=1)
  734. seg.score_with_o, seg.reason = await evaluate_with_o(seg.text, o, context.evaluation_cache, round_num=1)
  735. return seg
  736. if seg_list:
  737. print(f" 开始评估 {len(seg_list)} 个分词(并发限制: {MAX_CONCURRENT_SEG_EVALUATIONS})...")
  738. eval_tasks = [evaluate_seg(seg) for seg in seg_list]
  739. await asyncio.gather(*eval_tasks)
  740. for seg in seg_list:
  741. print(f" {seg.text}: {seg.score_with_o:.2f}")
  742. # 3. 构建word_list_1: seg_list -> word_list_1(固定词库)
  743. print(f"\n[步骤3] 构建word_list_1(固定词库)...")
  744. word_list_1 = []
  745. for seg in seg_list:
  746. word_list_1.append(Word(
  747. text=seg.text,
  748. score_with_o=seg.score_with_o,
  749. from_o=o
  750. ))
  751. print(f"word_list_1(固定): {[w.text for w in word_list_1]}")
  752. # 4. 构建q_list_1:seg_list 作为 q_list_1
  753. print(f"\n[步骤4] 构建q_list_1...")
  754. q_list_1 = []
  755. for seg in seg_list:
  756. q_list_1.append(Q(
  757. text=seg.text,
  758. score_with_o=seg.score_with_o,
  759. reason=seg.reason,
  760. from_source="seg"
  761. ))
  762. print(f"q_list_1: {[q.text for q in q_list_1]}")
  763. # 5. 构建seed_list: seg_list -> seed_list
  764. print(f"\n[步骤5] 构建seed_list...")
  765. seed_list = []
  766. for seg in seg_list:
  767. seed_list.append(Seed(
  768. text=seg.text,
  769. added_words=[],
  770. from_type="seg",
  771. score_with_o=seg.score_with_o
  772. ))
  773. print(f"seed_list: {[s.text for s in seed_list]}")
  774. return seg_list, word_list_1, q_list_1, seed_list
  775. async def run_round(
  776. round_num: int,
  777. q_list: list[Q],
  778. word_list_1: list[Word],
  779. seed_list: list[Seed],
  780. o: str,
  781. context: RunContext,
  782. xiaohongshu_api: XiaohongshuSearchRecommendations,
  783. xiaohongshu_search: XiaohongshuSearch,
  784. sug_threshold: float = 0.7
  785. ) -> tuple[list[Q], list[Seed], list[Search]]:
  786. """
  787. 运行一轮
  788. Args:
  789. round_num: 轮次编号
  790. q_list: 当前轮的q列表
  791. word_list_1: 固定的词库(第0轮分词结果)
  792. seed_list: 当前的seed列表
  793. o: 原始问题
  794. context: 运行上下文
  795. xiaohongshu_api: 建议词API
  796. xiaohongshu_search: 搜索API
  797. sug_threshold: suggestion的阈值
  798. Returns:
  799. (q_list_next, seed_list_next, search_list)
  800. """
  801. print(f"\n{'='*60}")
  802. print(f"第{round_num}轮")
  803. print(f"{'='*60}")
  804. round_data = {
  805. "round_num": round_num,
  806. "input_q_list": [{"text": q.text, "score": q.score_with_o, "type": "query"} for q in q_list],
  807. "input_word_list_1_size": len(word_list_1),
  808. "input_seed_list_size": len(seed_list)
  809. }
  810. # 1. 请求sug:q_list -> 每个q请求sug接口 -> sug_list_list
  811. print(f"\n[步骤1] 为每个q请求建议词...")
  812. sug_list_list = [] # list of list
  813. for q in q_list:
  814. print(f"\n 处理q: {q.text}")
  815. suggestions = xiaohongshu_api.get_recommendations(keyword=q.text)
  816. q_sug_list = []
  817. if suggestions:
  818. print(f" 获取到 {len(suggestions)} 个建议词")
  819. for sug_text in suggestions:
  820. sug = Sug(
  821. text=sug_text,
  822. from_q=QFromQ(text=q.text, score_with_o=q.score_with_o)
  823. )
  824. q_sug_list.append(sug)
  825. else:
  826. print(f" 未获取到建议词")
  827. sug_list_list.append(q_sug_list)
  828. # 2. sug评估:sug_list_list -> 每个sug与o进行评分(并发)
  829. print(f"\n[步骤2] 评估每个建议词与原始问题的相关度...")
  830. # 2.1 收集所有需要评估的sug,并记录它们所属的q
  831. all_sugs = []
  832. sug_to_q_map = {} # 记录每个sug属于哪个q
  833. for i, q_sug_list in enumerate(sug_list_list):
  834. if q_sug_list:
  835. q_text = q_list[i].text
  836. for sug in q_sug_list:
  837. all_sugs.append(sug)
  838. sug_to_q_map[id(sug)] = q_text
  839. # 2.2 并发评估所有sug(使用信号量限制并发数)
  840. # 每个 evaluate_sug 内部会并发调用 2 个 LLM,所以这里限制为 5,实际并发 LLM 请求为 10
  841. MAX_CONCURRENT_EVALUATIONS = 5
  842. semaphore = asyncio.Semaphore(MAX_CONCURRENT_EVALUATIONS)
  843. async def evaluate_sug(sug: Sug) -> Sug:
  844. async with semaphore: # 限制并发数
  845. # 根据轮次选择 prompt: 第一轮使用 round1 prompt,后续使用标准 prompt
  846. sug.score_with_o, sug.reason = await evaluate_with_o(sug.text, o, context.evaluation_cache, round_num=round_num)
  847. return sug
  848. if all_sugs:
  849. print(f" 开始评估 {len(all_sugs)} 个建议词(并发限制: {MAX_CONCURRENT_EVALUATIONS})...")
  850. eval_tasks = [evaluate_sug(sug) for sug in all_sugs]
  851. await asyncio.gather(*eval_tasks)
  852. # 2.3 打印结果并组织到sug_details
  853. sug_details = {} # 保存每个Q对应的sug列表
  854. for i, q_sug_list in enumerate(sug_list_list):
  855. if q_sug_list:
  856. q_text = q_list[i].text
  857. print(f"\n 来自q '{q_text}' 的建议词:")
  858. sug_details[q_text] = []
  859. for sug in q_sug_list:
  860. print(f" {sug.text}: {sug.score_with_o:.2f}")
  861. # 保存到sug_details
  862. sug_details[q_text].append({
  863. "text": sug.text,
  864. "score": sug.score_with_o,
  865. "reason": sug.reason,
  866. "type": "sug"
  867. })
  868. # 3. search_list构建
  869. print(f"\n[步骤3] 构建search_list(阈值>{sug_threshold})...")
  870. search_list = []
  871. high_score_sugs = [sug for sug in all_sugs if sug.score_with_o > sug_threshold]
  872. if high_score_sugs:
  873. print(f" 找到 {len(high_score_sugs)} 个高分建议词")
  874. # 并发搜索
  875. async def search_for_sug(sug: Sug) -> Search:
  876. print(f" 搜索: {sug.text}")
  877. try:
  878. search_result = xiaohongshu_search.search(keyword=sug.text)
  879. result_str = search_result.get("result", "{}")
  880. if isinstance(result_str, str):
  881. result_data = json.loads(result_str)
  882. else:
  883. result_data = result_str
  884. notes = result_data.get("data", {}).get("data", [])
  885. post_list = []
  886. for note in notes[:10]: # 只取前10个
  887. post = process_note_data(note)
  888. post_list.append(post)
  889. print(f" → 找到 {len(post_list)} 个帖子")
  890. return Search(
  891. text=sug.text,
  892. score_with_o=sug.score_with_o,
  893. from_q=sug.from_q,
  894. post_list=post_list
  895. )
  896. except Exception as e:
  897. print(f" ✗ 搜索失败: {e}")
  898. return Search(
  899. text=sug.text,
  900. score_with_o=sug.score_with_o,
  901. from_q=sug.from_q,
  902. post_list=[]
  903. )
  904. search_tasks = [search_for_sug(sug) for sug in high_score_sugs]
  905. search_list = await asyncio.gather(*search_tasks)
  906. else:
  907. print(f" 没有高分建议词,search_list为空")
  908. # 4. 构建q_list_next
  909. print(f"\n[步骤4] 构建q_list_next...")
  910. q_list_next = []
  911. existing_q_texts = set() # 用于去重
  912. add_word_details = {} # 保存每个seed对应的组合词列表
  913. all_seed_combinations = [] # 保存本轮所有seed的组合词(用于后续构建seed_list_next)
  914. # 4.1 对于seed_list中的每个seed,从word_list_1中选词组合,产生Top 5
  915. print(f"\n 4.1 为每个seed加词(产生Top 5组合)...")
  916. for seed in seed_list:
  917. print(f"\n 处理seed: {seed.text}")
  918. # 从固定词库word_list_1筛选候选词
  919. candidate_words = []
  920. for word in word_list_1:
  921. # 检查词是否已在seed中
  922. if word.text in seed.text:
  923. continue
  924. # 检查词是否已被添加过
  925. if word.text in seed.added_words:
  926. continue
  927. candidate_words.append(word)
  928. if not candidate_words:
  929. print(f" 没有可用的候选词")
  930. continue
  931. print(f" 候选词数量: {len(candidate_words)}")
  932. # 调用Agent一次性选择并组合Top 5(添加重试机制)
  933. candidate_words_text = ', '.join([w.text for w in candidate_words])
  934. selection_input = f"""
  935. <原始问题>
  936. {o}
  937. </原始问题>
  938. <当前Seed>
  939. {seed.text}
  940. </当前Seed>
  941. <候选词列表>
  942. {candidate_words_text}
  943. </候选词列表>
  944. 请从候选词列表中选择最多5个最合适的词,分别与当前seed组合成新的query。
  945. """
  946. # 重试机制
  947. max_retries = 2
  948. selection_result = None
  949. for attempt in range(max_retries):
  950. try:
  951. result = await Runner.run(word_selector, selection_input)
  952. selection_result = result.final_output
  953. break # 成功则跳出
  954. except Exception as e:
  955. error_msg = str(e)
  956. if attempt < max_retries - 1:
  957. print(f" ⚠️ 选词失败 (尝试 {attempt+1}/{max_retries}): {error_msg[:100]}")
  958. await asyncio.sleep(1)
  959. else:
  960. print(f" ❌ 选词失败,跳过该seed: {error_msg[:100]}")
  961. break
  962. if selection_result is None:
  963. print(f" 跳过seed: {seed.text}")
  964. continue
  965. print(f" Agent选择了 {len(selection_result.combinations)} 个组合")
  966. print(f" 整体选择思路: {selection_result.overall_reasoning}")
  967. # 并发评估所有组合的相关度
  968. async def evaluate_combination(comb: WordCombination) -> dict:
  969. combined = comb.combined_query
  970. # 验证:组合结果必须包含完整的seed和word
  971. # 检查是否包含seed的所有字符
  972. seed_chars_in_combined = all(char in combined for char in seed.text)
  973. # 检查是否包含word的所有字符
  974. word_chars_in_combined = all(char in combined for char in comb.selected_word)
  975. if not seed_chars_in_combined or not word_chars_in_combined:
  976. print(f" ⚠️ 警告:组合不完整")
  977. print(f" Seed: {seed.text}")
  978. print(f" Word: {comb.selected_word}")
  979. print(f" 组合: {combined}")
  980. print(f" 包含完整seed? {seed_chars_in_combined}")
  981. print(f" 包含完整word? {word_chars_in_combined}")
  982. # 返回极低分数,让这个组合不会被选中
  983. return {
  984. 'word': comb.selected_word,
  985. 'query': combined,
  986. 'score': -1.0, # 极低分数
  987. 'reason': f"组合不完整:缺少seed或word的部分内容",
  988. 'reasoning': comb.reasoning
  989. }
  990. # 正常评估,根据轮次选择 prompt
  991. score, reason = await evaluate_with_o(combined, o, context.evaluation_cache, round_num=round_num)
  992. return {
  993. 'word': comb.selected_word,
  994. 'query': combined,
  995. 'score': score,
  996. 'reason': reason,
  997. 'reasoning': comb.reasoning
  998. }
  999. eval_tasks = [evaluate_combination(comb) for comb in selection_result.combinations]
  1000. top_5 = await asyncio.gather(*eval_tasks)
  1001. print(f" 评估完成,得到 {len(top_5)} 个组合")
  1002. # 将Top 5全部加入q_list_next(去重检查 + 得分过滤)
  1003. for comb in top_5:
  1004. # 得分过滤:只有得分大于种子得分的组合词才加入下一轮
  1005. if comb['score'] <= seed.score_with_o:
  1006. print(f" ⊗ 跳过低分: {comb['query']} (分数{comb['score']:.2f} ≤ 种子{seed.score_with_o:.2f})")
  1007. continue
  1008. # 去重检查
  1009. if comb['query'] in existing_q_texts:
  1010. print(f" ⊗ 跳过重复: {comb['query']}")
  1011. continue
  1012. print(f" ✓ {comb['query']} (分数: {comb['score']:.2f} > 种子: {seed.score_with_o:.2f})")
  1013. new_q = Q(
  1014. text=comb['query'],
  1015. score_with_o=comb['score'],
  1016. reason=comb['reason'],
  1017. from_source="add"
  1018. )
  1019. q_list_next.append(new_q)
  1020. existing_q_texts.add(comb['query']) # 记录到去重集合
  1021. # 记录已添加的词
  1022. seed.added_words.append(comb['word'])
  1023. # 保存到add_word_details
  1024. add_word_details[seed.text] = [
  1025. {
  1026. "text": comb['query'],
  1027. "score": comb['score'],
  1028. "reason": comb['reason'],
  1029. "selected_word": comb['word'],
  1030. "seed_score": seed.score_with_o, # 添加原始种子的得分
  1031. "type": "add"
  1032. }
  1033. for comb in top_5
  1034. ]
  1035. # 保存到all_seed_combinations(用于构建seed_list_next)
  1036. # 附加seed_score,用于后续过滤
  1037. for comb in top_5:
  1038. comb['seed_score'] = seed.score_with_o
  1039. all_seed_combinations.extend(top_5)
  1040. # 4.2 对于sug_list_list中,每个sug大于来自的query分数,加到q_list_next(去重检查)
  1041. print(f"\n 4.2 将高分sug加入q_list_next...")
  1042. for sug in all_sugs:
  1043. if sug.from_q and sug.score_with_o > sug.from_q.score_with_o:
  1044. # 去重检查
  1045. if sug.text in existing_q_texts:
  1046. print(f" ⊗ 跳过重复: {sug.text}")
  1047. continue
  1048. new_q = Q(
  1049. text=sug.text,
  1050. score_with_o=sug.score_with_o,
  1051. reason=sug.reason,
  1052. from_source="sug"
  1053. )
  1054. q_list_next.append(new_q)
  1055. existing_q_texts.add(sug.text) # 记录到去重集合
  1056. print(f" ✓ {sug.text} (分数: {sug.score_with_o:.2f} > {sug.from_q.score_with_o:.2f})")
  1057. # 5. 构建seed_list_next(关键修改:不保留上一轮的seed)
  1058. print(f"\n[步骤5] 构建seed_list_next(不保留上轮seed)...")
  1059. seed_list_next = []
  1060. existing_seed_texts = set()
  1061. # 5.1 加入本轮所有组合词(只加入得分提升的)
  1062. print(f" 5.1 加入本轮所有组合词(得分过滤)...")
  1063. for comb in all_seed_combinations:
  1064. # 得分过滤:只有得分大于种子得分的组合词才作为下一轮种子
  1065. seed_score = comb.get('seed_score', 0)
  1066. if comb['score'] <= seed_score:
  1067. print(f" ⊗ 跳过低分: {comb['query']} (分数{comb['score']:.2f} ≤ 种子{seed_score:.2f})")
  1068. continue
  1069. if comb['query'] not in existing_seed_texts:
  1070. new_seed = Seed(
  1071. text=comb['query'],
  1072. added_words=[], # 新seed的added_words清空
  1073. from_type="add",
  1074. score_with_o=comb['score']
  1075. )
  1076. seed_list_next.append(new_seed)
  1077. existing_seed_texts.add(comb['query'])
  1078. print(f" ✓ {comb['query']} (分数: {comb['score']:.2f} > 种子: {seed_score:.2f})")
  1079. # 5.2 加入高分sug
  1080. print(f" 5.2 加入高分sug...")
  1081. for sug in all_sugs:
  1082. # sug分数 > 对应query分数
  1083. if sug.from_q and sug.score_with_o > sug.from_q.score_with_o and sug.text not in existing_seed_texts:
  1084. new_seed = Seed(
  1085. text=sug.text,
  1086. added_words=[],
  1087. from_type="sug",
  1088. score_with_o=sug.score_with_o
  1089. )
  1090. seed_list_next.append(new_seed)
  1091. existing_seed_texts.add(sug.text)
  1092. print(f" ✓ {sug.text} (分数: {sug.score_with_o:.2f} > 来源query: {sug.from_q.score_with_o:.2f})")
  1093. # 序列化搜索结果数据(包含帖子详情)
  1094. search_results_data = []
  1095. for search in search_list:
  1096. search_results_data.append({
  1097. "text": search.text,
  1098. "score_with_o": search.score_with_o,
  1099. "post_list": [
  1100. {
  1101. "note_id": post.note_id,
  1102. "note_url": post.note_url,
  1103. "title": post.title,
  1104. "body_text": post.body_text,
  1105. "images": post.images,
  1106. "interact_info": post.interact_info
  1107. }
  1108. for post in search.post_list
  1109. ]
  1110. })
  1111. # 记录本轮数据
  1112. round_data.update({
  1113. "sug_count": len(all_sugs),
  1114. "high_score_sug_count": len(high_score_sugs),
  1115. "search_count": len(search_list),
  1116. "total_posts": sum(len(s.post_list) for s in search_list),
  1117. "q_list_next_size": len(q_list_next),
  1118. "seed_list_next_size": len(seed_list_next),
  1119. "total_combinations": len(all_seed_combinations),
  1120. "output_q_list": [{"text": q.text, "score": q.score_with_o, "reason": q.reason, "from": q.from_source, "type": "query"} for q in q_list_next],
  1121. "seed_list_next": [{"text": seed.text, "from": seed.from_type, "score": seed.score_with_o} for seed in seed_list_next],
  1122. "sug_details": sug_details,
  1123. "add_word_details": add_word_details,
  1124. "search_results": search_results_data
  1125. })
  1126. context.rounds.append(round_data)
  1127. print(f"\n本轮总结:")
  1128. print(f" 建议词数量: {len(all_sugs)}")
  1129. print(f" 高分建议词: {len(high_score_sugs)}")
  1130. print(f" 搜索数量: {len(search_list)}")
  1131. print(f" 帖子总数: {sum(len(s.post_list) for s in search_list)}")
  1132. print(f" 组合词数量: {len(all_seed_combinations)}")
  1133. print(f" 下轮q数量: {len(q_list_next)}")
  1134. print(f" 下轮seed数量: {len(seed_list_next)}")
  1135. return q_list_next, seed_list_next, search_list
  1136. async def iterative_loop(
  1137. context: RunContext,
  1138. max_rounds: int = 2,
  1139. sug_threshold: float = 0.7
  1140. ):
  1141. """主迭代循环"""
  1142. print(f"\n{'='*60}")
  1143. print(f"开始迭代循环")
  1144. print(f"最大轮数: {max_rounds}")
  1145. print(f"sug阈值: {sug_threshold}")
  1146. print(f"{'='*60}")
  1147. # 初始化
  1148. seg_list, word_list_1, q_list, seed_list = await initialize(context.o, context)
  1149. # API实例
  1150. xiaohongshu_api = XiaohongshuSearchRecommendations()
  1151. xiaohongshu_search = XiaohongshuSearch()
  1152. # 保存初始化数据
  1153. context.rounds.append({
  1154. "round_num": 0,
  1155. "type": "initialization",
  1156. "seg_list": [{"text": s.text, "score": s.score_with_o, "reason": s.reason, "type": "seg"} for s in seg_list],
  1157. "word_list_1": [{"text": w.text, "score": w.score_with_o} for w in word_list_1],
  1158. "q_list_1": [{"text": q.text, "score": q.score_with_o, "reason": q.reason, "type": "query"} for q in q_list],
  1159. "seed_list": [{"text": s.text, "from_type": s.from_type, "score": s.score_with_o, "type": "seed"} for s in seed_list]
  1160. })
  1161. # 收集所有搜索结果
  1162. all_search_list = []
  1163. # 迭代
  1164. round_num = 1
  1165. while q_list and round_num <= max_rounds:
  1166. q_list, seed_list, search_list = await run_round(
  1167. round_num=round_num,
  1168. q_list=q_list,
  1169. word_list_1=word_list_1, # 传递固定词库
  1170. seed_list=seed_list,
  1171. o=context.o,
  1172. context=context,
  1173. xiaohongshu_api=xiaohongshu_api,
  1174. xiaohongshu_search=xiaohongshu_search,
  1175. sug_threshold=sug_threshold
  1176. )
  1177. all_search_list.extend(search_list)
  1178. round_num += 1
  1179. print(f"\n{'='*60}")
  1180. print(f"迭代完成")
  1181. print(f" 总轮数: {round_num - 1}")
  1182. print(f" 总搜索次数: {len(all_search_list)}")
  1183. print(f" 总帖子数: {sum(len(s.post_list) for s in all_search_list)}")
  1184. print(f"{'='*60}")
  1185. return all_search_list
  1186. # ============================================================================
  1187. # 主函数
  1188. # ============================================================================
  1189. async def main(input_dir: str, max_rounds: int = 2, sug_threshold: float = 0.5, visualize: bool = False):
  1190. """主函数"""
  1191. current_time, log_url = set_trace()
  1192. # 读取输入
  1193. input_context_file = os.path.join(input_dir, 'context.md')
  1194. input_q_file = os.path.join(input_dir, 'q.md')
  1195. c = read_file_as_string(input_context_file) # 原始需求
  1196. o = read_file_as_string(input_q_file) # 原始问题
  1197. # 版本信息
  1198. version = os.path.basename(__file__)
  1199. version_name = os.path.splitext(version)[0]
  1200. # 日志目录
  1201. log_dir = os.path.join(input_dir, "output", version_name, current_time)
  1202. # 创建运行上下文
  1203. run_context = RunContext(
  1204. version=version,
  1205. input_files={
  1206. "input_dir": input_dir,
  1207. "context_file": input_context_file,
  1208. "q_file": input_q_file,
  1209. },
  1210. c=c,
  1211. o=o,
  1212. log_dir=log_dir,
  1213. log_url=log_url,
  1214. )
  1215. # 创建日志目录
  1216. os.makedirs(run_context.log_dir, exist_ok=True)
  1217. # 配置日志文件
  1218. log_file_path = os.path.join(run_context.log_dir, "run.log")
  1219. log_file = open(log_file_path, 'w', encoding='utf-8')
  1220. # 重定向stdout到TeeLogger(同时输出到控制台和文件)
  1221. original_stdout = sys.stdout
  1222. sys.stdout = TeeLogger(original_stdout, log_file)
  1223. try:
  1224. print(f"📝 日志文件: {log_file_path}")
  1225. print(f"{'='*60}\n")
  1226. # 执行迭代
  1227. all_search_list = await iterative_loop(
  1228. run_context,
  1229. max_rounds=max_rounds,
  1230. sug_threshold=sug_threshold
  1231. )
  1232. # 格式化输出
  1233. output = f"原始需求:{run_context.c}\n"
  1234. output += f"原始问题:{run_context.o}\n"
  1235. output += f"总搜索次数:{len(all_search_list)}\n"
  1236. output += f"总帖子数:{sum(len(s.post_list) for s in all_search_list)}\n"
  1237. output += "\n" + "="*60 + "\n"
  1238. if all_search_list:
  1239. output += "【搜索结果】\n\n"
  1240. for idx, search in enumerate(all_search_list, 1):
  1241. output += f"{idx}. 搜索词: {search.text} (分数: {search.score_with_o:.2f})\n"
  1242. output += f" 帖子数: {len(search.post_list)}\n"
  1243. if search.post_list:
  1244. for post_idx, post in enumerate(search.post_list[:3], 1): # 只显示前3个
  1245. output += f" {post_idx}) {post.title}\n"
  1246. output += f" URL: {post.note_url}\n"
  1247. output += "\n"
  1248. else:
  1249. output += "未找到搜索结果\n"
  1250. run_context.final_output = output
  1251. print(f"\n{'='*60}")
  1252. print("最终结果")
  1253. print(f"{'='*60}")
  1254. print(output)
  1255. # 保存上下文文件
  1256. context_file_path = os.path.join(run_context.log_dir, "run_context.json")
  1257. context_dict = run_context.model_dump()
  1258. with open(context_file_path, "w", encoding="utf-8") as f:
  1259. json.dump(context_dict, f, ensure_ascii=False, indent=2)
  1260. print(f"\nRunContext saved to: {context_file_path}")
  1261. # 保存详细的搜索结果
  1262. search_results_path = os.path.join(run_context.log_dir, "search_results.json")
  1263. search_results_data = [s.model_dump() for s in all_search_list]
  1264. with open(search_results_path, "w", encoding="utf-8") as f:
  1265. json.dump(search_results_data, f, ensure_ascii=False, indent=2)
  1266. print(f"Search results saved to: {search_results_path}")
  1267. # 可视化
  1268. if visualize:
  1269. import subprocess
  1270. output_html = os.path.join(run_context.log_dir, "visualization.html")
  1271. print(f"\n🎨 生成可视化HTML...")
  1272. # 获取绝对路径
  1273. abs_context_file = os.path.abspath(context_file_path)
  1274. abs_output_html = os.path.abspath(output_html)
  1275. # 运行可视化脚本
  1276. result = subprocess.run([
  1277. "node",
  1278. "visualization/sug_v6_1_2_8/index.js",
  1279. abs_context_file,
  1280. abs_output_html
  1281. ])
  1282. if result.returncode == 0:
  1283. print(f"✅ 可视化已生成: {output_html}")
  1284. else:
  1285. print(f"❌ 可视化生成失败")
  1286. finally:
  1287. # 恢复stdout
  1288. sys.stdout = original_stdout
  1289. log_file.close()
  1290. print(f"\n📝 运行日志已保存: {log_file_path}")
  1291. if __name__ == "__main__":
  1292. parser = argparse.ArgumentParser(description="搜索query优化工具 - v6.1.2.115 广度遍历版")
  1293. parser.add_argument(
  1294. "--input-dir",
  1295. type=str,
  1296. default="input/旅游-逸趣玩旅行/如何获取能体现川西秋季特色的高质量风光摄影素材?",
  1297. help="输入目录路径,默认: input/旅游-逸趣玩旅行/如何获取能体现川西秋季特色的高质量风光摄影素材?"
  1298. )
  1299. parser.add_argument(
  1300. "--max-rounds",
  1301. type=int,
  1302. default=4,
  1303. help="最大轮数,默认: 4"
  1304. )
  1305. parser.add_argument(
  1306. "--sug-threshold",
  1307. type=float,
  1308. default=0.7,
  1309. help="suggestion阈值,默认: 0.7"
  1310. )
  1311. parser.add_argument(
  1312. "--visualize",
  1313. action="store_true",
  1314. default=True,
  1315. help="运行完成后自动生成可视化HTML"
  1316. )
  1317. args = parser.parse_args()
  1318. asyncio.run(main(args.input_dir, max_rounds=args.max_rounds, sug_threshold=args.sug_threshold, visualize=args.visualize))