sug_v4_with_yx.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. import asyncio
  2. import json
  3. import os
  4. import argparse
  5. from datetime import datetime
  6. from agents import Agent, Runner, function_tool, AgentOutputSchema
  7. from lib.my_trace import set_trace
  8. from typing import Literal
  9. from pydantic import BaseModel, Field
  10. from lib.utils import read_file_as_string
  11. from script.search_recommendations.xiaohongshu_search_recommendations import XiaohongshuSearchRecommendations
  12. from agents import Agent, RunContextWrapper, Runner, function_tool
  13. from pydantic import BaseModel, Field
  14. class RunContext(BaseModel):
  15. version: str = Field(..., description="当前运行的脚本版本(文件名)")
  16. input_files: dict[str, str] = Field(..., description="输入文件路径映射,如 {'context_file': '...', 'q_file': '...'}")
  17. q_with_context: str
  18. q_context: str
  19. q: str
  20. log_url: str
  21. log_dir: str
  22. # 问题标注结果 - 直接用字符串记录
  23. question_annotation: str | None = Field(default=None, description="问题的标注结果,类似NER格式")
  24. # 中间数据记录 - 按时间顺序记录所有操作
  25. operations_history: list[dict] = Field(default_factory=list, description="记录所有操作的历史,包括 get_query_suggestions 和 modify_query")
  26. # 最终输出结果
  27. final_output: str | None = Field(default=None, description="Agent的最终输出结果")
  28. # 问题标注 Agent - 三层标注
  29. question_annotation_instructions = """
  30. 你是搜索需求分析专家。给定问题(含需求背景),在原文上标注三层:本质、硬性、软性。
  31. ## 三层结构
  32. **[本质]** - 问题的核心意图,改变后是完全不同的问题
  33. - 如何获取、教程、推荐、作品、测评等
  34. **[硬]** - 在本质意图下,必须满足的约束
  35. - 地域、时间、对象、质量要求等
  36. **[软]** - 可有可无的修饰
  37. - 能体现、特色、快速、简单等
  38. ## 输出格式
  39. 词语[本质-描述]、词语[硬-描述]、词语[软-描述]
  40. ## 示例
  41. 输入:如何获取能体现川西秋季特色的高质量风光摄影素材?
  42. 输出:如何获取[本质-找方法] 川西[硬-地域] 秋季[硬-季节] 高质量[硬-质量] 风光摄影素材[硬-对象] 能体现[软-修饰] 特色[软-修饰]
  43. 输入:PS抠图教程
  44. 输出:PS[硬-工具] 抠图[硬-需求] 教程[本质-学习]
  45. 输入:川西秋季风光摄影作品
  46. 输出:川西[硬-地域] 秋季[硬-季节] 风光摄影[硬-对象] 作品[本质-欣赏]
  47. ## 注意
  48. - 只输出标注后的字符串
  49. - 结合需求背景判断意图
  50. """.strip()
  51. question_annotator = Agent[None](
  52. name="问题标注专家",
  53. instructions=question_annotation_instructions,
  54. )
  55. eval_instructions = """
  56. 你是搜索query评估专家。给定原始问题标注(三层)和推荐query,评估三个分数。
  57. ## 评估目标
  58. 用这个推荐query搜索,能否找到满足原始需求的内容?
  59. ## 三层评分
  60. ### 1. essence_score(本质/意图)= 0 或 1
  61. 推荐query的本质/意图是否与原问题一致?
  62. **原问题标注中的[本质-XXX]:**
  63. - 找方法/如何获取 → 推荐词应该是方法/获取途径
  64. - 教程/学习 → 推荐词应该是教程/教学
  65. - 作品/欣赏 → 推荐词应该是作品展示
  66. - 工具/推荐 → 推荐词应该是工具推荐
  67. **评分:**
  68. - 1 = 本质一致
  69. - 0 = 本质改变(完全答非所问)
  70. **示例:**
  71. - 原问题:如何获取[本质-找方法]...素材
  72. - 推荐词:素材获取方法 → essence=1
  73. - 推荐词:素材推荐 → essence=1(都是获取途径)
  74. - 推荐词:素材作品 → essence=0(找方法≠看作品)
  75. ### 2. hard_score(硬性约束)= 0 或 1
  76. 在本质一致的前提下,是否满足所有硬性约束?
  77. **原问题标注中的[硬-XXX]:**地域、时间、对象、质量、工具(如果用户明确要求)等
  78. **评分:**
  79. - 1 = 所有硬性约束都满足
  80. - 0 = 任一硬性约束不满足
  81. **示例:**
  82. - 原问题:川西[硬-地域] 秋季[硬-季节] 高质量[硬-质量] 风光摄影[硬-对象]
  83. - 推荐词:川西秋季风光摄影 → hard=1
  84. - 推荐词:四川秋季风光摄影 → hard=0(地域泛化:川西→四川)
  85. - 推荐词:川西风光摄影 → hard=0(丢失季节)
  86. ### 3. soft_score(软性修饰)= 0-1
  87. 软性修饰词保留了多少?
  88. **原问题标注中的[软-XXX]:**修饰词、非关键限定等
  89. **评分参考:**
  90. - 1.0 = 完整保留
  91. - 0.7-0.9 = 保留核心
  92. - 0.4-0.6 = 部分丢失
  93. - 0-0.3 = 大量丢失
  94. ## 示例
  95. **原问题标注:** 如何获取[本质-找方法] 川西[硬-地域] 秋季[硬-季节] 高质量[硬-质量] 风光摄影素材[硬-对象] 能体现[软-修饰] 特色[软-修饰]
  96. **推荐query1:** 川西秋季风光摄影素材视频
  97. - essence_score=0(找方法→找素材本身,本质变了)
  98. - hard_score=1(地域、季节、对象都符合)
  99. - soft_score=0.5(丢失"高质量")
  100. - reason: 本质改变,用户要找获取素材的方法,推荐词是素材内容本身
  101. **推荐query2:** 川西秋季风光摄影素材网站推荐
  102. - essence_score=1(找方法→推荐网站,本质一致)
  103. - hard_score=1(所有硬性约束满足)
  104. - soft_score=0.8(保留核心,"高质量"未明确但推荐通常筛选过)
  105. - reason: 本质一致,硬性约束满足,软性略有丢失但可接受
  106. ## 注意
  107. - essence=0 直接拒绝,不管hard/soft多高
  108. - essence=1, hard=0 也要拒绝
  109. - essence=1, hard=1 才看soft_score
  110. """.strip()
  111. class EvaluationFeedback(BaseModel):
  112. """评估反馈模型 - 三层评分"""
  113. essence_score: Literal[0, 1] = Field(..., description="本质/意图匹配度,0或1。1=问题本质/意图一致,0=本质改变")
  114. hard_score: Literal[0, 1] = Field(..., description="硬性约束匹配度,0或1。1=所有硬性约束都满足,0=任一硬性约束不满足")
  115. soft_score: float = Field(..., description="软性修饰完整度,0-1的浮点数。1.0=完整保留,0.7-0.9=保留核心,0.4-0.6=泛化较大,0-0.3=大量丢失")
  116. reason: str = Field(..., description="评估理由,包括:1)本质/意图是否一致 2)硬性约束是否满足 3)软性修饰保留情况 4)搜索预期")
  117. evaluator = Agent[None](
  118. name="评估专家",
  119. instructions=eval_instructions,
  120. output_type=EvaluationFeedback,
  121. )
  122. @function_tool
  123. async def get_query_suggestions(wrapper: RunContextWrapper[RunContext], query: str):
  124. """Fetch search recommendations from Xiaohongshu."""
  125. # 1. 首次调用时,先标注问题(带需求背景)
  126. if wrapper.context.question_annotation is None:
  127. print("正在标注问题...")
  128. annotation_result = await Runner.run(question_annotator, wrapper.context.q_with_context)
  129. wrapper.context.question_annotation = str(annotation_result.final_output)
  130. print(f"问题标注完成:{wrapper.context.question_annotation}")
  131. # 2. 获取推荐词
  132. xiaohongshu_api = XiaohongshuSearchRecommendations()
  133. query_suggestions = xiaohongshu_api.get_recommendations(keyword=query)
  134. print(f"获取到 {len(query_suggestions) if query_suggestions else 0} 个推荐词:{query_suggestions}")
  135. # 3. 评估推荐词(三层评分)
  136. async def evaluate_single_query(q_sug: str):
  137. """Evaluate a single query suggestion."""
  138. eval_input = f"""
  139. <原始问题标注(三层)>
  140. {wrapper.context.question_annotation}
  141. </原始问题标注(三层)>
  142. <待评估的推荐query>
  143. {q_sug}
  144. </待评估的推荐query>
  145. 请评估该推荐query的三个分数:
  146. 1. essence_score: 本质/意图是否一致(0或1)
  147. 2. hard_score: 硬性约束是否满足(0或1)
  148. 3. soft_score: 软性修饰保留程度(0-1)
  149. 4. reason: 详细的评估理由
  150. """
  151. evaluator_result = await Runner.run(evaluator, eval_input)
  152. result: EvaluationFeedback = evaluator_result.final_output
  153. return {
  154. "query": q_sug,
  155. "essence_score": result.essence_score,
  156. "hard_score": result.hard_score,
  157. "soft_score": result.soft_score,
  158. "reason": result.reason,
  159. }
  160. # 并发执行所有评估任务
  161. res = []
  162. if query_suggestions:
  163. res = await asyncio.gather(*[evaluate_single_query(q_sug) for q_sug in query_suggestions])
  164. else:
  165. res = '未返回任何推荐词'
  166. # 记录到 RunContext
  167. wrapper.context.operations_history.append({
  168. "operation_type": "get_query_suggestions",
  169. "timestamp": datetime.now().isoformat(),
  170. "query": query,
  171. "suggestions": query_suggestions,
  172. "evaluations": res,
  173. })
  174. return res
  175. @function_tool
  176. def modify_query(wrapper: RunContextWrapper[RunContext], original_query: str, operation_type: str, new_query: str, reason: str):
  177. """
  178. Modify the search query with a specific operation.
  179. Args:
  180. original_query: The original query before modification
  181. operation_type: Type of modification - must be one of: "简化", "扩展", "替换", "组合"
  182. new_query: The modified query after applying the operation
  183. reason: Detailed explanation of why this modification was made and what insight from previous suggestions led to this change
  184. Returns:
  185. A dict containing the modification record and the new query to use for next search
  186. """
  187. operation_types = ["简化", "扩展", "替换", "组合"]
  188. if operation_type not in operation_types:
  189. return {
  190. "status": "error",
  191. "message": f"Invalid operation_type. Must be one of: {', '.join(operation_types)}"
  192. }
  193. modification_record = {
  194. "original_query": original_query,
  195. "operation_type": operation_type,
  196. "new_query": new_query,
  197. "reason": reason,
  198. }
  199. # 记录到 RunContext
  200. wrapper.context.operations_history.append({
  201. "operation_type": "modify_query",
  202. "timestamp": datetime.now().isoformat(),
  203. "modification_type": operation_type,
  204. "original_query": original_query,
  205. "new_query": new_query,
  206. "reason": reason,
  207. })
  208. return {
  209. "status": "success",
  210. "modification_record": modification_record,
  211. "new_query": new_query,
  212. "message": f"Query modified successfully. Use '{new_query}' for the next search."
  213. }
  214. instructions = """
  215. 你是一个专业的搜索query优化专家,擅长通过动态探索找到最符合用户搜索习惯的query。
  216. ## 核心任务
  217. 给定原始问题,通过迭代调用搜索推荐接口(get_query_suggestions),找到满足硬性要求且尽量保留软性信息的推荐query。
  218. ## 重要说明
  219. - **你不需要自己评估query的适配性**
  220. - get_query_suggestions 函数会:
  221. 1. 首次调用时自动标注问题(三层:本质、硬性、软性)
  222. 2. 对每个推荐词进行三维度评估
  223. - 返回结果包含:
  224. - **query**:推荐词
  225. - **essence_score**:本质/意图匹配度(0或1),0=本质改变,1=本质一致
  226. - **hard_score**:硬性约束匹配度(0或1),0=不满足约束,1=满足所有约束
  227. - **soft_score**:软性修饰完整度(0-1),越高表示保留的信息越完整
  228. - **reason**:详细的评估理由
  229. - **你的职责是分析评估结果,做出决策和策略调整**
  230. ## 防止幻觉 - 关键原则
  231. - **严禁编造数据**:只能基于 get_query_suggestions 实际返回的结果进行分析
  232. - **空结果处理**:如果返回的列表为空([]),必须明确说明"未返回任何推荐词"
  233. - **不要猜测**:在 modify_query 的 reason 中,不能引用不存在的推荐词或评分
  234. - **如实记录**:每次分析都要如实反映实际返回的数据
  235. ## 工作流程
  236. ### 1. 理解原始问题
  237. - 仔细阅读<需求上下文>和<当前问题>
  238. - 提取问题的核心需求和关键概念
  239. - 明确问题的本质意图(what)、应用场景(where)、实现方式(how)
  240. ### 2. 动态探索策略
  241. **第一轮尝试:**
  242. - 使用原始问题直接调用 get_query_suggestions(query="原始问题")
  243. - 第一次调用会自动标注问题(三层),后续调用会复用该标注
  244. - **检查返回结果**:
  245. - 如果返回空列表 []:说明"该query未返回任何推荐词",需要简化或替换query
  246. - 如果有推荐词:查看每个推荐词的 essence_score、hard_score、soft_score 和 reason
  247. - **做出判断**:是否有 essence_score=1 且 hard_score=1 且 soft_score >= 0.7 的推荐词?
  248. **后续迭代:**
  249. 如果没有合格推荐词(或返回空列表),必须先调用 modify_query 记录修改,然后再次搜索:
  250. **工具使用流程:**
  251. 1. **分析评估反馈**(必须基于实际返回的数据):
  252. - **情况A - 返回空列表**:
  253. * 在 reason 中说明:"第X轮未返回任何推荐词,可能是query过于复杂或生僻"
  254. * 不能编造任何推荐词或评分
  255. - **情况B - 有推荐词但无合格词**:
  256. * **首先检查 essence_score**:
  257. - 如果全是 essence_score=0:本质/意图完全不对,需要重新理解问题
  258. - 如果有 essence_score=1:本质对了,继续分析
  259. * **分析 essence_score=1 且 hard_score=1 的推荐词**:
  260. - 有哪些?soft_score 是多少?
  261. - 如果 soft_score 较低(<0.7),reason 中说明丢失了哪些信息?
  262. - 能否通过修改query提高 soft_score?
  263. * **如果 essence_score=1 但全是 hard_score=0**:
  264. - reason 中说明了哪些硬性约束不满足?(地域、时间、对象、质量等)
  265. - 需要如何调整query才能满足硬性约束?
  266. 2. **决策修改策略**:基于实际评估反馈,调用 modify_query(original_query, operation_type, new_query, reason)
  267. - reason 必须引用具体的 essence_score、hard_score、soft_score 和评估理由
  268. - 不能编造任何数据
  269. 3. 使用返回的 new_query 调用 get_query_suggestions
  270. 4. 分析新的评估结果,如果仍不满足,重复步骤1-3
  271. **四种操作类型(operation_type):**
  272. - **简化**:删除冗余词汇,提取核心关键词(当推荐词过于发散时)
  273. - **扩展**:添加限定词或场景描述(当推荐词过于泛化时)
  274. - **替换**:使用同义词、行业术语或口语化表达(当推荐词偏离核心时)
  275. - **组合**:调整关键词顺序或组合方式(当推荐词结构不合理时)
  276. **每次修改的reason必须包含:**
  277. - 上一轮评估结果的关键发现(引用具体的 essence_score、hard_score、soft_score 和评估理由)
  278. - 基于评估反馈,为什么这样修改
  279. - 预期这次修改会带来什么改进
  280. ### 3. 决策标准
  281. 采用**三级评分标准**:
  282. **优先级1:本质/意图(最高优先级)**
  283. - **essence_score = 1**:本质一致,继续检查
  284. - **essence_score = 0**:本质改变,**直接放弃**
  285. **优先级2:硬性约束(必须满足)**
  286. - **hard_score = 1**:所有约束满足,继续检查
  287. - **hard_score = 0**:约束不满足,**直接放弃**
  288. **优先级3:软性修饰(越高越好)**
  289. - **soft_score >= 0.7**:信息保留较完整,**理想结果**
  290. - **0.5 <= soft_score < 0.7**:有所丢失但可接受,**备选结果**
  291. - **soft_score < 0.5**:丢失过多,继续优化
  292. **采纳标准:**
  293. - **最优**:essence=1 且 hard=1 且 soft >= 0.7
  294. - **可接受**:essence=1 且 hard=1 且 soft >= 0.5(多次尝试后)
  295. - **不可接受**:essence=0 或 hard=0(无论soft多高)
  296. ### 4. 迭代终止条件
  297. - **成功终止**:找到 essence=1 且 hard=1 且 soft >= 0.7 的推荐query
  298. - **可接受终止**:5轮后找到 essence=1 且 hard=1 且 soft >= 0.5 的推荐query
  299. - **失败终止**:最多5轮
  300. - **无推荐词**:返回空列表或错误
  301. ### 5. 输出要求
  302. **成功找到合格query时:**
  303. ```
  304. 原始问题:[原问题]
  305. 优化后的query:[最终推荐query]
  306. 本质匹配度:[essence_score] (1=本质一致)
  307. 硬性约束匹配度:[hard_score] (1=所有约束满足)
  308. 软性修饰完整度:[soft_score] (0-1)
  309. 评估理由:[简要说明]
  310. ```
  311. **未找到合格query时:**
  312. ```
  313. 原始问题:[原问题]
  314. 结果:未找到合格推荐query
  315. 原因:[本质不符 / 硬性约束不满足 / 软性信息丢失过多]
  316. 最接近的推荐词:[如果有essence=1且hard=1的词,列出soft最高的]
  317. 建议:[简要建议]
  318. ```
  319. ## 注意事项
  320. - **第一轮必须使用原始问题**:直接调用 get_query_suggestions(query="原始问题")
  321. - 第一次调用会自动标注问题(三层),打印出标注结果
  322. - 后续调用会复用该标注进行评估
  323. - **后续修改必须调用 modify_query**:不能直接用新query调用 get_query_suggestions
  324. - **重点关注评估结果**:每次都要仔细分析返回的三个分数
  325. - **essence_score=0 直接放弃**,本质不对
  326. - **hard_score=0 也直接放弃**,约束不满足
  327. - **优先关注 essence=1 且 hard=1 的推荐词**,分析如何提升 soft_score
  328. - **基于数据决策**:修改策略必须基于评估反馈
  329. - 引用具体的 essence_score、hard_score、soft_score
  330. - 引用 reason 中的关键发现
  331. - **采纳标准明确**:
  332. - **最优**:essence=1 且 hard=1 且 soft >= 0.7,立即采纳
  333. - **可接受**:essence=1 且 hard=1 且 soft >= 0.5,多次尝试后可采纳
  334. - **不可接受**:essence=0 或 hard=0,无论soft多高都不能用
  335. - **严禁编造数据**:
  336. * 如果返回空列表,必须明确说明"未返回任何推荐词"
  337. * 不能引用不存在的推荐词、分数或评估理由
  338. * 每次 modify_query 的 reason 必须基于上一轮实际返回的结果
  339. """.strip()
  340. async def main(input_dir: str):
  341. current_time, log_url = set_trace()
  342. # 从目录中读取固定文件名
  343. input_context_file = os.path.join(input_dir, 'context.md')
  344. input_q_file = os.path.join(input_dir, 'q.md')
  345. q_context = read_file_as_string(input_context_file)
  346. q = read_file_as_string(input_q_file)
  347. q_with_context = f"""
  348. <需求上下文>
  349. {q_context}
  350. </需求上下文>
  351. <当前问题>
  352. {q}
  353. </当前问题>
  354. """.strip()
  355. # 获取当前文件名作为版本
  356. version = os.path.basename(__file__)
  357. version_name = os.path.splitext(version)[0] # 去掉 .py 后缀
  358. # 日志保存到输入目录的 output/版本/时间戳 目录下
  359. log_dir = os.path.join(input_dir, "output", version_name, current_time)
  360. run_context = RunContext(
  361. version=version,
  362. input_files={
  363. "input_dir": input_dir,
  364. "context_file": input_context_file,
  365. "q_file": input_q_file,
  366. },
  367. q_with_context=q_with_context,
  368. q_context=q_context,
  369. q=q,
  370. log_dir=log_dir,
  371. log_url=log_url,
  372. )
  373. agent = Agent[RunContext](
  374. name="Query Optimization Agent",
  375. instructions=instructions,
  376. tools=[get_query_suggestions, modify_query],
  377. )
  378. result = await Runner.run(agent, input=q_with_context, context = run_context,)
  379. print(result.final_output)
  380. # 保存最终输出到 RunContext
  381. run_context.final_output = str(result.final_output)
  382. # 保存 RunContext 到 log_dir
  383. os.makedirs(run_context.log_dir, exist_ok=True)
  384. context_file_path = os.path.join(run_context.log_dir, "run_context.json")
  385. with open(context_file_path, "w", encoding="utf-8") as f:
  386. json.dump(run_context.model_dump(), f, ensure_ascii=False, indent=2)
  387. print(f"\nRunContext saved to: {context_file_path}")
  388. if __name__ == "__main__":
  389. parser = argparse.ArgumentParser(description="搜索query优化工具")
  390. parser.add_argument(
  391. "--input-dir",
  392. type=str,
  393. default="input/简单扣图",
  394. help="输入目录路径,默认: input/简单扣图"
  395. )
  396. args = parser.parse_args()
  397. asyncio.run(main(args.input_dir))