sug_v2.py 10 KB

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