sug_v3.py 12 KB

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