sug_v2_raw_v2.py 11 KB

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