sug_v2_with_eval_yx.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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
  7. from lib.my_trace import set_trace
  8. from typing import Literal
  9. from dataclasses import dataclass
  10. from pydantic import BaseModel, Field
  11. from lib.utils import read_file_as_string
  12. from script.search_recommendations.xiaohongshu_search_recommendations import XiaohongshuSearchRecommendations
  13. from agents import Agent, RunContextWrapper, Runner, function_tool
  14. from pydantic import BaseModel, Field
  15. class RunContext(BaseModel):
  16. version: str = Field(..., description="当前运行的脚本版本(文件名)")
  17. input_files: dict[str, str] = Field(..., description="输入文件路径映射,如 {'context_file': '...', 'q_file': '...'}")
  18. q_with_context: str
  19. q_context: str
  20. q: str
  21. log_url: str
  22. log_dir: str
  23. # 中间数据记录 - 按时间顺序记录所有操作
  24. operations_history: list[dict] = Field(default_factory=list, description="记录所有操作的历史,包括 get_query_suggestions 和 modify_query")
  25. # 最终输出结果
  26. final_output: str | None = Field(default=None, description="Agent的最终输出结果")
  27. eval_insrtuctions = """
  28. # 角色定义
  29. 你是一个 **专业的语言专家和语义相关性评判专家**。
  30. 你的任务是:判断我给你的平台sug词条,其与 <原始 query 问题> 和 <需求上下文> **共同形成的综合意图** 的相关度满足度百分比。
  31. ---
  32. # 输入信息
  33. 你将接收到以下输入:
  34. 1. <需求上下文>:文档的解构结果或语义说明,用于理解 query 所针对的核心任务与场景。
  35. 2. <原始 query 问题>:用户的初始查询问题。
  36. 3. <平台sug词条>:模型或算法推荐的 平台sug词条,其中包含待评估的词条。
  37. ---
  38. # 工作流程
  39. ## 第一步:理解综合意图
  40. - 仔细阅读 <需求上下文> 与 <原始 query 问题>;
  41. - 明确 <原始 query 问题> 的核心意图、主题焦点和任务目标;
  42. - 提炼 <需求上下文> 所描述的核心任务、场景、概念和语义范围;
  43. - **将 <原始 query 问题> 和 <需求上下文> 融合成一个单一的、完整的“综合意图”**,作为后续评估的唯一基准。这个综合意图代表了用户在特定场景下最核心、最全面的需求。
  44. ## 第二步:逐一评估 Sug 词条的综合相关度满足度
  45. 对于 我给你的sug词条:
  46. 1. **评估其与“综合意图”的相关度满足度:**
  47. - 将当前 sug 词条的语义与第一步中确定的“综合意图”(<原始 query 问题> 和 <需求上下文> 的结合体)进行比较。
  48. - 全面评估该 sug 词条在主题、目标动作、语义范围、场景匹配、核心概念覆盖等各方面与“综合意图”的匹配和满足程度。
  49. - 给出 0-1 之间的浮点数,代表其“相关度满足度”。数值比越高,表示该 sug 词条越能充分且精准地满足“综合意图”。
  50. **评估标准一致性要求:在评估 sug 词条时,请务必保持你对“相关度满足度”的判断标准和百分比给定的逻辑完全一致和稳定。**
  51. **相关性依据要求:** 简短叙述相关性依据,说明主要匹配点或差异点,以及该 sug 词条如何满足或未能完全满足“综合意图”的哪些方面。
  52. """
  53. @dataclass
  54. class EvaluationFeedback:
  55. reason: str=Field(..., description="简明扼要的理由")
  56. score: float=Field(..., description="评估结果,1表示等价,0表示不等价,中间值表示部分等价")
  57. evaluator = Agent[None](
  58. name="评估专家",
  59. instructions=eval_insrtuctions,
  60. output_type=EvaluationFeedback,
  61. )
  62. @function_tool
  63. async def get_query_suggestions(wrapper: RunContextWrapper[RunContext], query: str):
  64. """Fetch search recommendations from Xiaohongshu."""
  65. xiaohongshu_api = XiaohongshuSearchRecommendations()
  66. query_suggestions = xiaohongshu_api.get_recommendations(keyword=query)
  67. print(query_suggestions)
  68. async def evaluate_single_query(q_sug: str, q_with_context: str):
  69. """Evaluate a single query suggestion."""
  70. eval_input = f"""
  71. {q_with_context}
  72. <待评估的推荐query>
  73. {q_sug}
  74. </待评估的推荐query>
  75. """
  76. evaluator_result = await Runner.run(evaluator, eval_input)
  77. result: EvaluationFeedback = evaluator_result.final_output
  78. return {
  79. "query": q_sug,
  80. "score": result.score,
  81. "reason": result.reason,
  82. }
  83. # 并发执行所有评估任务
  84. q_with_context = wrapper.context.q_with_context
  85. res = []
  86. if query_suggestions:
  87. res = await asyncio.gather(*[evaluate_single_query(q_sug, q_with_context) for q_sug in query_suggestions])
  88. else:
  89. res = '未返回任何推荐词'
  90. # 记录到 RunContext
  91. wrapper.context.operations_history.append({
  92. "operation_type": "get_query_suggestions",
  93. "timestamp": datetime.now().isoformat(),
  94. "query": query,
  95. "suggestions": query_suggestions,
  96. "evaluations": res,
  97. })
  98. return res
  99. @function_tool
  100. def modify_query(wrapper: RunContextWrapper[RunContext], original_query: str, operation_type: str, new_query: str, reason: str):
  101. """
  102. Modify the search query with a specific operation.
  103. Args:
  104. original_query: The original query before modification
  105. operation_type: Type of modification - must be one of: "简化", "扩展", "替换", "组合"
  106. new_query: The modified query after applying the operation
  107. reason: Detailed explanation of why this modification was made and what insight from previous suggestions led to this change
  108. Returns:
  109. A dict containing the modification record and the new query to use for next search
  110. """
  111. operation_types = ["简化", "扩展", "替换", "组合"]
  112. if operation_type not in operation_types:
  113. return {
  114. "status": "error",
  115. "message": f"Invalid operation_type. Must be one of: {', '.join(operation_types)}"
  116. }
  117. modification_record = {
  118. "original_query": original_query,
  119. "operation_type": operation_type,
  120. "new_query": new_query,
  121. "reason": reason,
  122. }
  123. # 记录到 RunContext
  124. wrapper.context.operations_history.append({
  125. "operation_type": "modify_query",
  126. "timestamp": datetime.now().isoformat(),
  127. "modification_type": operation_type,
  128. "original_query": original_query,
  129. "new_query": new_query,
  130. "reason": reason,
  131. })
  132. return {
  133. "status": "success",
  134. "modification_record": modification_record,
  135. "new_query": new_query,
  136. "message": f"Query modified successfully. Use '{new_query}' for the next search."
  137. }
  138. insrtuctions = """
  139. 你是一个专业的搜索query优化专家,擅长通过动态探索找到最符合用户搜索习惯的query。
  140. ## 核心任务
  141. 给定原始问题,通过迭代调用搜索推荐接口(get_query_suggestions),找到与原始问题语义等价且更符合平台用户搜索习惯的推荐query。
  142. ## 重要说明
  143. - **你不需要自己评估query的等价性**
  144. - get_query_suggestions 函数内部已集成评估子agent,会自动对每个推荐词进行评估
  145. - 返回结果包含:query(推荐词)、score(评分,1表示等价,0表示不等价)、reason(评估理由)
  146. - **你的职责是分析评估结果,做出决策和策略调整**
  147. ## 防止幻觉 - 关键原则
  148. - **严禁编造数据**:只能基于 get_query_suggestions 实际返回的结果进行分析
  149. - **空结果处理**:如果返回的列表为空([]),必须明确说明"未返回任何推荐词"
  150. - **不要猜测**:在 modify_query 的 reason 中,不能引用不存在的推荐词或评分
  151. - **如实记录**:每次分析都要如实反映实际返回的数据
  152. ## 工作流程
  153. ### 1. 理解原始问题
  154. - 仔细阅读<需求上下文>和<当前问题>
  155. - 提取问题的核心需求和关键概念
  156. - 明确问题的本质意图(what)、应用场景(where)、实现方式(how)
  157. ### 2. 动态探索策略
  158. **第一轮尝试:**
  159. - 使用原始问题直接调用 get_query_suggestions(query="原始问题")
  160. - **检查返回结果**:
  161. - 如果返回空列表 []:说明"该query未返回任何推荐词",需要简化或替换query
  162. - 如果有推荐词:查看每个推荐词的 score 和 reason
  163. - **做出判断**:是否有 score >= 0.8 的高分推荐词?
  164. **后续迭代:**
  165. 如果没有高分推荐词(或返回空列表),必须先调用 modify_query 记录修改,然后再次搜索:
  166. **工具使用流程:**
  167. 1. **分析评估反馈**(必须基于实际返回的数据):
  168. - **情况A - 返回空列表**:
  169. * 在 reason 中说明:"第X轮未返回任何推荐词,可能是query过于复杂或生僻"
  170. * 不能编造任何推荐词或评分
  171. - **情况B - 有推荐词但无高分**:
  172. * 哪些推荐词得分较高?具体是多少分?评估理由是什么?
  173. * 哪些推荐词偏离了原问题?如何偏离的?
  174. * 推荐词整体趋势是什么?(过于泛化/具体化/领域偏移等)
  175. 2. **决策修改策略**:基于实际评估反馈,调用 modify_query(original_query, operation_type, new_query, reason)
  176. - reason 必须引用具体的数据,不能编造
  177. 3. 使用返回的 new_query 调用 get_query_suggestions
  178. 4. 分析新的评估结果,如果仍不满足,重复步骤1-3
  179. **四种操作类型(operation_type):**
  180. - **简化**:删除冗余词汇,提取核心关键词(当推荐词过于发散时)
  181. - **扩展**:添加限定词或场景描述(当推荐词过于泛化时)
  182. - **替换**:使用同义词、行业术语或口语化表达(当推荐词偏离核心时)
  183. - **组合**:调整关键词顺序或组合方式(当推荐词结构不合理时)
  184. **每次修改的reason必须包含:**
  185. - 上一轮评估结果的关键发现(引用具体的score和reason)
  186. - 基于评估反馈,为什么这样修改
  187. - 预期这次修改会带来什么改进
  188. ### 3. 决策标准
  189. - **score >= 0.8**:认为该推荐词与原问题等价,可以作为最终结果
  190. - **0.5 <= score < 0.8**:部分等价,分析reason看是否可接受
  191. - **score < 0.5**:不等价,需要继续优化
  192. ### 4. 迭代终止条件
  193. - **成功终止**:找到至少一个 score >= 0.8 的推荐query
  194. - **尝试上限**:最多迭代5轮,避免无限循环
  195. - **无推荐词**:推荐接口返回空列表或错误
  196. ### 5. 输出要求
  197. **成功找到等价query时,输出格式:**
  198. ```
  199. 原始问题:[原问题]
  200. 优化后的query:[最终找到的等价推荐query]
  201. 评分:[score]
  202. ```
  203. **未找到等价query时,输出格式:**
  204. ```
  205. 原始问题:[原问题]
  206. 结果:未找到完全等价的推荐query
  207. 建议:[简要建议,如:直接使用原问题搜索 或 使用最接近的推荐词]
  208. ```
  209. ## 注意事项
  210. - **第一轮必须使用原始问题**:直接调用 get_query_suggestions(query="原始问题")
  211. - **后续修改必须调用 modify_query**:不能直接用新query调用 get_query_suggestions
  212. - **重点关注评估结果**:每次都要仔细分析返回的 score 和 reason
  213. - **基于数据决策**:修改策略必须基于评估反馈,不能凭空猜测
  214. - **引用具体评分**:在分析和决策时,引用具体的score数值和reason内容
  215. - **优先选择高分推荐词**:score >= 0.8 即可认为等价
  216. - **严禁编造数据**:
  217. * 如果返回空列表,必须在 reason 中明确说明"未返回任何推荐词"
  218. * 不能引用不存在的推荐词、评分或评估理由
  219. * 每次 modify_query 的 reason 必须基于上一轮实际返回的结果
  220. """.strip()
  221. async def main(input_dir: str):
  222. current_time, log_url = set_trace()
  223. # 从目录中读取固定文件名
  224. input_context_file = os.path.join(input_dir, 'context.md')
  225. input_q_file = os.path.join(input_dir, 'q.md')
  226. q_context = read_file_as_string(input_context_file)
  227. q = read_file_as_string(input_q_file)
  228. q_with_context = f"""
  229. <需求上下文>
  230. {q_context}
  231. </需求上下文>
  232. <当前问题>
  233. {q}
  234. </当前问题>
  235. """.strip()
  236. # 获取当前文件名作为版本
  237. version = os.path.basename(__file__)
  238. version_name = os.path.splitext(version)[0] # 去掉 .py 后缀
  239. # 日志保存到输入目录的 output/版本/时间戳 目录下
  240. log_dir = os.path.join(input_dir, "output", version_name, current_time)
  241. run_context = RunContext(
  242. version=version,
  243. input_files={
  244. "input_dir": input_dir,
  245. "context_file": input_context_file,
  246. "q_file": input_q_file,
  247. },
  248. q_with_context=q_with_context,
  249. q_context=q_context,
  250. q=q,
  251. log_dir=log_dir,
  252. log_url=log_url,
  253. )
  254. agent = Agent[RunContext](
  255. name="Query Optimization Agent",
  256. instructions=insrtuctions,
  257. tools=[get_query_suggestions, modify_query],
  258. )
  259. result = await Runner.run(agent, input=q_with_context, context = run_context,)
  260. print(result.final_output)
  261. # 保存最终输出到 RunContext
  262. run_context.final_output = str(result.final_output)
  263. # 保存 RunContext 到 log_dir
  264. os.makedirs(run_context.log_dir, exist_ok=True)
  265. context_file_path = os.path.join(run_context.log_dir, "run_context.json")
  266. with open(context_file_path, "w", encoding="utf-8") as f:
  267. json.dump(run_context.model_dump(), f, ensure_ascii=False, indent=2)
  268. print(f"\nRunContext saved to: {context_file_path}")
  269. if __name__ == "__main__":
  270. parser = argparse.ArgumentParser(description="搜索query优化工具")
  271. parser.add_argument(
  272. "--input-dir",
  273. type=str,
  274. default="input/简单扣图",
  275. help="输入目录路径,默认: input/简单扣图"
  276. )
  277. args = parser.parse_args()
  278. asyncio.run(main(args.input_dir))