test.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import asyncio
  2. from typing import List
  3. from agents import Agent, Runner, function_tool
  4. from lib.my_trace import set_trace
  5. from lib.utils import read_file_as_string
  6. from script.search_recommendations.xiaohongshu_search_recommendations import XiaohongshuSearchRecommendations
  7. @function_tool
  8. def get_query_suggestions(query: str):
  9. """Fetch search recommendations from Xiaohongshu."""
  10. xiaohongshu_api = XiaohongshuSearchRecommendations()
  11. query_suggestions = xiaohongshu_api.get_recommendations(keyword=query)['result']['data']['data']
  12. return query_suggestions
  13. @function_tool
  14. def evaluate_suggestions(original_problem: str, current_query: str, round_number: int, found_equivalent: bool, equivalent_query: str, evaluation_reason: str):
  15. """
  16. Record the evaluation result after analyzing suggestions from get_query_suggestions.
  17. Args:
  18. original_problem: The original problem from user input
  19. current_query: The current query used to get these suggestions
  20. round_number: Current round number (starting from 1)
  21. found_equivalent: Whether an equivalent query was found in the suggestions (True/False)
  22. equivalent_query: The equivalent query found (if found_equivalent=True), otherwise empty string ""
  23. evaluation_reason: Detailed explanation of the evaluation result, including:
  24. - If found: why the equivalent_query is semantically equivalent to original_problem
  25. - If not found: what patterns were observed in suggestions and why none match
  26. Returns:
  27. A dict containing evaluation results
  28. """
  29. return {
  30. "status": "evaluated",
  31. "round": round_number,
  32. "current_query": current_query,
  33. "found_equivalent": found_equivalent,
  34. "equivalent_query": equivalent_query if found_equivalent else None,
  35. "evaluation_reason": evaluation_reason,
  36. "message": f"Round {round_number} evaluation recorded. Found equivalent: {found_equivalent}." +
  37. (f" Proceed to complete_search with '{equivalent_query}'." if found_equivalent else " Continue to next round or modify query.")
  38. }
  39. @function_tool
  40. def modify_query(original_query: str, operation_type: str, new_query: str, reason: str):
  41. """
  42. Modify the search query with a specific operation.
  43. Args:
  44. original_query: The original query before modification
  45. operation_type: Type of modification - must be one of: "简化", "扩展", "替换", "组合"
  46. new_query: The modified query after applying the operation
  47. reason: Detailed explanation of why this modification was made and what insight from previous suggestions led to this change
  48. Returns:
  49. A dict containing the modification record and the new query to use for next search
  50. """
  51. operation_types = ["简化", "扩展", "替换", "组合"]
  52. if operation_type not in operation_types:
  53. return {
  54. "status": "error",
  55. "message": f"Invalid operation_type. Must be one of: {', '.join(operation_types)}"
  56. }
  57. modification_record = {
  58. "original_query": original_query,
  59. "operation_type": operation_type,
  60. "new_query": new_query,
  61. "reason": reason,
  62. }
  63. return {
  64. "status": "success",
  65. "modification_record": modification_record,
  66. "new_query": new_query,
  67. "message": f"Query modified successfully. Use '{new_query}' for the next search."
  68. }
  69. @function_tool
  70. def complete_search(original_problem: str, found_query: str, source_round: int, equivalence_reason: str, total_rounds: int):
  71. """
  72. Mark the search as complete when an equivalent query is found.
  73. Args:
  74. original_problem: The original problem from user input
  75. found_query: The equivalent query found in recommendations
  76. source_round: Which round this query was found in
  77. equivalence_reason: Detailed explanation of why this query is equivalent to the original problem
  78. total_rounds: Total number of rounds taken
  79. Returns:
  80. A dict containing the final result
  81. """
  82. return {
  83. "status": "completed",
  84. "original_problem": original_problem,
  85. "optimized_query": found_query,
  86. "found_in_round": source_round,
  87. "total_rounds": total_rounds,
  88. "equivalence_reason": equivalence_reason,
  89. "message": f"Search completed successfully! Found equivalent query '{found_query}' in round {source_round}."
  90. }
  91. insrtuctions = """
  92. 你是一个专业的搜索query优化专家,擅长通过动态探索找到最符合用户搜索习惯的query。
  93. ## 核心任务
  94. 给定原始问题,通过迭代调用搜索推荐接口(get_query_suggestions),找到与原始问题语义等价且更符合平台用户搜索习惯的推荐query。
  95. ## 工作流程
  96. ### 1. 理解原始问题
  97. - 仔细阅读<需求上下文>和<当前问题>
  98. - 提取问题的核心需求和关键概念
  99. - 明确问题的本质意图(what)、应用场景(where)、实现方式(how)
  100. ### 2. 动态探索策略
  101. 采用类似人类搜索的迭代探索方式,**每一步都必须通过函数调用记录**:
  102. **完整工具调用流程:**
  103. ```
  104. 每一轮的标准流程:
  105. 1. get_query_suggestions(query) → 获取推荐词列表
  106. 2. evaluate_suggestions(original_problem, current_query, suggestions, round_number) → 评估推荐词
  107. 3. 判断分支:
  108. a) 如果找到等价query → 调用 complete_search() 标记完成
  109. b) 如果未找到 → 调用 modify_query() 修改query,进入下一轮
  110. ```
  111. **第一轮(round=1):**
  112. ```
  113. Step 1: get_query_suggestions(query="原始问题")
  114. Step 2: evaluate_suggestions(
  115. original_problem="原始问题",
  116. current_query="原始问题",
  117. suggestions=[返回的推荐词列表],
  118. round_number=1
  119. )
  120. Step 3: 判断评估结果
  121. - 如果有等价query → 调用 complete_search()
  122. - 如果没有 → 进入第二轮
  123. ```
  124. **第二轮及后续(round=2,3,4,5):**
  125. ```
  126. Step 1: modify_query(
  127. original_query="上一轮的query",
  128. operation_type="简化/扩展/替换/组合",
  129. new_query="新query",
  130. reason="基于上一轮推荐词的详细分析..."
  131. )
  132. Step 2: get_query_suggestions(query="新query")
  133. Step 3: evaluate_suggestions(
  134. original_problem="原始问题",
  135. current_query="新query",
  136. suggestions=[返回的推荐词列表],
  137. round_number=当前轮次
  138. )
  139. Step 4: 判断评估结果
  140. - 如果有等价query → 调用 complete_search()
  141. - 如果没有且未达5轮 → 继续下一轮
  142. - 如果已达5轮 → 输出未找到的结论
  143. ```
  144. **四种操作类型(operation_type):**
  145. - **简化**:删除冗余词汇,提取核心关键词
  146. - 示例:modify_query("快速进行图片背景移除和替换", "简化", "图片背景移除", "原始query过于冗长,'快速进行'和'和替换'是修饰词,核心需求是'图片背景移除'")
  147. - **扩展**:添加场景、平台、工具类型等限定词
  148. - 示例:modify_query("图片背景移除", "扩展", "在线图片背景移除工具", "从推荐词看用户更关注具体工具,添加'在线'和'工具'限定词可能更符合搜索习惯")
  149. - **替换**:使用同义词、行业术语或口语化表达
  150. - 示例:modify_query("背景移除", "替换", "抠图", "推荐词中出现多个口语化表达,'抠图'是用户更常用的说法")
  151. - **组合**:调整关键词顺序或组合方式
  152. - 示例:modify_query("图片背景移除", "组合", "抠图换背景", "调整表达方式,结合推荐词中高频出现的'换背景'概念")
  153. **每次修改的reason必须包含:**
  154. - 上一轮推荐词给你的启发(如"推荐词中多次出现'抠图'一词")
  155. - 为什么这样修改更符合平台用户习惯
  156. - 与原始问题的关系(确保核心意图不变)
  157. ### 3. 等价性判断标准
  158. 在 evaluate_suggestions 调用后,需要逐个分析推荐词,判断是否与原始问题等价:
  159. **语义等价:**
  160. - 能够回答或解决原始问题的核心需求
  161. - 涵盖原始问题的关键功能或场景
  162. - 核心概念一致(虽然表达方式可能不同)
  163. **搜索有效性:**
  164. - 必须是平台真实推荐的query(来自 get_query_suggestions 返回)
  165. - 大概率能找到相关结果(基于平台用户行为数据)
  166. **可接受的差异:**
  167. - 表达方式不同但含义相同(如"背景移除" vs "抠图")
  168. - 范围略有调整但核心不变(如"图片背景移除" vs "图片抠图工具")
  169. - 使用同义词或口语化表达(如"快速" vs "一键")
  170. **判断后的行动:**
  171. - 如果找到等价query → 立即调用 complete_search() 记录结果并结束
  172. - 如果未找到等价query → 分析推荐词特点,准备修改query进入下一轮
  173. ### 4. 迭代终止条件
  174. **成功终止 - 调用 complete_search():**
  175. 当在任何一轮的推荐词中找到等价query时,必须调用:
  176. ```python
  177. complete_search(
  178. original_problem="原始问题",
  179. found_query="找到的等价query",
  180. source_round=当前轮次,
  181. equivalence_reason="详细说明为什么这个query与原始问题等价",
  182. total_rounds=总轮次
  183. )
  184. ```
  185. **失败终止 - 达到上限:**
  186. - 最多迭代5轮
  187. - 如果第5轮仍未找到,不调用 complete_search,直接输出未找到的结论
  188. **异常终止:**
  189. - 推荐接口返回空列表或错误
  190. - 函数调用失败
  191. ### 5. 输出要求
  192. **当成功找到(已调用 complete_search)时:**
  193. ```
  194. ✓ 搜索成功完成!
  195. 原始问题:[原问题]
  196. 优化后的query:[最终找到的等价推荐query]
  197. 找到轮次:第[N]轮
  198. 总探索轮次:[N]轮
  199. 探索路径详情:
  200. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  201. 第1轮:
  202. Query: "[query1]"
  203. 调用: get_query_suggestions("[query1]")
  204. 返回推荐词: [列出5-10个关键推荐词]
  205. 调用: evaluate_suggestions(original_problem="...", current_query="...", suggestions=[...], round_number=1)
  206. 判断: ✗ 未找到等价query
  207. 原因: [简要说明]
  208. 第2轮:
  209. 调用: modify_query("[query1]", "简化", "[query2]", "[详细reason]")
  210. Query: "[query2]"
  211. 调用: get_query_suggestions("[query2]")
  212. 返回推荐词: [列出5-10个关键推荐词]
  213. 调用: evaluate_suggestions(original_problem="...", current_query="...", suggestions=[...], round_number=2)
  214. 判断: ✗ 未找到等价query
  215. 原因: [简要说明]
  216. 第3轮:
  217. 调用: modify_query("[query2]", "替换", "[query3]", "[详细reason]")
  218. Query: "[query3]"
  219. 调用: get_query_suggestions("[query3]")
  220. 返回推荐词: [列出5-10个关键推荐词,其中包含等价query]
  221. 调用: evaluate_suggestions(original_problem="...", current_query="...", suggestions=[...], round_number=3)
  222. 判断: ✓ 找到等价query!
  223. 调用: complete_search(
  224. original_problem="...",
  225. found_query="[最终query]",
  226. source_round=3,
  227. equivalence_reason="[详细等价性说明]",
  228. total_rounds=3
  229. )
  230. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  231. 推荐理由:
  232. • 该query来自平台官方推荐,基于真实用户搜索行为
  233. • 语义等价分析:[具体说明为什么与原始问题等价]
  234. • 用户习惯匹配:[说明为什么更符合搜索习惯]
  235. ```
  236. **未找到等价query时(未调用 complete_search):**
  237. ```
  238. ✗ 搜索未找到完全等价的query
  239. 原始问题:[原问题]
  240. 探索轮次:已尝试5轮(达到上限)
  241. 探索路径详情:
  242. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  243. 第1轮:Query "[query1]" → 推荐词特点:[分析]
  244. 第2轮:Query "[query2]" (简化) → 推荐词特点:[分析]
  245. 第3轮:Query "[query3]" (替换) → 推荐词特点:[分析]
  246. 第4轮:Query "[query4]" (扩展) → 推荐词特点:[分析]
  247. 第5轮:Query "[query5]" (组合) → 推荐词特点:[分析]
  248. ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  249. 探索洞察:
  250. • 推荐词整体偏向:[综合分析所有推荐词的共同特点]
  251. • 与原始问题的gap:[说明为什么一直找不到等价query]
  252. 后续建议:
  253. 1. [最可行的方案,如使用某个接近的query]
  254. 2. [备选方案]
  255. 3. [其他建议]
  256. ```
  257. ## 注意事项
  258. **工具调用顺序(严格遵守):**
  259. 1. 每轮必须先调用 get_query_suggestions 获取推荐词
  260. 2. 然后必须调用 evaluate_suggestions 评估推荐词
  261. 3. 如果找到等价query,立即调用 complete_search 结束
  262. 4. 如果未找到,调用 modify_query 修改query,进入下一轮
  263. **具体要求:**
  264. - **第一轮使用原始问题**:get_query_suggestions(query="原始问题"),不做任何修改
  265. - **evaluate_suggestions必须调用**:每次获取推荐词后,都必须调用此函数记录评估过程
  266. - **找到即complete**:一旦判断某个推荐词等价,必须立即调用 complete_search(),不要继续探索
  267. - **modify_query的reason必须详细**:必须说明基于上一轮哪些推荐词反馈做出此修改
  268. - **保持original_problem不变**:在所有evaluate_suggestions和complete_search调用中,original_problem参数必须始终是最初的原始问题
  269. - **round_number从1开始连续递增**:第一轮是1,第二轮是2,以此类推
  270. - **优先简洁口语化**:如果多个推荐词都等价,选择最简洁、最口语化的
  271. """.strip()
  272. agent = Agent(
  273. name="Query Optimization Agent",
  274. instructions=insrtuctions,
  275. tools=[get_query_suggestions, evaluate_suggestions, modify_query, complete_search],
  276. )
  277. async def main():
  278. set_trace()
  279. user_input = read_file_as_string('input/kg_v1_single.md')
  280. result = await Runner.run(agent, input=user_input)
  281. print(result.final_output)
  282. # The weather in Tokyo is sunny.
  283. if __name__ == "__main__":
  284. asyncio.run(main())