sug_v5_0.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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. - 哪些query让系统理解方向变化了?(从"旅游"变成"摄影")
  157. - 哪些方向是死路?(多次essence=0且推荐词主题不变)
  158. - **是否有渐进的改善?**(推荐词越来越接近目标)
  159. ### 第三步:选择策略类型(带着明确的探索目的)
  160. **refine_current(微调当前query)**
  161. - 适用:推荐词方向对了,需要微调让它更精确
  162. - 探索目的:在正确方向上精细化
  163. - 动作:加词/减词/换词/调整顺序
  164. **use_recommendation(选推荐词作为新起点)** ⭐ 最重要策略
  165. - 适用:推荐词虽然essence=0,但**揭示了系统在这个方向有内容**
  166. - 探索目的:利用推荐词这个客观信号,引导系统往目标方向
  167. - **核心思维**:推荐词是系统给你的提示,告诉你"我有这个"
  168. - 动作:
  169. - 选一个最有潜力的推荐词作为base_query
  170. - 在它基础上加目标方向的词
  171. - **这个新query可能不满足原需求,但目的是探索和引导**
  172. **change_approach(换完全不同的角度)**
  173. - 适用:当前方向是死路(多次尝试推荐词主题不变)
  174. - 探索目的:跳出当前框架,从另一个角度切入
  175. - 动作:换一种完全不同的表述方式
  176. **relax_constraints(放宽约束)**
  177. - 适用:query太复杂,系统不理解(返回空列表)
  178. - 探索目的:先让系统有响应,看它在最基础层面有什么
  179. - 动作:去掉限定词,保留核心概念
  180. ## 输出要求
  181. ### 1. reasoning(推理过程)
  182. 必须包含三部分,**重点写探索目的**:
  183. - **当前推荐词信号分析**:
  184. - 系统理解成什么主题了?(旅游?教程?素材?工具?品种?)
  185. - 推荐词揭示了什么信息?(系统在哪个方向有内容)
  186. - **不要只看essence_score**:
  187. - essence_score=0不代表推荐词没用
  188. - 关键看推荐词的主题是否有助于引导
  189. - 哪个推荐词最有潜力作为下一步的桥梁?
  190. - **历史尝试与趋势**:
  191. - 系统理解的主题变化:从"品种介绍"→"旅游"→"摄影"
  192. - 是否在逐步接近目标?还是原地打转?
  193. - **下一步策略与探索目的**:
  194. - **这一步query的探索目的是什么?**
  195. - 验证系统对某个词的理解?
  196. - 往某个方向引导?
  197. - 利用推荐词作为桥梁?
  198. - 为什么选这个base_query?
  199. - 为什么这样修改?
  200. - **重要**:不要纠结"这个query不满足原需求",关键是它能否达成探索目的
  201. ### 2. strategy_type
  202. 从4种策略中选择:refine_current, use_recommendation, change_approach, relax_constraints
  203. ### 3. base_query
  204. **关键**:可以选择历史中的query,也可以选择历史推荐词
  205. - 如果选历史query:base_query_source = "history_query"
  206. - 如果选历史推荐词:base_query_source = "history_recommendation"
  207. ### 4. base_query_source
  208. 说明base_query的来源
  209. ### 5. modification_actions
  210. 列出具体的修改动作,例如:
  211. - ["去掉'如何获取'", "保留'川西秋季'", "把'素材'改为'图片'"]
  212. - ["选择推荐词'川西旅游'", "加上'秋季'", "加上'照片'"]
  213. ### 6. new_query
  214. 最终的新query
  215. ## 重要原则
  216. 1. **推荐词是最宝贵的反馈** - 充分利用推荐词这个客观信号
  217. - 即使essence=0的推荐词,也揭示了系统在这个方向有什么
  218. - **优先考虑use_recommendation策略** - 选一个推荐词作为起点
  219. 2. **中间query可以偏离原需求** - 每一步都有明确的探索目的
  220. - 不要纠结"这个query不满足原需求"
  221. - 关键是:这个query能不能帮你往正确方向引导系统
  222. 3. **识别死胡同,及时换方向**
  223. - 如果多次尝试推荐词主题不变 → 换方向
  224. - 如果推荐词越来越偏 → 回退到之前的某个好的起点
  225. 4. **保持推理简洁** - 抓住关键信息
  226. - 明确说出探索目的
  227. - 不要重复啰嗦
  228. """.strip()
  229. class ModificationStrategy(BaseModel):
  230. """修改策略模型 - 模拟人的搜索调整过程"""
  231. reasoning: str = Field(..., description="推理过程:1)当前推荐词分析:系统理解成什么了?2)历史尝试总结:哪些方向有效/无效?3)下一步策略:为什么这样调整?")
  232. strategy_type: Literal[
  233. "refine_current", # 微调当前query(加词/减词/换词/换顺序)
  234. "use_recommendation", # 选择推荐词作为新起点,在它基础上修改
  235. "change_approach", # 换完全不同的表述角度
  236. "relax_constraints" # 放宽约束,去掉部分限定词
  237. ] = Field(..., description="策略类型")
  238. base_query: str = Field(..., description="基础query,可以是:1)历史中的query 2)历史推荐词中的某一个")
  239. base_query_source: Literal["history_query", "history_recommendation"] = Field(..., description="base_query的来源")
  240. modification_actions: list[str] = Field(..., description="具体修改动作的描述,如:['去掉\"如何获取\"', '保留核心词\"川西秋季\"', '把\"素材\"改为\"图片\"']")
  241. new_query: str = Field(..., description="修改后的新query")
  242. strategy_generator = Agent[None](
  243. name="策略生成专家",
  244. instructions=strategy_instructions,
  245. output_type=ModificationStrategy,
  246. )
  247. # ============================================================================
  248. # 核心函数
  249. # ============================================================================
  250. async def annotate_question(q_with_context: str) -> str:
  251. """标注问题(三层)"""
  252. print("\n正在标注问题...")
  253. result = await Runner.run(question_annotator, q_with_context)
  254. annotation = str(result.final_output)
  255. print(f"问题标注完成:{annotation}")
  256. return annotation
  257. async def get_suggestions_with_eval(query: str, annotation: str, context: RunContext) -> list[dict]:
  258. """获取推荐词并评估"""
  259. print(f"\n正在获取推荐词:{query}")
  260. # 1. 调用小红书API
  261. xiaohongshu_api = XiaohongshuSearchRecommendations()
  262. query_suggestions = xiaohongshu_api.get_recommendations(keyword=query)
  263. print(f"获取到 {len(query_suggestions) if query_suggestions else 0} 个推荐词:{query_suggestions}")
  264. if not query_suggestions:
  265. # 记录到历史
  266. context.operations_history.append({
  267. "operation_type": "get_query_suggestions",
  268. "timestamp": datetime.now().isoformat(),
  269. "query": query,
  270. "suggestions": [],
  271. "evaluations": "未返回任何推荐词",
  272. })
  273. return []
  274. # 2. 并发评估所有推荐词
  275. async def evaluate_single_query(q_sug: str):
  276. eval_input = f"""
  277. <原始问题标注(三层)>
  278. {annotation}
  279. </原始问题标注(三层)>
  280. <待评估的推荐query>
  281. {q_sug}
  282. </待评估的推荐query>
  283. 请评估该推荐query的三个分数:
  284. 1. essence_score: 本质/意图是否一致(0或1)
  285. 2. hard_score: 硬性约束是否满足(0或1)
  286. 3. soft_score: 软性修饰保留程度(0-1)
  287. 4. reason: 详细的评估理由
  288. """
  289. evaluator_result = await Runner.run(evaluator, eval_input)
  290. result: EvaluationFeedback = evaluator_result.final_output
  291. return {
  292. "query": q_sug,
  293. "essence_score": result.essence_score,
  294. "hard_score": result.hard_score,
  295. "soft_score": result.soft_score,
  296. "reason": result.reason,
  297. }
  298. evaluations = await asyncio.gather(*[evaluate_single_query(q_sug) for q_sug in query_suggestions])
  299. # 3. 记录到历史
  300. context.operations_history.append({
  301. "operation_type": "get_query_suggestions",
  302. "timestamp": datetime.now().isoformat(),
  303. "query": query,
  304. "suggestions": query_suggestions,
  305. "evaluations": evaluations,
  306. })
  307. return evaluations
  308. async def generate_modification_strategy(
  309. current_query: str,
  310. evaluations: list[dict],
  311. annotation: str,
  312. context: RunContext
  313. ) -> ModificationStrategy:
  314. """生成修改策略"""
  315. print("\n正在生成修改策略...")
  316. # 整理历史尝试记录 - 完整保留推荐词和评估结果
  317. history_records = []
  318. round_num = 0
  319. for op in context.operations_history:
  320. if op["operation_type"] == "get_query_suggestions":
  321. round_num += 1
  322. record = {
  323. "round": round_num,
  324. "query": op["query"],
  325. "suggestions": op["suggestions"],
  326. "evaluations": op["evaluations"]
  327. }
  328. history_records.append(record)
  329. elif op["operation_type"] == "modify_query":
  330. # 修改操作也记录,但不增加轮数
  331. history_records.append({
  332. "operation": "modify_query",
  333. "strategy_type": op.get("strategy_type", op.get("modification_type")), # 兼容旧字段
  334. "base_query": op.get("base_query"),
  335. "base_query_source": op.get("base_query_source"),
  336. "modification_actions": op.get("modification_actions", []),
  337. "original_query": op["original_query"],
  338. "new_query": op["new_query"],
  339. "reasoning": op["reasoning"]
  340. })
  341. # 格式化历史记录为JSON
  342. history_json = json.dumps(history_records, ensure_ascii=False, indent=2)
  343. strategy_input = f"""
  344. <原始问题标注(三层)>
  345. {annotation}
  346. </原始问题标注(三层)>
  347. <历史尝试记录(完整)>
  348. {history_json}
  349. </历史尝试记录(完整)>
  350. <当前query>
  351. {current_query}
  352. </当前query>
  353. <当前轮推荐词评估结果>
  354. {json.dumps(evaluations, ensure_ascii=False, indent=2) if evaluations else "空列表"}
  355. </当前轮推荐词评估结果>
  356. 请基于所有历史尝试和当前评估结果,生成下一步的query修改策略。
  357. 重点分析:
  358. 1. **当前推荐词的信号**:
  359. - 系统理解成什么主题了?(旅游?教程?素材?工具?品种?)
  360. - 推荐词揭示了什么信息?系统在哪个方向有内容?
  361. - **不要只看essence_score**:essence=0的推荐词也可能是好的探索起点
  362. - 哪个推荐词最有潜力作为下一步的桥梁?
  363. 2. **历史趋势分析**:
  364. - 推荐词的主题变化:从"品种介绍"→"旅游"→"摄影"?
  365. - 是否在逐步接近目标?还是原地打转(主题不变)?
  366. - 哪些query让系统理解方向改变了?
  367. 3. **确定探索目的**:
  368. - 下一步query的探索目的是什么?
  369. * 验证系统对某个词的理解?
  370. * 往某个方向引导系统?
  371. * 利用推荐词作为桥梁?
  372. - **记住**:中间query不需要满足原需求,关键是达成探索目的
  373. """
  374. result = await Runner.run(strategy_generator, strategy_input)
  375. strategy: ModificationStrategy = result.final_output
  376. return strategy
  377. def find_qualified_queries(evaluations: list[dict], min_soft_score: float = 0.7) -> list[dict]:
  378. """查找所有合格的query,按soft_score降序排列"""
  379. qualified = [
  380. e for e in evaluations
  381. if e['essence_score'] == 1
  382. and e['hard_score'] == 1
  383. and e['soft_score'] >= min_soft_score
  384. ]
  385. # 按soft_score降序排列
  386. return sorted(qualified, key=lambda x: x['soft_score'], reverse=True)
  387. # ============================================================================
  388. # 主流程(代码控制)
  389. # ============================================================================
  390. async def optimize_query(context: RunContext, max_rounds: int = 20) -> dict:
  391. """
  392. 主优化流程 - 由代码控制
  393. Args:
  394. context: 运行上下文
  395. max_rounds: 最大迭代轮数,默认20
  396. 返回格式:
  397. {
  398. "success": True/False,
  399. "result": {...} or None,
  400. "message": "..."
  401. }
  402. """
  403. # 1. 标注问题(仅一次)
  404. annotation = await annotate_question(context.q_with_context)
  405. context.question_annotation = annotation
  406. # 2. 迭代优化
  407. current_query = context.q
  408. for round_num in range(1, max_rounds + 1):
  409. print(f"\n{'='*60}")
  410. print(f"第 {round_num} 轮:{'使用原始问题' if round_num == 1 else '使用修改后的query'}")
  411. print(f"当前query: {current_query}")
  412. print(f"{'='*60}")
  413. # 获取推荐词并评估
  414. evaluations = await get_suggestions_with_eval(current_query, annotation, context)
  415. if evaluations:
  416. # 检查是否找到合格query
  417. qualified_queries = find_qualified_queries(evaluations, min_soft_score=0.7)
  418. if qualified_queries:
  419. return {
  420. "success": True,
  421. "results": qualified_queries,
  422. "message": f"第{round_num}轮找到{len(qualified_queries)}个合格query"
  423. }
  424. # 如果是最后一轮,不再生成策略
  425. if round_num == max_rounds:
  426. break
  427. # 生成修改策略
  428. print(f"\n--- 生成修改策略 ---")
  429. strategy = await generate_modification_strategy(current_query, evaluations, annotation, context)
  430. print(f"\n修改策略:")
  431. print(f" 推理过程:{strategy.reasoning}")
  432. print(f" 策略类型:{strategy.strategy_type}")
  433. print(f" 基础query:{strategy.base_query} (来源: {strategy.base_query_source})")
  434. print(f" 修改动作:{', '.join(strategy.modification_actions)}")
  435. print(f" 新query:{strategy.new_query}")
  436. # 记录修改
  437. context.operations_history.append({
  438. "operation_type": "modify_query",
  439. "timestamp": datetime.now().isoformat(),
  440. "reasoning": strategy.reasoning,
  441. "strategy_type": strategy.strategy_type,
  442. "base_query": strategy.base_query,
  443. "base_query_source": strategy.base_query_source,
  444. "modification_actions": strategy.modification_actions,
  445. "original_query": current_query,
  446. "new_query": strategy.new_query,
  447. })
  448. # 更新当前query
  449. current_query = strategy.new_query
  450. # 所有轮次后仍未找到,降低标准查找
  451. print(f"\n{'='*60}")
  452. print(f"{max_rounds}轮后未找到最优query,降低标准(soft_score >= 0.5)")
  453. print(f"{'='*60}")
  454. acceptable_queries = find_qualified_queries(evaluations, min_soft_score=0.5)
  455. if acceptable_queries:
  456. return {
  457. "success": True,
  458. "results": acceptable_queries,
  459. "message": f"{max_rounds}轮后找到{len(acceptable_queries)}个可接受query(soft_score >= 0.5)"
  460. }
  461. # 完全失败:找出最接近的
  462. essence_hard_ok = [
  463. e for e in evaluations
  464. if e['essence_score'] == 1 and e['hard_score'] == 1
  465. ]
  466. if essence_hard_ok:
  467. # 返回所有满足essence和hard的,按soft_score降序
  468. closest_queries = sorted(essence_hard_ok, key=lambda x: x['soft_score'], reverse=True)
  469. return {
  470. "success": False,
  471. "results": closest_queries,
  472. "message": f"未找到合格query,但有{len(closest_queries)}个接近的推荐词(essence=1, hard=1)"
  473. }
  474. return {
  475. "success": False,
  476. "results": [],
  477. "message": "未找到任何满足本质和硬性约束的推荐词"
  478. }
  479. # ============================================================================
  480. # 输出格式化
  481. # ============================================================================
  482. def format_output(optimization_result: dict, context: RunContext) -> str:
  483. """格式化输出结果"""
  484. results = optimization_result.get("results", [])
  485. if optimization_result["success"] and results:
  486. output = f"原始问题:{context.q}\n"
  487. output += f"状态:{optimization_result['message']}\n\n"
  488. output += "合格的推荐query(按soft_score降序):\n"
  489. for i, result in enumerate(results, 1):
  490. output += f"\n{i}. {result['query']}\n"
  491. output += f" - 本质匹配度:{result['essence_score']} (1=本质一致)\n"
  492. output += f" - 硬性约束匹配度:{result['hard_score']} (1=所有约束满足)\n"
  493. output += f" - 软性修饰完整度:{result['soft_score']:.2f} (0-1)\n"
  494. output += f" - 评估理由:{result['reason']}\n"
  495. return output.strip()
  496. else:
  497. output = f"原始问题:{context.q}\n"
  498. output += f"结果:未找到合格推荐query\n"
  499. output += f"原因:{optimization_result['message']}\n"
  500. if results:
  501. output += "\n最接近的推荐词(按soft_score降序):\n"
  502. for i, result in enumerate(results[:3], 1): # 只显示前3个
  503. output += f"\n{i}. {result['query']}\n"
  504. output += f" - essence_score: {result['essence_score']}\n"
  505. output += f" - hard_score: {result['hard_score']}\n"
  506. output += f" - soft_score: {result['soft_score']:.2f}\n"
  507. output += f" - reason: {result['reason']}\n"
  508. output += "\n建议:尝试简化问题或调整需求描述"
  509. return output.strip()
  510. # ============================================================================
  511. # 主函数
  512. # ============================================================================
  513. async def main(input_dir: str, max_rounds: int = 20):
  514. current_time, log_url = set_trace()
  515. # 从目录中读取固定文件名
  516. input_context_file = os.path.join(input_dir, 'context.md')
  517. input_q_file = os.path.join(input_dir, 'q.md')
  518. q_context = read_file_as_string(input_context_file)
  519. q = read_file_as_string(input_q_file)
  520. q_with_context = f"""
  521. <需求上下文>
  522. {q_context}
  523. </需求上下文>
  524. <当前问题>
  525. {q}
  526. </当前问题>
  527. """.strip()
  528. # 获取当前文件名作为版本
  529. version = os.path.basename(__file__)
  530. version_name = os.path.splitext(version)[0]
  531. # 日志保存目录
  532. log_dir = os.path.join(input_dir, "output", version_name, current_time)
  533. run_context = RunContext(
  534. version=version,
  535. input_files={
  536. "input_dir": input_dir,
  537. "context_file": input_context_file,
  538. "q_file": input_q_file,
  539. },
  540. q_with_context=q_with_context,
  541. q_context=q_context,
  542. q=q,
  543. log_dir=log_dir,
  544. log_url=log_url,
  545. )
  546. # 执行优化流程(代码控制)
  547. optimization_result = await optimize_query(run_context, max_rounds=max_rounds)
  548. # 格式化输出
  549. final_output = format_output(optimization_result, run_context)
  550. print(f"\n{'='*60}")
  551. print("最终结果")
  552. print(f"{'='*60}")
  553. print(final_output)
  554. # 保存结果
  555. run_context.final_output = final_output
  556. # 保存 RunContext 到 log_dir
  557. os.makedirs(run_context.log_dir, exist_ok=True)
  558. context_file_path = os.path.join(run_context.log_dir, "run_context.json")
  559. with open(context_file_path, "w", encoding="utf-8") as f:
  560. json.dump(run_context.model_dump(), f, ensure_ascii=False, indent=2)
  561. print(f"\nRunContext saved to: {context_file_path}")
  562. if __name__ == "__main__":
  563. parser = argparse.ArgumentParser(description="搜索query优化工具")
  564. parser.add_argument(
  565. "--input-dir",
  566. type=str,
  567. default="input/简单扣图",
  568. help="输入目录路径,默认: input/简单扣图"
  569. )
  570. parser.add_argument(
  571. "--max-rounds",
  572. type=int,
  573. default=20,
  574. help="最大迭代轮数,默认: 20"
  575. )
  576. args = parser.parse_args()
  577. asyncio.run(main(args.input_dir, max_rounds=args.max_rounds))