sug_v5_1.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. import asyncio
  2. import json
  3. import os
  4. import argparse
  5. from datetime import datetime
  6. from agents import Agent, Runner
  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. class RunContext(BaseModel):
  13. version: str = Field(..., description="当前运行的脚本版本(文件名)")
  14. input_files: dict[str, str] = Field(..., description="输入文件路径映射")
  15. q_with_context: str
  16. q_context: str
  17. q: str
  18. log_url: str
  19. log_dir: str
  20. question_annotation: str | None = Field(default=None, description="问题的标注结果")
  21. operations_history: list[dict] = Field(default_factory=list, description="记录所有操作的历史")
  22. final_output: str | None = Field(default=None, description="最终输出结果")
  23. # ============================================================================
  24. # Agent 1: 问题标注专家
  25. # ============================================================================
  26. question_annotation_instructions = """
  27. 你是搜索需求分析专家。给定问题(含需求背景),在原文上标注三层:本质、硬性、软性。
  28. ## 判断标准
  29. **[本质]** - 问题的核心意图
  30. - 如何获取、教程、推荐、作品、测评等
  31. **[硬]** - 客观事实性约束(可明确验证、非主观判断)
  32. - 能明确区分类别的:地域、时间、对象、工具、操作类型
  33. - 特征:改变后得到完全不同类别的结果
  34. **[软]** - 主观判断性修饰(因人而异、程度性的)
  35. - 需要主观评价的:质量、速度、美观、特色、程度
  36. - 特征:改变后仍是同类结果,只是满足程度不同
  37. ## 输出格式
  38. 词语[本质-描述]、词语[硬-描述]、词语[软-描述]
  39. ## 注意
  40. - 只输出标注后的字符串
  41. - 结合需求背景判断意图
  42. """.strip()
  43. question_annotator = Agent[None](
  44. name="问题标注专家",
  45. instructions=question_annotation_instructions,
  46. )
  47. # ============================================================================
  48. # Agent 2: 评估专家
  49. # ============================================================================
  50. eval_instructions = """
  51. 你是搜索query评估专家。给定原始问题标注(三层)和推荐query,评估三个分数。
  52. ## 评估目标
  53. 用这个推荐query搜索,能否找到满足原始需求的内容?
  54. ## 三层评分
  55. ### 1. essence_score(本质/意图)= 0 或 1
  56. 推荐query的本质/意图是否与原问题一致?
  57. **原问题标注中的[本质-XXX]对应推荐词要求:**
  58. - 找方法/如何获取 → 推荐词**必须明确包含方法/途径类词汇**
  59. - ✅ "...网站推荐"、"如何获取..."、"...获取途径"、"...方法"
  60. - ❌ "...下载"、"...素材"(直接找内容,不是找方法)
  61. - 教程/学习 → 推荐词应该是教程/教学
  62. - 作品/欣赏 → 推荐词应该是作品展示
  63. - 工具/推荐 → 推荐词应该是工具推荐
  64. **评分原则:**
  65. - 1 = 本质一致,推荐词**明确表达**相同意图
  66. - 0 = 本质改变或**不够明确**(宁可严格,不可放松)
  67. ### 2. hard_score(硬性约束)= 0 或 1
  68. 在本质一致的前提下,是否满足所有硬性约束?
  69. **原问题标注中的[硬-XXX]:**地域、时间、对象、质量、工具等
  70. **评分:**
  71. - 1 = 所有硬性约束都满足
  72. - 0 = 任一硬性约束不满足
  73. ### 3. soft_score(软性修饰)= 0-1
  74. 软性修饰词保留了多少?
  75. **评分参考:**
  76. - 1.0 = 完整保留
  77. - 0.7-0.9 = 保留核心
  78. - 0.4-0.6 = 部分丢失
  79. - 0-0.3 = 大量丢失
  80. ## 注意
  81. - essence=0 直接拒绝,不管hard/soft多高
  82. - essence=1, hard=0 也要拒绝
  83. - essence=1, hard=1 才看soft_score
  84. """.strip()
  85. class EvaluationFeedback(BaseModel):
  86. """评估反馈模型 - 三层评分"""
  87. essence_score: Literal[0, 1] = Field(..., description="本质/意图匹配度,0或1")
  88. hard_score: Literal[0, 1] = Field(..., description="硬性约束匹配度,0或1")
  89. soft_score: float = Field(..., description="软性修饰完整度,0-1")
  90. reason: str = Field(..., description="评估理由")
  91. evaluator = Agent[None](
  92. name="评估专家",
  93. instructions=eval_instructions,
  94. output_type=EvaluationFeedback,
  95. )
  96. # ============================================================================
  97. # Agent 3: 修改策略生成专家
  98. # ============================================================================
  99. strategy_instructions = """
  100. 你是query修改策略专家。**模拟人在搜索引擎中的真实搜索行为**,基于反馈动态调整query。
  101. ## 核心思路:搜索是探索过程,不是直达过程
  102. **关键认知:**
  103. 1. **中间query不需要满足原始需求** - 它是探索工具,可以偏离原需求
  104. 2. **推荐词是最宝贵的反馈信号** - 告诉你系统理解成什么了,有什么内容
  105. 3. **每一步query都有明确的探索目的** - 不是盲目改词,而是试探和引导
  106. 4. **最终目标:找到满足需求的推荐词** - 不是让query本身满足需求
  107. ## 人的真实搜索过程
  108. **搜索的本质**:通过多步探索,利用推荐词作为桥梁,逐步引导系统
  109. **典型模式**:
  110. 第1步:直接尝试
  111. - 目的:看系统能否直接理解
  112. - 结果:空列表或essence=0
  113. - essence=0的推荐词:告诉你系统理解成什么了
  114. 第2步:降低要求,简化query
  115. - 目的:让系统有响应,看它在基础层面有什么
  116. - 推荐词虽然essence=0,但揭示了系统在某个主题有内容
  117. - **关键**:选一个最有潜力的推荐词
  118. 第3步:基于推荐词,往目标方向引导
  119. - 目的:利用推荐词作为桥梁,加上目标方向的词
  120. - 推荐词还是essence=0,但主题在变化(接近目标)
  121. - **渐进式**:不求一步到位,每步都有进展
  122. 第4步:继续引导或换角度
  123. - 如果推荐词主题不变 → 换角度
  124. - 如果推荐词主题在接近 → 继续引导
  125. 最终:找到essence=1的推荐词
  126. **关键原则**:
  127. 1. essence_score是评估推荐词的,不是评估中间query的
  128. 2. essence=0的推荐词也有价值,它揭示了系统的理解方向
  129. 3. 每一步都有明确的探索目的,看目的是否达成
  130. 4. 通过推荐词的主题变化,判断是否在接近目标
  131. ## 输入信息
  132. - 原始问题标注(三层):本质、硬性约束、软性修饰
  133. - 历史尝试记录:所有轮次的query、推荐词、评估结果
  134. - 当前query和推荐词评估
  135. ## 分析步骤
  136. ### 第一步:理解当前推荐词的信号
  137. **核心问题:推荐词告诉我什么信息?**
  138. **重要提醒:essence_score是评估推荐词是否满足原始需求的最终目标**
  139. - essence_score=1: 推荐词满足原需求的本质
  140. - essence_score=0: 推荐词不满足原需求的本质
  141. - **但中间query的目的可能不是满足原需求**,所以essence_score只是参考
  142. 1. **系统理解层面**(看推荐词的主题):
  143. - 空列表 → 系统完全不理解当前query
  144. - 有推荐词 → 系统理解成了什么主题?
  145. - 旅游?教程?素材?工具?品种介绍?
  146. - 这些主题是否有助于往目标方向引导?
  147. 2. **内容可用性层面**(看推荐词的价值):
  148. - **即使推荐词essence=0,也可能是很好的探索起点**
  149. - 例如:推荐词"川西旅游攻略"虽然essence=0,但揭示了系统认识"川西"
  150. - 哪些推荐词最有潜力作为下一步的桥梁?
  151. 3. **探索目的验证**:
  152. - 当前query的探索目的是什么?达到了吗?
  153. - 例如:目的是"看系统对川西有什么" → 达到了(有推荐词)
  154. - 下一步要验证/探索什么?
  155. ### 第二步:回顾历史,识别规律
  156. **什么是真正的死胡同?**
  157. - ❌ 不是essence=0就是死胡同
  158. - ✅ 死胡同:连续多次尝试,**推荐词的主题完全不变**
  159. - 例如:连续3轮都是"取名/品种介绍"
  160. - 例如:连续3轮都是"旅游攻略"
  161. **什么是有进展?**
  162. - ✅ 推荐词的主题在变化(旅游→摄影→作品→素材)
  163. - ✅ 即使essence=0,也说明在接近目标
  164. - ✅ 说明系统的理解在被引导
  165. **避免同义词打转**:
  166. - ❌ "素材"→"照片"→"图片"→"资源"
  167. - 这些同义词不会改变系统理解,纯粹浪费轮次
  168. - ✅ 应该从推荐词中选一个作为桥梁,或换完全不同的角度
  169. ### 第三步:选择策略类型(带着明确的探索目的)
  170. **refine_current(微调当前query)**
  171. - 适用:推荐词方向对了,需要微调让它更精确
  172. - 探索目的:在正确方向上精细化
  173. - 动作:加词/减词/换词/调整顺序
  174. **use_recommendation(选推荐词作为新起点)** ⭐ 最重要策略
  175. - 适用:推荐词虽然essence=0,但**揭示了系统在这个方向有内容**
  176. - 探索目的:利用推荐词这个客观信号,引导系统往目标方向
  177. - **核心思维**:推荐词是系统给你的提示,告诉你"我有这个"
  178. - 动作:
  179. - 选一个最有潜力的推荐词作为base_query
  180. - 在它基础上加目标方向的词
  181. - **这个新query可能不满足原需求,但目的是探索和引导**
  182. **change_approach(换完全不同的角度)**
  183. - 适用:当前方向是死路(多次尝试推荐词主题不变)
  184. - 探索目的:跳出当前框架,从另一个角度切入
  185. - 动作:换一种完全不同的表述方式
  186. **relax_constraints(放宽约束)**
  187. - 适用:query太复杂,系统不理解(返回空列表)
  188. - 探索目的:先让系统有响应,看它在最基础层面有什么
  189. - 动作:去掉限定词,保留核心概念
  190. ## 输出要求
  191. ### 1. reasoning(推理过程)
  192. 必须包含三部分,**核心是目标导向**:
  193. - **当前位置评估**(相对于最终目标):
  194. - 当前推荐词反映了系统在什么主题空间?
  195. - 离原始需求多远?(完全偏离/部分相关/已经接近)
  196. - **不要只看essence_score**:
  197. - essence_score=0不代表没用,可能是必经之路
  198. - 关键看推荐词能否帮助靠近目标
  199. - **历史进展判断**:
  200. - 推荐词主题是否在变化?(变化=进展,不变=死胡同)
  201. - 在靠近目标,还是原地打转?
  202. - 哪些尝试让系统理解发生了改变?
  203. - **下一步探索规划**:
  204. - **这一步的作用**(必须明确!):
  205. * 离目标远?→ 先让系统理解某个关键词/概念
  206. * 部分相关?→ 选推荐词作为桥梁,引导往目标方向
  207. * 已经接近?→ 微调细节,精确匹配
  208. - 为什么选这个base_query?
  209. - 这个修改如何让我们靠近目标?
  210. - **重要**:中间query不需要满足原需求,只要能靠近目标
  211. ### 2. strategy_type
  212. 从4种策略中选择:refine_current, use_recommendation, change_approach, relax_constraints
  213. ### 3. base_query
  214. **关键**:可以选择历史中的query,也可以选择历史推荐词
  215. - 如果选历史query:base_query_source = "history_query"
  216. - 如果选历史推荐词:base_query_source = "history_recommendation"
  217. ### 4. base_query_source
  218. 说明base_query的来源
  219. ### 5. modification_action
  220. **重要:一次只做一个核心动作**
  221. - 不要列举多个动作
  222. - 只描述最核心的那一个修改
  223. - 例如:"选择推荐词'川西旅游'作为新起点"
  224. - 例如:"去掉'如何获取'改为直接搜内容"
  225. - 例如:"加上'AI生成'转向生成方向"
  226. ### 6. new_query
  227. 最终的新query
  228. ## 重要原则
  229. 1. **推荐词是最宝贵的反馈** - 充分利用推荐词这个客观信号
  230. - 即使essence=0的推荐词,也揭示了系统在这个方向有什么
  231. - **优先考虑use_recommendation策略** - 选一个推荐词作为起点
  232. 2. **中间query可以偏离原需求** - 每一步都有明确的探索目的
  233. - 不要纠结"这个query不满足原需求"
  234. - 关键是:这个query能不能帮你往正确方向引导系统
  235. 3. **识别死胡同,及时换方向**
  236. - 如果多次尝试推荐词主题不变 → 换方向
  237. - 如果推荐词越来越偏 → 回退到之前的某个好的起点
  238. 4. **保持推理简洁** - 抓住关键信息
  239. - 明确说出探索目的
  240. - 不要重复啰嗦
  241. """.strip()
  242. class ModificationStrategy(BaseModel):
  243. """修改策略模型 - 模拟人的搜索调整过程"""
  244. reasoning: str = Field(..., description="推理过程:1)当前推荐词分析:系统理解成什么了?2)历史尝试总结:哪些方向有效/无效?3)下一步策略:为什么这样调整?")
  245. strategy_type: Literal[
  246. "refine_current", # 微调当前query(加词/减词/换词/换顺序)
  247. "use_recommendation", # 选择推荐词作为新起点,在它基础上修改
  248. "change_approach", # 换完全不同的表述角度
  249. "relax_constraints" # 放宽约束,去掉部分限定词
  250. ] = Field(..., description="策略类型")
  251. base_query: str = Field(..., description="基础query,可以是:1)历史中的query 2)历史推荐词中的某一个")
  252. base_query_source: Literal["history_query", "history_recommendation"] = Field(..., description="base_query的来源")
  253. modification_action: str = Field(..., description="核心修改动作(只一个),如:'选择推荐词作为新起点' 或 '去掉方法类词改为直接搜内容' 或 '加上AI生成转向生成方向'")
  254. new_query: str = Field(..., description="修改后的新query")
  255. strategy_generator = Agent[None](
  256. name="策略生成专家",
  257. instructions=strategy_instructions,
  258. output_type=ModificationStrategy,
  259. )
  260. # ============================================================================
  261. # 核心函数
  262. # ============================================================================
  263. async def annotate_question(q_with_context: str) -> str:
  264. """标注问题(三层)"""
  265. print("\n正在标注问题...")
  266. result = await Runner.run(question_annotator, q_with_context)
  267. annotation = str(result.final_output)
  268. print(f"问题标注完成:{annotation}")
  269. return annotation
  270. async def get_suggestions_with_eval(query: str, annotation: str, context: RunContext) -> list[dict]:
  271. """获取推荐词并评估"""
  272. print(f"\n正在获取推荐词:{query}")
  273. # 1. 调用小红书API
  274. xiaohongshu_api = XiaohongshuSearchRecommendations()
  275. query_suggestions = xiaohongshu_api.get_recommendations(keyword=query)
  276. print(f"获取到 {len(query_suggestions) if query_suggestions else 0} 个推荐词:{query_suggestions}")
  277. if not query_suggestions:
  278. # 记录到历史
  279. context.operations_history.append({
  280. "operation_type": "get_query_suggestions",
  281. "timestamp": datetime.now().isoformat(),
  282. "query": query,
  283. "suggestions": [],
  284. "evaluations": "未返回任何推荐词",
  285. })
  286. return []
  287. # 2. 并发评估所有推荐词
  288. async def evaluate_single_query(q_sug: str):
  289. eval_input = f"""
  290. <需求背景>
  291. {context.q_context if context.q_context else "无"}
  292. </需求背景>
  293. <原始问题>
  294. {context.q}
  295. </原始问题>
  296. <原始问题标注(三层)>
  297. {annotation}
  298. </原始问题标注(三层)>
  299. <待评估的推荐query>
  300. {q_sug}
  301. </待评估的推荐query>
  302. 请评估该推荐query的三个分数:
  303. 1. essence_score: 本质/意图是否一致(0或1)
  304. 2. hard_score: 硬性约束是否满足(0或1)
  305. 3. soft_score: 软性修饰保留程度(0-1)
  306. 4. reason: 详细的评估理由
  307. """
  308. evaluator_result = await Runner.run(evaluator, eval_input)
  309. result: EvaluationFeedback = evaluator_result.final_output
  310. return {
  311. "query": q_sug,
  312. "essence_score": result.essence_score,
  313. "hard_score": result.hard_score,
  314. "soft_score": result.soft_score,
  315. "reason": result.reason,
  316. }
  317. evaluations = await asyncio.gather(*[evaluate_single_query(q_sug) for q_sug in query_suggestions])
  318. # 3. 记录到历史
  319. context.operations_history.append({
  320. "operation_type": "get_query_suggestions",
  321. "timestamp": datetime.now().isoformat(),
  322. "query": query,
  323. "suggestions": query_suggestions,
  324. "evaluations": evaluations,
  325. })
  326. return evaluations
  327. async def generate_modification_strategy(
  328. annotation: str,
  329. context: RunContext
  330. ) -> ModificationStrategy:
  331. """生成修改策略"""
  332. print("\n正在生成修改策略...")
  333. # 整理历史尝试记录 - 完整保留推荐词和评估结果
  334. history_records = []
  335. round_num = 0
  336. for op in context.operations_history:
  337. if op["operation_type"] == "get_query_suggestions":
  338. round_num += 1
  339. record = {
  340. "round": round_num,
  341. "query": op["query"],
  342. "suggestions": op["suggestions"],
  343. "evaluations": op["evaluations"]
  344. }
  345. history_records.append(record)
  346. elif op["operation_type"] == "modify_query":
  347. # 修改操作也记录,但不增加轮数
  348. history_records.append({
  349. "operation": "modify_query",
  350. "strategy_type": op.get("strategy_type", op.get("modification_type")), # 兼容旧字段
  351. "base_query": op.get("base_query"),
  352. "base_query_source": op.get("base_query_source"),
  353. "modification_action": op.get("modification_action", op.get("modification_actions", [])), # 兼容旧版本
  354. "original_query": op["original_query"],
  355. "new_query": op["new_query"],
  356. "reasoning": op["reasoning"]
  357. })
  358. # 格式化历史记录为JSON
  359. history_json = json.dumps(history_records, ensure_ascii=False, indent=2)
  360. strategy_input = f"""
  361. <需求背景>
  362. {context.q_context if context.q_context else "无"}
  363. </需求背景>
  364. <原始问题>
  365. {context.q}
  366. </原始问题>
  367. <原始问题标注(三层)>
  368. {annotation}
  369. </原始问题标注(三层)>
  370. <历史尝试记录(完整)>
  371. {history_json}
  372. </历史尝试记录(完整)>
  373. 请基于所有历史尝试,生成下一步的query修改策略。
  374. **说明**:历史记录中最后一条就是当前轮的query和推荐词评估结果。
  375. **核心思路**:每一步都要明确 "当前在哪 → 离目标多远 → 下一步做什么能靠近目标"
  376. 重点分析:
  377. 1. **评估当前位置**(相对于最终目标):
  378. - 当前推荐词反映了什么?系统在哪个主题空间?
  379. - 离原始需求的距离:完全偏离?部分相关?已经接近?
  380. - **不要只看essence_score**:essence=0不代表没用,可能是通往目标的必经之路
  381. 2. **判断历史进展**:
  382. - 推荐词主题是否在变化?(变化=有进展,不变=死胡同)
  383. - 是在靠近目标,还是在原地打转?
  384. - 哪个方向的query让系统理解发生了改变?
  385. 3. **规划下一步探索**:
  386. - **这一步query的作用是什么**?(必须明确!)
  387. * 如果离目标很远:需要先让系统理解某个关键词/概念
  388. * 如果部分相关:选一个推荐词作为桥梁,在它基础上引导
  389. * 如果已经接近:微调细节,精确匹配需求
  390. - **记住**:中间query不需要满足原需求,只要能让我们往目标靠近
  391. """
  392. result = await Runner.run(strategy_generator, strategy_input)
  393. strategy: ModificationStrategy = result.final_output
  394. return strategy
  395. def find_qualified_queries(evaluations: list[dict], min_soft_score: float = 0.7) -> list[dict]:
  396. """查找所有合格的query,按soft_score降序排列"""
  397. qualified = [
  398. e for e in evaluations
  399. if e['essence_score'] == 1
  400. and e['hard_score'] == 1
  401. and e['soft_score'] >= min_soft_score
  402. ]
  403. # 按soft_score降序排列
  404. return sorted(qualified, key=lambda x: x['soft_score'], reverse=True)
  405. # ============================================================================
  406. # 主流程(代码控制)
  407. # ============================================================================
  408. async def optimize_query(context: RunContext, max_rounds: int = 20) -> dict:
  409. """
  410. 主优化流程 - 由代码控制
  411. Args:
  412. context: 运行上下文
  413. max_rounds: 最大迭代轮数,默认20
  414. 返回格式:
  415. {
  416. "success": True/False,
  417. "result": {...} or None,
  418. "message": "..."
  419. }
  420. """
  421. # 1. 标注问题(仅一次)
  422. annotation = await annotate_question(context.q_with_context)
  423. context.question_annotation = annotation
  424. # 2. 迭代优化
  425. current_query = context.q
  426. for round_num in range(1, max_rounds + 1):
  427. print(f"\n{'='*60}")
  428. print(f"第 {round_num} 轮:{'使用原始问题' if round_num == 1 else '使用修改后的query'}")
  429. print(f"当前query: {current_query}")
  430. print(f"{'='*60}")
  431. # 获取推荐词并评估
  432. evaluations = await get_suggestions_with_eval(current_query, annotation, context)
  433. if evaluations:
  434. # 检查是否找到合格query
  435. qualified_queries = find_qualified_queries(evaluations, min_soft_score=0.7)
  436. if qualified_queries:
  437. return {
  438. "success": True,
  439. "results": qualified_queries,
  440. "message": f"第{round_num}轮找到{len(qualified_queries)}个合格query"
  441. }
  442. # 如果是最后一轮,不再生成策略
  443. if round_num == max_rounds:
  444. break
  445. # 生成修改策略
  446. print(f"\n--- 生成修改策略 ---")
  447. strategy = await generate_modification_strategy(annotation, context)
  448. print(f"\n修改策略:")
  449. print(f" 推理过程:{strategy.reasoning}")
  450. print(f" 策略类型:{strategy.strategy_type}")
  451. print(f" 基础query:{strategy.base_query} (来源: {strategy.base_query_source})")
  452. print(f" 修改动作:{strategy.modification_action}")
  453. print(f" 新query:{strategy.new_query}")
  454. # 记录修改
  455. context.operations_history.append({
  456. "operation_type": "modify_query",
  457. "timestamp": datetime.now().isoformat(),
  458. "reasoning": strategy.reasoning,
  459. "strategy_type": strategy.strategy_type,
  460. "base_query": strategy.base_query,
  461. "base_query_source": strategy.base_query_source,
  462. "modification_action": strategy.modification_action,
  463. "original_query": current_query,
  464. "new_query": strategy.new_query,
  465. })
  466. # 更新当前query
  467. current_query = strategy.new_query
  468. # 所有轮次后仍未找到,从所有历史评估中降低标准查找
  469. print(f"\n{'='*60}")
  470. print(f"{max_rounds}轮后未找到最优query,降低标准(soft_score >= 0.5)")
  471. print(f"{'='*60}")
  472. # 收集所有历史轮次的评估结果
  473. all_evaluations = []
  474. for op in context.operations_history:
  475. if op["operation_type"] == "get_query_suggestions" and op["evaluations"]:
  476. all_evaluations.extend(op["evaluations"])
  477. if not all_evaluations:
  478. return {
  479. "success": False,
  480. "results": [],
  481. "message": "所有轮次均未返回推荐词"
  482. }
  483. # 降级查找:soft_score >= 0.5
  484. acceptable_queries = find_qualified_queries(all_evaluations, min_soft_score=0.5)
  485. if acceptable_queries:
  486. return {
  487. "success": True,
  488. "results": acceptable_queries,
  489. "message": f"{max_rounds}轮后找到{len(acceptable_queries)}个可接受query(soft_score >= 0.5)"
  490. }
  491. # 完全失败:找出最接近的(essence=1, hard=1)
  492. essence_hard_ok = [
  493. e for e in all_evaluations
  494. if e['essence_score'] == 1 and e['hard_score'] == 1
  495. ]
  496. if essence_hard_ok:
  497. # 返回所有满足essence和hard的,按soft_score降序
  498. closest_queries = sorted(essence_hard_ok, key=lambda x: x['soft_score'], reverse=True)
  499. return {
  500. "success": False,
  501. "results": closest_queries,
  502. "message": f"未找到合格query,但有{len(closest_queries)}个接近的推荐词(essence=1, hard=1)"
  503. }
  504. return {
  505. "success": False,
  506. "results": [],
  507. "message": "未找到任何满足本质和硬性约束的推荐词"
  508. }
  509. # ============================================================================
  510. # 输出格式化
  511. # ============================================================================
  512. def format_output(optimization_result: dict, context: RunContext) -> str:
  513. """格式化输出结果"""
  514. results = optimization_result.get("results", [])
  515. if optimization_result["success"] and results:
  516. output = f"原始问题:{context.q}\n"
  517. output += f"状态:{optimization_result['message']}\n\n"
  518. output += "合格的推荐query(按soft_score降序):\n"
  519. for i, result in enumerate(results, 1):
  520. output += f"\n{i}. {result['query']}\n"
  521. output += f" - 本质匹配度:{result['essence_score']} (1=本质一致)\n"
  522. output += f" - 硬性约束匹配度:{result['hard_score']} (1=所有约束满足)\n"
  523. output += f" - 软性修饰完整度:{result['soft_score']:.2f} (0-1)\n"
  524. output += f" - 评估理由:{result['reason']}\n"
  525. return output.strip()
  526. else:
  527. output = f"原始问题:{context.q}\n"
  528. output += f"结果:未找到合格推荐query\n"
  529. output += f"原因:{optimization_result['message']}\n"
  530. if results:
  531. output += "\n最接近的推荐词(按soft_score降序):\n"
  532. for i, result in enumerate(results[:3], 1): # 只显示前3个
  533. output += f"\n{i}. {result['query']}\n"
  534. output += f" - essence_score: {result['essence_score']}\n"
  535. output += f" - hard_score: {result['hard_score']}\n"
  536. output += f" - soft_score: {result['soft_score']:.2f}\n"
  537. output += f" - reason: {result['reason']}\n"
  538. output += "\n建议:尝试简化问题或调整需求描述"
  539. return output.strip()
  540. # ============================================================================
  541. # 主函数
  542. # ============================================================================
  543. async def main(input_dir: str, max_rounds: int = 20):
  544. current_time, log_url = set_trace()
  545. # 从目录中读取固定文件名
  546. input_context_file = os.path.join(input_dir, 'context.md')
  547. input_q_file = os.path.join(input_dir, 'q.md')
  548. q_context = read_file_as_string(input_context_file)
  549. q = read_file_as_string(input_q_file)
  550. q_with_context = f"""
  551. <需求上下文>
  552. {q_context}
  553. </需求上下文>
  554. <当前问题>
  555. {q}
  556. </当前问题>
  557. """.strip()
  558. # 获取当前文件名作为版本
  559. version = os.path.basename(__file__)
  560. version_name = os.path.splitext(version)[0]
  561. # 日志保存目录
  562. log_dir = os.path.join(input_dir, "output", version_name, current_time)
  563. run_context = RunContext(
  564. version=version,
  565. input_files={
  566. "input_dir": input_dir,
  567. "context_file": input_context_file,
  568. "q_file": input_q_file,
  569. },
  570. q_with_context=q_with_context,
  571. q_context=q_context,
  572. q=q,
  573. log_dir=log_dir,
  574. log_url=log_url,
  575. )
  576. # 执行优化流程(代码控制)
  577. optimization_result = await optimize_query(run_context, max_rounds=max_rounds)
  578. # 格式化输出
  579. final_output = format_output(optimization_result, run_context)
  580. print(f"\n{'='*60}")
  581. print("最终结果")
  582. print(f"{'='*60}")
  583. print(final_output)
  584. # 保存结果
  585. run_context.final_output = final_output
  586. # 保存 RunContext 到 log_dir
  587. os.makedirs(run_context.log_dir, exist_ok=True)
  588. context_file_path = os.path.join(run_context.log_dir, "run_context.json")
  589. with open(context_file_path, "w", encoding="utf-8") as f:
  590. json.dump(run_context.model_dump(), f, ensure_ascii=False, indent=2)
  591. print(f"\nRunContext saved to: {context_file_path}")
  592. if __name__ == "__main__":
  593. parser = argparse.ArgumentParser(description="搜索query优化工具")
  594. parser.add_argument(
  595. "--input-dir",
  596. type=str,
  597. default="input/简单扣图",
  598. help="输入目录路径,默认: input/简单扣图"
  599. )
  600. parser.add_argument(
  601. "--max-rounds",
  602. type=int,
  603. default=20,
  604. help="最大迭代轮数,默认: 20"
  605. )
  606. args = parser.parse_args()
  607. asyncio.run(main(args.input_dir, max_rounds=args.max_rounds))