|
|
@@ -0,0 +1,1016 @@
|
|
|
+import asyncio
|
|
|
+import json
|
|
|
+import os
|
|
|
+import argparse
|
|
|
+from datetime import datetime
|
|
|
+
|
|
|
+from agents import Agent, Runner
|
|
|
+from lib.my_trace import set_trace
|
|
|
+from typing import Literal
|
|
|
+from pydantic import BaseModel, Field
|
|
|
+
|
|
|
+from lib.utils import read_file_as_string
|
|
|
+from script.search_recommendations.xiaohongshu_search_recommendations import XiaohongshuSearchRecommendations
|
|
|
+
|
|
|
+
|
|
|
+class RunContext(BaseModel):
|
|
|
+ version: str = Field(..., description="当前运行的脚本版本(文件名)")
|
|
|
+ input_files: dict[str, str] = Field(..., description="输入文件路径映射")
|
|
|
+ q_with_context: str
|
|
|
+ q_context: str
|
|
|
+ q: str
|
|
|
+ log_url: str
|
|
|
+ log_dir: str
|
|
|
+ question_annotation: str | None = Field(default=None, description="问题的标注结果")
|
|
|
+ operations_history: list[dict] = Field(default_factory=list, description="记录所有操作的历史")
|
|
|
+ optimization_result: dict | None = Field(default=None, description="最终优化结果对象")
|
|
|
+ final_output: str | None = Field(default=None, description="最终输出结果(格式化文本)")
|
|
|
+
|
|
|
+
|
|
|
+# ============================================================================
|
|
|
+# Agent 1: 问题标注专家
|
|
|
+# ============================================================================
|
|
|
+question_annotation_instructions = """
|
|
|
+你是搜索需求分析专家。给定问题(含需求背景),在原文上标注三层:本质、硬性、软性。
|
|
|
+
|
|
|
+## 判断标准
|
|
|
+
|
|
|
+**[本质]** - 问题的核心意图
|
|
|
+- 如何获取、教程、推荐、作品、测评等
|
|
|
+
|
|
|
+**[硬]** - 客观事实性约束(可明确验证、非主观判断)
|
|
|
+- 能明确区分类别的:地域、时间、对象、工具、操作类型
|
|
|
+- 特征:改变后得到完全不同类别的结果
|
|
|
+
|
|
|
+**[软]** - 主观判断性修饰(因人而异、程度性的)
|
|
|
+- 需要主观评价的:质量、速度、美观、特色、程度
|
|
|
+- 特征:改变后仍是同类结果,只是满足程度不同
|
|
|
+
|
|
|
+## 输出格式
|
|
|
+
|
|
|
+词语[本质-描述]、词语[硬-描述]、词语[软-描述]
|
|
|
+
|
|
|
+## 注意
|
|
|
+- 只输出标注后的字符串
|
|
|
+- 结合需求背景判断意图
|
|
|
+""".strip()
|
|
|
+
|
|
|
+question_annotator = Agent[None](
|
|
|
+ name="问题标注专家",
|
|
|
+ instructions=question_annotation_instructions,
|
|
|
+)
|
|
|
+
|
|
|
+
|
|
|
+# ============================================================================
|
|
|
+# Agent 2: 评估专家
|
|
|
+# ============================================================================
|
|
|
+eval_instructions = """
|
|
|
+你是专业的语言专家和语义相关性评判专家。你的任务是判断平台sug词条与原始query问题的相关度满足度。
|
|
|
+
|
|
|
+## 评估目标
|
|
|
+
|
|
|
+用这个推荐query搜索,能否找到满足原始需求的内容?
|
|
|
+
|
|
|
+## 三层判定流程(一次性返回所有层级的评分)
|
|
|
+
|
|
|
+### 第一层:知识识别(knowledge_recognition = 0 或 1)
|
|
|
+
|
|
|
+**什么是知识?**
|
|
|
+在社交媒体创作场景下,知识是指:可应用的认知内容 + 实践指导 + 问题解决方案
|
|
|
+
|
|
|
+包含三个核心要素:
|
|
|
+- 陈述性知识(Know-What): 是什么、有哪些、包括什么
|
|
|
+- 程序性知识(Know-How): 如何做、怎么实现、步骤方法
|
|
|
+- 策略性知识(Know-Why): 为什么、原理机制、优化策略
|
|
|
+
|
|
|
+**判定方法(三步判定法):**
|
|
|
+
|
|
|
+Step 1: 意图识别
|
|
|
+- 原始需求是想【知道/学会/获得】某样东西吗?→ yes 进入step2
|
|
|
+
|
|
|
+Step 2: 动词解析
|
|
|
+- 提取核心动词:
|
|
|
+ - 认知类(了解、学习、理解)
|
|
|
+ - 操作类(制作、拍摄、剪辑、运营)
|
|
|
+ - 获取类(找、下载、获取、收集)
|
|
|
+ - 决策类(选择、对比、评估)
|
|
|
+- 有明确动词 → 是知识需求
|
|
|
+- 无明确动词但有隐含目的 → 提取隐含动词
|
|
|
+- 完全无动作意图 → 非知识需求
|
|
|
+
|
|
|
+Step 3: 目标验证
|
|
|
+- 这个query解决后,用户会获得新的认知或能力吗? → YES则是知识
|
|
|
+- 这个query的答案可以被学习和应用吗? → YES则是知识
|
|
|
+- 这个query在寻求某个问题的解决方案吗? → YES则是知识
|
|
|
+
|
|
|
+**输出:**
|
|
|
+- knowledge_recognition: 1=是知识需求,0=非知识需求
|
|
|
+- knowledge_recognition_reason: 判定依据(包含意图识别、动词提取、目标验证的关键发现)
|
|
|
+
|
|
|
+**重要:即使knowledge_recognition=0,也要继续计算后两层得分(便于分析)**
|
|
|
+
|
|
|
+---
|
|
|
+
|
|
|
+### 第二层:知识动机判定(motivation_score = 0-1分值)
|
|
|
+
|
|
|
+**目标:** 完全理解原始query的综合意图,识别主要需求和次要需求,并进行加权评估。
|
|
|
+
|
|
|
+**评估维度:**
|
|
|
+
|
|
|
+#### 维度1: 核心意图动词识别(权重50%)
|
|
|
+- 显性动词直接提取:如"如何获取素材" → 核心动作="获取"
|
|
|
+- 隐性动词语义推理:如"川西秋天风光摄影" → 隐含动作="拍摄"或"欣赏"
|
|
|
+- 动作层级区分:主动作 vs 子动作
|
|
|
+
|
|
|
+**评分规则:**
|
|
|
+- 核心动作完全一致 → 1.0
|
|
|
+- 核心动作语义相近(近义词) → 0.8-0.9
|
|
|
+- 核心动作有包含关系(主次关系) → 0.5-0.7
|
|
|
+- 核心动作完全不同 → 0-0.4
|
|
|
+
|
|
|
+#### 维度2: 目标对象识别(权重30%)
|
|
|
+- 主要对象(What):如"获取川西秋季风光摄影素材" → 主要对象="风光摄影素材"
|
|
|
+- 对象的限定词:地域限定("川西")、时间限定("秋季")、质量限定("高质量")
|
|
|
+
|
|
|
+**评分规则:**
|
|
|
+- 主要对象+核心限定词完全匹配 → 1.0
|
|
|
+- 主要对象匹配,限定词部分匹配 → 0.7-0.9
|
|
|
+- 主要对象匹配,限定词缺失/不符 → 0.4-0.6
|
|
|
+- 主要对象不匹配 → 0-0.3
|
|
|
+
|
|
|
+#### 维度3: 终极目的识别(权重20%)
|
|
|
+**评分规则:**
|
|
|
+- 目的完全一致 → 1.0
|
|
|
+- 目的相关但路径不同 → 0.6-0.7
|
|
|
+- 目的不相关 → 0-0.5
|
|
|
+
|
|
|
+**综合计算公式:**
|
|
|
+```
|
|
|
+motivation_score = 核心意图动词×0.5 + 目标对象×0.3 + 终极目的×0.2
|
|
|
+```
|
|
|
+
|
|
|
+**输出:**
|
|
|
+- motivation_score: 0-1分值(>=0.9才算通过)
|
|
|
+- motivation_breakdown: {"核心意图动词": 0.x, "目标对象": 0.x, "终极目的": 0.x}
|
|
|
+
|
|
|
+**阈值判定:**
|
|
|
+- >=0.9:意图高度匹配
|
|
|
+- <0.9:意图不匹配,建议重新生成sug词或调整query词
|
|
|
+
|
|
|
+**注意:评估标准需要严格,对所有用例保持一致的标准**
|
|
|
+
|
|
|
+---
|
|
|
+
|
|
|
+### 第三层:相关性判定(relevance_score = 0-1分值)
|
|
|
+
|
|
|
+**目标:** 基于第二层的综合意图,评估sug词条对原始query的满足程度。
|
|
|
+
|
|
|
+**评分标准体系:**
|
|
|
+
|
|
|
+#### 高度满足(0.9-1.0)
|
|
|
+- 核心动作:完全一致或为标准近义词
|
|
|
+- 目标对象:主体+关键限定词全部匹配
|
|
|
+- 使用场景:完全相同或高度兼容
|
|
|
+- 终极目的:完全一致
|
|
|
+- 判定方法:逐一核对,所有维度≥0.9;替换测试(把sug词替换原query,意思不变)
|
|
|
+
|
|
|
+#### 中高满足(0.7-0.89)
|
|
|
+- 核心动作:一致或相近,但可能更泛化/具体化
|
|
|
+- 目标对象:主体匹配,但1-2个限定词缺失/泛化
|
|
|
+- 使用场景:基本兼容,可能略有扩展或收窄
|
|
|
+- 终极目的:一致但实现路径略有差异
|
|
|
+- 判定方法:"有效信息保留率" ≥70%
|
|
|
+
|
|
|
+#### 中低满足(0.4-0.69)
|
|
|
+- 核心动作:存在明显差异,但主题相关
|
|
|
+- 目标对象:部分匹配,关键限定词缺失或错位
|
|
|
+- 使用场景:有关联但场景不同
|
|
|
+- 终极目的:相关但实现路径完全不同
|
|
|
+- 判定方法:只有主题词重叠,用户需要显著改变搜索策略
|
|
|
+
|
|
|
+#### 低度/不满足(0-0.39)
|
|
|
+- 核心动作:完全不同或对立
|
|
|
+- 目标对象:主体不同或无关联
|
|
|
+- 使用场景:场景冲突
|
|
|
+- 终极目的:完全不相关
|
|
|
+- 判定方法:除通用词外无有效重叠,sug词满足了完全不同的需求
|
|
|
+
|
|
|
+**维度计算公式:**
|
|
|
+```
|
|
|
+relevance_score = 核心动作×0.4 + 目标对象×0.3 + 使用场景×0.15 + 终极目的×0.15
|
|
|
+```
|
|
|
+
|
|
|
+**特殊情况处理:**
|
|
|
+
|
|
|
+1. 泛化与具体化
|
|
|
+ - 泛化(sug词更广):如果原query所有要素都在覆盖范围内 → 0.75-0.85
|
|
|
+ - 具体化(sug词更窄):如果sug词是原query的典型子场景 → 0.7-0.8
|
|
|
+
|
|
|
+2. 同义转换宽容度
|
|
|
+ - 允许:获取≈下载≈寻找≈收集;技巧≈方法≈教程≈攻略
|
|
|
+ - 不允许:获取素材≠制作素材;学习技巧≠查看案例
|
|
|
+
|
|
|
+3. 多意图处理
|
|
|
+ - 识别主次意图(通过语序、连接词判断)
|
|
|
+ - sug词至少满足主意图 → 中高满足
|
|
|
+ - sug词同时满足主次意图 → 高度满足
|
|
|
+ - sug词只满足次意图 → 降至中低满足
|
|
|
+
|
|
|
+**输出:**
|
|
|
+- relevance_score: 0-1分值(>=0.9为高度满足)
|
|
|
+- relevance_breakdown: {"核心动作": 0.x, "目标对象": 0.x, "使用场景": 0.x, "终极目的": 0.x}
|
|
|
+
|
|
|
+---
|
|
|
+
|
|
|
+## 最终输出要求
|
|
|
+
|
|
|
+一次性返回所有三层的评估结果:
|
|
|
+1. knowledge_recognition (0或1) + knowledge_recognition_reason
|
|
|
+2. motivation_score (0-1) + motivation_breakdown
|
|
|
+3. relevance_score (0-1) + relevance_breakdown
|
|
|
+4. overall_reason: 综合评估理由(简要总结三层判定结果)
|
|
|
+
|
|
|
+**重要原则:**
|
|
|
+- 即使第一层knowledge_recognition=0,也要完整计算第二层和第三层
|
|
|
+- 即使第二层motivation_score<0.9,也要完整计算第三层
|
|
|
+- 所有维度的breakdown必须提供具体数值
|
|
|
+- 评估标准严格一致,不因用例不同而放松标准
|
|
|
+""".strip()
|
|
|
+
|
|
|
+class MotivationBreakdown(BaseModel):
|
|
|
+ """动机得分明细"""
|
|
|
+ 核心意图动词: float = Field(..., description="核心意图动词得分,0-1")
|
|
|
+ 目标对象: float = Field(..., description="目标对象得分,0-1")
|
|
|
+ 终极目的: float = Field(..., description="终极目的得分,0-1")
|
|
|
+
|
|
|
+
|
|
|
+class RelevanceBreakdown(BaseModel):
|
|
|
+ """相关性得分明细"""
|
|
|
+ 核心动作: float = Field(..., description="核心动作得分,0-1")
|
|
|
+ 目标对象: float = Field(..., description="目标对象得分,0-1")
|
|
|
+ 使用场景: float = Field(..., description="使用场景得分,0-1")
|
|
|
+ 终极目的: float = Field(..., description="终极目的得分,0-1")
|
|
|
+
|
|
|
+
|
|
|
+class EvaluationFeedback(BaseModel):
|
|
|
+ """评估反馈模型 - 三层知识评估"""
|
|
|
+ # 第一层:知识识别
|
|
|
+ knowledge_recognition: Literal[0, 1] = Field(
|
|
|
+ ...,
|
|
|
+ description="是否为知识需求,1=是,0=否"
|
|
|
+ )
|
|
|
+ knowledge_recognition_reason: str = Field(
|
|
|
+ ...,
|
|
|
+ description="知识识别判定依据(意图识别、动词提取、目标验证)"
|
|
|
+ )
|
|
|
+
|
|
|
+ # 第二层:知识动机匹配
|
|
|
+ motivation_score: float = Field(
|
|
|
+ ...,
|
|
|
+ description="知识动机匹配度,0-1分值,>=0.9才通过"
|
|
|
+ )
|
|
|
+ motivation_breakdown: MotivationBreakdown = Field(
|
|
|
+ ...,
|
|
|
+ description="动机得分明细"
|
|
|
+ )
|
|
|
+
|
|
|
+ # 第三层:相关性评分
|
|
|
+ relevance_score: float = Field(
|
|
|
+ ...,
|
|
|
+ description="相关性得分,0-1分值,>=0.9为高度满足"
|
|
|
+ )
|
|
|
+ relevance_breakdown: RelevanceBreakdown = Field(
|
|
|
+ ...,
|
|
|
+ description="相关性得分明细"
|
|
|
+ )
|
|
|
+
|
|
|
+ overall_reason: str = Field(
|
|
|
+ ...,
|
|
|
+ description="综合评估理由"
|
|
|
+ )
|
|
|
+
|
|
|
+evaluator = Agent[None](
|
|
|
+ name="评估专家",
|
|
|
+ instructions=eval_instructions,
|
|
|
+ output_type=EvaluationFeedback,
|
|
|
+)
|
|
|
+
|
|
|
+
|
|
|
+# ============================================================================
|
|
|
+# Agent 3: 修改策略生成专家
|
|
|
+# ============================================================================
|
|
|
+strategy_instructions = """
|
|
|
+你是query修改策略专家。**模拟人在搜索引擎中的真实搜索行为**,基于反馈动态调整query。
|
|
|
+
|
|
|
+## 核心思路:搜索是探索过程,不是直达过程
|
|
|
+
|
|
|
+**关键认知:**
|
|
|
+1. **中间query不需要满足原始需求** - 它是探索工具,可以偏离原需求
|
|
|
+2. **推荐词是最宝贵的反馈信号** - 告诉你系统理解成什么了,有什么内容
|
|
|
+3. **每一步query都有明确的探索目的** - 不是盲目改词,而是试探和引导
|
|
|
+4. **最终目标:找到满足需求的推荐词** - 不是让query本身满足需求
|
|
|
+
|
|
|
+## 人的真实搜索过程
|
|
|
+
|
|
|
+**搜索的本质**:通过多步探索,利用推荐词作为桥梁,逐步引导系统
|
|
|
+
|
|
|
+**典型模式**:
|
|
|
+
|
|
|
+第1步:直接尝试
|
|
|
+- 目的:看系统能否直接理解
|
|
|
+- 结果:空列表或essence=0
|
|
|
+- essence=0的推荐词:告诉你系统理解成什么了
|
|
|
+
|
|
|
+第2步:降低要求,简化query
|
|
|
+- 目的:让系统有响应,看它在基础层面有什么
|
|
|
+- 推荐词虽然essence=0,但揭示了系统在某个主题有内容
|
|
|
+- **关键**:选一个最有潜力的推荐词
|
|
|
+
|
|
|
+第3步:基于推荐词,往目标方向引导
|
|
|
+- 目的:利用推荐词作为桥梁,加上目标方向的词
|
|
|
+- 推荐词还是essence=0,但主题在变化(接近目标)
|
|
|
+- **渐进式**:不求一步到位,每步都有进展
|
|
|
+
|
|
|
+第4步:继续引导或换角度
|
|
|
+- 如果推荐词主题不变 → 换角度
|
|
|
+- 如果推荐词主题在接近 → 继续引导
|
|
|
+
|
|
|
+最终:找到essence=1的推荐词
|
|
|
+
|
|
|
+**关键原则**:
|
|
|
+1. essence_score是评估推荐词的,不是评估中间query的
|
|
|
+2. essence=0的推荐词也有价值,它揭示了系统的理解方向
|
|
|
+3. 每一步都有明确的探索目的,看目的是否达成
|
|
|
+4. 通过推荐词的主题变化,判断是否在接近目标
|
|
|
+
|
|
|
+## 输入信息
|
|
|
+- 原始问题标注(三层):本质、硬性约束、软性修饰
|
|
|
+- 历史尝试记录:所有轮次的query、推荐词、评估结果
|
|
|
+- 当前query和推荐词评估
|
|
|
+
|
|
|
+## 分析步骤
|
|
|
+
|
|
|
+### 第一步:理解当前推荐词的信号
|
|
|
+**核心问题:推荐词告诉我什么信息?**
|
|
|
+
|
|
|
+**重要提醒:essence_score是评估推荐词是否满足原始需求的最终目标**
|
|
|
+- essence_score=1: 推荐词满足原需求的本质
|
|
|
+- essence_score=0: 推荐词不满足原需求的本质
|
|
|
+- **但中间query的目的可能不是满足原需求**,所以essence_score只是参考
|
|
|
+
|
|
|
+1. **系统理解层面**(看推荐词的主题):
|
|
|
+ - 空列表 → 系统完全不理解当前query
|
|
|
+ - 有推荐词 → 系统理解成了什么主题?
|
|
|
+ - 旅游?教程?素材?工具?品种介绍?
|
|
|
+ - 这些主题是否有助于往目标方向引导?
|
|
|
+
|
|
|
+2. **内容可用性层面**(看推荐词的价值):
|
|
|
+ - **即使推荐词essence=0,也可能是很好的探索起点**
|
|
|
+ - 例如:推荐词"川西旅游攻略"虽然essence=0,但揭示了系统认识"川西"
|
|
|
+ - 哪些推荐词最有潜力作为下一步的桥梁?
|
|
|
+
|
|
|
+3. **探索目的验证**:
|
|
|
+ - 当前query的探索目的是什么?达到了吗?
|
|
|
+ - 例如:目的是"看系统对川西有什么" → 达到了(有推荐词)
|
|
|
+ - 下一步要验证/探索什么?
|
|
|
+
|
|
|
+### 第二步:回顾历史,识别规律
|
|
|
+- 哪些query让系统理解方向变化了?(从"旅游"变成"摄影")
|
|
|
+- 哪些方向是死路?(多次essence=0且推荐词主题不变)
|
|
|
+- **是否有渐进的改善?**(推荐词越来越接近目标)
|
|
|
+
|
|
|
+### 第三步:选择策略类型和具体操作(带着明确的探索目的)
|
|
|
+
|
|
|
+**策略类型(strategy_type):**
|
|
|
+
|
|
|
+**refine_current(微调当前query)**
|
|
|
+- 适用:推荐词方向对了,需要微调让它更精确
|
|
|
+- 探索目的:在正确方向上精细化
|
|
|
+- 动作:加词/减词/换词/调整顺序
|
|
|
+
|
|
|
+**use_recommendation(选推荐词作为新起点)** ⭐ 最重要策略
|
|
|
+- 适用:推荐词虽然knowledge_recognition=0或relevance_score低,但**揭示了系统在这个方向有内容**
|
|
|
+- 探索目的:利用推荐词这个客观信号,引导系统往目标方向
|
|
|
+- **核心思维**:推荐词是系统给你的提示,告诉你"我有这个"
|
|
|
+- 动作:
|
|
|
+ - 选一个最有潜力的推荐词作为base_query
|
|
|
+ - 在它基础上加目标方向的词
|
|
|
+ - **这个新query可能不满足原需求,但目的是探索和引导**
|
|
|
+
|
|
|
+**change_approach(换完全不同的角度)**
|
|
|
+- 适用:当前方向是死路(多次尝试推荐词主题不变)
|
|
|
+- 探索目的:跳出当前框架,从另一个角度切入
|
|
|
+- 动作:换一种完全不同的表述方式
|
|
|
+
|
|
|
+**relax_constraints(放宽约束)**
|
|
|
+- 适用:query太复杂,系统不理解(返回空列表)
|
|
|
+- 探索目的:先让系统有响应,看它在最基础层面有什么
|
|
|
+- 动作:去掉限定词,保留核心概念
|
|
|
+
|
|
|
+---
|
|
|
+
|
|
|
+**具体操作类型(operation_type):**
|
|
|
+
|
|
|
+**增加**
|
|
|
+- **判定标准**:
|
|
|
+ * 推荐词的语义比当前query更具体,且词汇数量 > 当前query的词汇数量
|
|
|
+ * 推荐词包含当前query的核心关键词,且添加了能将query具体化的新词
|
|
|
+ * 推荐词中存在当前query中不存在的关键新词(如:特定平台名称、特定功能词、具体场景词)
|
|
|
+- **使用时机**:当推荐词整体趋势是添加更具体的限定词或场景描述时
|
|
|
+
|
|
|
+**删减**
|
|
|
+- **判定标准**(满足以下任一条件):
|
|
|
+ * 推荐词的词汇数量明显少于当前query
|
|
|
+ * 推荐词返回空列表(说明query过于复杂)
|
|
|
+ * 推荐词词汇数量少于query,但核心搜索意图一致
|
|
|
+ * 识别出query中1-2个词为"非核心冗余词",删除后不影响核心意图
|
|
|
+- **使用时机**:当原query过于冗长复杂,推荐词都倾向于使用更简洁的表达时
|
|
|
+
|
|
|
+**调序**
|
|
|
+- **判定标准**:
|
|
|
+ * 推荐词与query拥有完全相同或极为相似的核心关键词集合,只是词汇排列顺序不同
|
|
|
+ * 推荐词的词序更自然或更符合用户搜索习惯
|
|
|
+ * 多个推荐词都倾向于使用与query不同但意思一致的词序
|
|
|
+- **使用时机**:当推荐词与原query关键词相同但顺序不同,且新顺序更符合用户习惯时
|
|
|
+
|
|
|
+**替换**
|
|
|
+- **判定标准**:
|
|
|
+ * 推荐词与query仅有1-2个核心词不同,其他词均相同
|
|
|
+ * 差异词是同义词、近义词或在该领域更流行/专业的替代词
|
|
|
+ * 推荐词中的新词在推荐列表中出现频率更高
|
|
|
+- **使用时机**:当推荐词显示某个词的同义词或专业术语更受欢迎时
|
|
|
+
|
|
|
+## 输出要求
|
|
|
+
|
|
|
+### 1. reasoning(推理过程)
|
|
|
+必须包含三部分,**重点写探索目的**:
|
|
|
+
|
|
|
+- **当前推荐词信号分析**:
|
|
|
+ - 系统理解成什么主题了?(旅游?教程?素材?工具?品种?)
|
|
|
+ - 推荐词揭示了什么信息?(系统在哪个方向有内容)
|
|
|
+ - **不要只看knowledge_recognition和relevance_score**:
|
|
|
+ - knowledge_recognition=0或relevance_score低不代表推荐词没用
|
|
|
+ - 关键看推荐词的主题是否有助于引导
|
|
|
+ - 哪个推荐词最有潜力作为下一步的桥梁?
|
|
|
+
|
|
|
+- **历史尝试与趋势**:
|
|
|
+ - 系统理解的主题变化:从"品种介绍"→"旅游"→"摄影"
|
|
|
+ - 是否在逐步接近目标?还是原地打转?
|
|
|
+
|
|
|
+- **下一步策略与探索目的**:
|
|
|
+ - **这一步query的探索目的是什么?**
|
|
|
+ - 验证系统对某个词的理解?
|
|
|
+ - 往某个方向引导?
|
|
|
+ - 利用推荐词作为桥梁?
|
|
|
+ - 为什么选这个base_query?
|
|
|
+ - 为什么选这个operation_type?
|
|
|
+ - 为什么这样修改?
|
|
|
+ - **重要**:不要纠结"这个query不满足原需求",关键是它能否达成探索目的
|
|
|
+
|
|
|
+### 2. strategy_type
|
|
|
+从4种策略中选择:refine_current, use_recommendation, change_approach, relax_constraints
|
|
|
+
|
|
|
+### 3. operation_type
|
|
|
+从4种操作中选择:增加、删减、调序、替换
|
|
|
+- **必须基于推荐词的特征选择**:看推荐词与当前query的差异模式
|
|
|
+- 参考上述"具体操作类型"的判定标准
|
|
|
+
|
|
|
+### 4. base_query
|
|
|
+**关键**:可以选择历史中的query,也可以选择历史推荐词
|
|
|
+- 如果选历史query:base_query_source = "history_query"
|
|
|
+- 如果选历史推荐词:base_query_source = "history_recommendation"
|
|
|
+
|
|
|
+### 5. base_query_source
|
|
|
+说明base_query的来源
|
|
|
+
|
|
|
+### 6. modification_actions
|
|
|
+列出具体的修改动作,建议格式:
|
|
|
+- 每个动作以操作类型开头(增加/删减/调序/替换)
|
|
|
+- 清晰描述具体修改了什么内容
|
|
|
+
|
|
|
+### 7. new_query
|
|
|
+最终的新query
|
|
|
+
|
|
|
+## 重要原则
|
|
|
+
|
|
|
+1. **推荐词是最宝贵的反馈** - 充分利用推荐词这个客观信号
|
|
|
+ - 即使essence=0的推荐词,也揭示了系统在这个方向有什么
|
|
|
+ - **优先考虑use_recommendation策略** - 选一个推荐词作为起点
|
|
|
+
|
|
|
+2. **中间query可以偏离原需求** - 每一步都有明确的探索目的
|
|
|
+ - 不要纠结"这个query不满足原需求"
|
|
|
+ - 关键是:这个query能不能帮你往正确方向引导系统
|
|
|
+
|
|
|
+3. **识别死胡同,及时换方向**
|
|
|
+ - 如果多次尝试推荐词主题不变 → 换方向
|
|
|
+ - 如果推荐词越来越偏 → 回退到之前的某个好的起点
|
|
|
+
|
|
|
+4. **保持推理简洁** - 抓住关键信息
|
|
|
+ - 明确说出探索目的
|
|
|
+ - 不要重复啰嗦
|
|
|
+""".strip()
|
|
|
+
|
|
|
+class ModificationStrategy(BaseModel):
|
|
|
+ """修改策略模型 - 模拟人的搜索调整过程"""
|
|
|
+ reasoning: str = Field(..., description="推理过程:1)当前推荐词分析:系统理解成什么了?2)历史尝试总结:哪些方向有效/无效?3)下一步策略:为什么这样调整?")
|
|
|
+
|
|
|
+ strategy_type: Literal[
|
|
|
+ "refine_current", # 微调当前query(加词/减词/换词/换顺序)
|
|
|
+ "use_recommendation", # 选择推荐词作为新起点,在它基础上修改
|
|
|
+ "change_approach", # 换完全不同的表述角度
|
|
|
+ "relax_constraints" # 放宽约束,去掉部分限定词
|
|
|
+ ] = Field(..., description="策略类型")
|
|
|
+
|
|
|
+ operation_type: Literal[
|
|
|
+ "增加", # 增加query语句,添加具体化的关键词
|
|
|
+ "删减", # 删减query词,去除冗余词汇
|
|
|
+ "调序", # 调整query词的顺序,更符合用户习惯的词序
|
|
|
+ "替换", # 替换query中的某个词,使用同义词或专业术语
|
|
|
+ ] = Field(..., description="具体操作类型:增加、删减、调序、替换")
|
|
|
+
|
|
|
+ base_query: str = Field(..., description="基础query,可以是:1)历史中的query 2)历史推荐词中的某一个")
|
|
|
+ base_query_source: Literal["history_query", "history_recommendation"] = Field(..., description="base_query的来源")
|
|
|
+
|
|
|
+ modification_actions: list[str] = Field(..., description="具体修改动作的描述,如:['去掉\"如何获取\"', '保留核心词\"川西秋季\"', '把\"素材\"改为\"图片\"']")
|
|
|
+
|
|
|
+ new_query: str = Field(..., description="修改后的新query")
|
|
|
+
|
|
|
+strategy_generator = Agent[None](
|
|
|
+ name="策略生成专家",
|
|
|
+ instructions=strategy_instructions,
|
|
|
+ output_type=ModificationStrategy,
|
|
|
+)
|
|
|
+
|
|
|
+
|
|
|
+# ============================================================================
|
|
|
+# 核心函数
|
|
|
+# ============================================================================
|
|
|
+
|
|
|
+async def annotate_question(q_with_context: str) -> str:
|
|
|
+ """标注问题(三层)"""
|
|
|
+ print("\n正在标注问题...")
|
|
|
+ result = await Runner.run(question_annotator, q_with_context)
|
|
|
+ annotation = str(result.final_output)
|
|
|
+ print(f"问题标注完成:{annotation}")
|
|
|
+ return annotation
|
|
|
+
|
|
|
+
|
|
|
+async def get_suggestions_with_eval(query: str, annotation: str, context: RunContext) -> list[dict]:
|
|
|
+ """获取推荐词并评估"""
|
|
|
+ print(f"\n正在获取推荐词:{query}")
|
|
|
+
|
|
|
+ # 1. 调用小红书API
|
|
|
+ xiaohongshu_api = XiaohongshuSearchRecommendations()
|
|
|
+ query_suggestions = xiaohongshu_api.get_recommendations(keyword=query)
|
|
|
+ print(f"获取到 {len(query_suggestions) if query_suggestions else 0} 个推荐词:{query_suggestions}")
|
|
|
+
|
|
|
+ if not query_suggestions:
|
|
|
+ # 记录到历史
|
|
|
+ context.operations_history.append({
|
|
|
+ "operation_type": "get_query_suggestions",
|
|
|
+ "timestamp": datetime.now().isoformat(),
|
|
|
+ "query": query,
|
|
|
+ "suggestions": [],
|
|
|
+ "evaluations": "未返回任何推荐词",
|
|
|
+ })
|
|
|
+ return []
|
|
|
+
|
|
|
+ # 2. 并发评估所有推荐词
|
|
|
+ async def evaluate_single_query(q_sug: str):
|
|
|
+ eval_input = f"""
|
|
|
+<需求上下文>
|
|
|
+{context.q_context}
|
|
|
+</需求上下文>
|
|
|
+
|
|
|
+<原始query问题>
|
|
|
+{context.q}
|
|
|
+</原始query问题>
|
|
|
+
|
|
|
+<平台sug词条>
|
|
|
+{q_sug}
|
|
|
+</平台sug词条>
|
|
|
+
|
|
|
+请对该sug词条进行三层评估(一次性返回所有层级的评分):
|
|
|
+
|
|
|
+第一层:判断sug词条是否为知识需求(knowledge_recognition: 0或1)
|
|
|
+第二层:评估知识动机匹配度(motivation_score: 0-1,需>=0.9)
|
|
|
+第三层:评估相关性得分(relevance_score: 0-1,>=0.9为高度满足)
|
|
|
+
|
|
|
+重要:即使第一层=0或第二层<0.9,也要完整计算所有层级的得分。
|
|
|
+"""
|
|
|
+ evaluator_result = await Runner.run(evaluator, eval_input)
|
|
|
+ result: EvaluationFeedback = evaluator_result.final_output
|
|
|
+ return {
|
|
|
+ "query": q_sug,
|
|
|
+ "knowledge_recognition": result.knowledge_recognition,
|
|
|
+ "knowledge_recognition_reason": result.knowledge_recognition_reason,
|
|
|
+ "motivation_score": result.motivation_score,
|
|
|
+ "motivation_breakdown": result.motivation_breakdown.model_dump(),
|
|
|
+ "relevance_score": result.relevance_score,
|
|
|
+ "relevance_breakdown": result.relevance_breakdown.model_dump(),
|
|
|
+ "overall_reason": result.overall_reason,
|
|
|
+ }
|
|
|
+
|
|
|
+ evaluations = await asyncio.gather(*[evaluate_single_query(q_sug) for q_sug in query_suggestions])
|
|
|
+
|
|
|
+ # 3. 记录到历史
|
|
|
+ context.operations_history.append({
|
|
|
+ "operation_type": "get_query_suggestions",
|
|
|
+ "timestamp": datetime.now().isoformat(),
|
|
|
+ "query": query,
|
|
|
+ "suggestions": query_suggestions,
|
|
|
+ "evaluations": evaluations,
|
|
|
+ })
|
|
|
+
|
|
|
+ return evaluations
|
|
|
+
|
|
|
+
|
|
|
+async def generate_modification_strategy(
|
|
|
+ current_query: str,
|
|
|
+ evaluations: list[dict],
|
|
|
+ annotation: str,
|
|
|
+ context: RunContext
|
|
|
+) -> ModificationStrategy:
|
|
|
+ """生成修改策略"""
|
|
|
+ print("\n正在生成修改策略...")
|
|
|
+
|
|
|
+ # 整理历史尝试记录 - 完整保留推荐词和评估结果
|
|
|
+ history_records = []
|
|
|
+ round_num = 0
|
|
|
+
|
|
|
+ for op in context.operations_history:
|
|
|
+ if op["operation_type"] == "get_query_suggestions":
|
|
|
+ round_num += 1
|
|
|
+ record = {
|
|
|
+ "round": round_num,
|
|
|
+ "query": op["query"],
|
|
|
+ "suggestions": op["suggestions"],
|
|
|
+ "evaluations": op["evaluations"]
|
|
|
+ }
|
|
|
+ history_records.append(record)
|
|
|
+ elif op["operation_type"] == "modify_query":
|
|
|
+ # 修改操作也记录,但不增加轮数
|
|
|
+ history_records.append({
|
|
|
+ "operation": "modify_query",
|
|
|
+ "strategy_type": op.get("strategy_type", op.get("modification_type")), # 兼容旧字段
|
|
|
+ "operation_type_detail": op.get("operation_type_detail"), # 新增:具体操作类型(增加、删减、调序、替换)
|
|
|
+ "base_query": op.get("base_query"),
|
|
|
+ "base_query_source": op.get("base_query_source"),
|
|
|
+ "modification_actions": op.get("modification_actions", []),
|
|
|
+ "original_query": op["original_query"],
|
|
|
+ "new_query": op["new_query"],
|
|
|
+ "reasoning": op["reasoning"]
|
|
|
+ })
|
|
|
+
|
|
|
+ # 格式化历史记录为JSON
|
|
|
+ history_json = json.dumps(history_records, ensure_ascii=False, indent=2)
|
|
|
+
|
|
|
+ strategy_input = f"""
|
|
|
+<原始问题标注(三层)>
|
|
|
+{annotation}
|
|
|
+</原始问题标注(三层)>
|
|
|
+
|
|
|
+<历史尝试记录(完整)>
|
|
|
+{history_json}
|
|
|
+</历史尝试记录(完整)>
|
|
|
+
|
|
|
+<当前query>
|
|
|
+{current_query}
|
|
|
+</当前query>
|
|
|
+
|
|
|
+<当前轮推荐词评估结果>
|
|
|
+{json.dumps(evaluations, ensure_ascii=False, indent=2) if evaluations else "空列表"}
|
|
|
+</当前轮推荐词评估结果>
|
|
|
+
|
|
|
+请基于所有历史尝试和当前评估结果,生成下一步的query修改策略。
|
|
|
+
|
|
|
+重点分析:
|
|
|
+
|
|
|
+1. **当前推荐词的信号**:
|
|
|
+ - 系统理解成什么主题了?(旅游?教程?素材?工具?品种?)
|
|
|
+ - 推荐词揭示了什么信息?系统在哪个方向有内容?
|
|
|
+ - **不要只看essence_score**:essence=0的推荐词也可能是好的探索起点
|
|
|
+ - 哪个推荐词最有潜力作为下一步的桥梁?
|
|
|
+
|
|
|
+2. **历史趋势分析**:
|
|
|
+ - 推荐词的主题变化:从"品种介绍"→"旅游"→"摄影"?
|
|
|
+ - 是否在逐步接近目标?还是原地打转(主题不变)?
|
|
|
+ - 哪些query让系统理解方向改变了?
|
|
|
+
|
|
|
+3. **确定探索目的**:
|
|
|
+ - 下一步query的探索目的是什么?
|
|
|
+ * 验证系统对某个词的理解?
|
|
|
+ * 往某个方向引导系统?
|
|
|
+ * 利用推荐词作为桥梁?
|
|
|
+ - **记住**:中间query不需要满足原需求,关键是达成探索目的
|
|
|
+"""
|
|
|
+ result = await Runner.run(strategy_generator, strategy_input)
|
|
|
+ strategy: ModificationStrategy = result.final_output
|
|
|
+ return strategy
|
|
|
+
|
|
|
+
|
|
|
+def find_qualified_queries(evaluations: list[dict]) -> dict:
|
|
|
+ """分级查找合格query
|
|
|
+
|
|
|
+ Returns:
|
|
|
+ {
|
|
|
+ "highly_qualified": [...], # 高度满足:knowledge=1, motivation>=0.9, relevance>=0.9
|
|
|
+ "moderately_qualified": [...], # 中高满足:knowledge=1, motivation>=0.9, relevance>=0.7
|
|
|
+ "lower_qualified": [...], # 中低满足:knowledge=1, motivation>=0.9, relevance>=0.4
|
|
|
+ }
|
|
|
+ """
|
|
|
+ # 高度满足:knowledge=1, motivation>=0.9, relevance>=0.9
|
|
|
+ highly_qualified = [
|
|
|
+ e for e in evaluations
|
|
|
+ if e['knowledge_recognition'] == 1
|
|
|
+ and e['motivation_score'] >= 0.9
|
|
|
+ and e['relevance_score'] >= 0.9
|
|
|
+ ]
|
|
|
+
|
|
|
+ # 中高满足:knowledge=1, motivation>=0.9, 0.7<=relevance<0.9
|
|
|
+ moderately_qualified = [
|
|
|
+ e for e in evaluations
|
|
|
+ if e['knowledge_recognition'] == 1
|
|
|
+ and e['motivation_score'] >= 0.9
|
|
|
+ and 0.7 <= e['relevance_score'] < 0.9
|
|
|
+ ]
|
|
|
+
|
|
|
+ # 中低满足:knowledge=1, motivation>=0.9, 0.4<=relevance<0.7
|
|
|
+ lower_qualified = [
|
|
|
+ e for e in evaluations
|
|
|
+ if e['knowledge_recognition'] == 1
|
|
|
+ and e['motivation_score'] >= 0.9
|
|
|
+ and 0.4 <= e['relevance_score'] < 0.7
|
|
|
+ ]
|
|
|
+
|
|
|
+ return {
|
|
|
+ "highly_qualified": sorted(highly_qualified, key=lambda x: x['relevance_score'], reverse=True),
|
|
|
+ "moderately_qualified": sorted(moderately_qualified, key=lambda x: x['relevance_score'], reverse=True),
|
|
|
+ "lower_qualified": sorted(lower_qualified, key=lambda x: x['relevance_score'], reverse=True),
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+# ============================================================================
|
|
|
+# 主流程(代码控制)
|
|
|
+# ============================================================================
|
|
|
+
|
|
|
+async def optimize_query(context: RunContext, max_rounds: int = 20) -> dict:
|
|
|
+ """
|
|
|
+ 主优化流程 - 由代码控制
|
|
|
+
|
|
|
+ Args:
|
|
|
+ context: 运行上下文
|
|
|
+ max_rounds: 最大迭代轮数,默认20
|
|
|
+
|
|
|
+ 返回格式:
|
|
|
+ {
|
|
|
+ "success": True/False,
|
|
|
+ "result": {...} or None,
|
|
|
+ "message": "..."
|
|
|
+ }
|
|
|
+ """
|
|
|
+ # 1. 标注问题(仅一次)
|
|
|
+ annotation = await annotate_question(context.q_with_context)
|
|
|
+ context.question_annotation = annotation
|
|
|
+
|
|
|
+ # 2. 迭代优化
|
|
|
+ current_query = context.q
|
|
|
+
|
|
|
+ for round_num in range(1, max_rounds + 1):
|
|
|
+ print(f"\n{'='*60}")
|
|
|
+ print(f"第 {round_num} 轮:{'使用原始问题' if round_num == 1 else '使用修改后的query'}")
|
|
|
+ print(f"当前query: {current_query}")
|
|
|
+ print(f"{'='*60}")
|
|
|
+
|
|
|
+ # 获取推荐词并评估
|
|
|
+ evaluations = await get_suggestions_with_eval(current_query, annotation, context)
|
|
|
+
|
|
|
+ if evaluations:
|
|
|
+ # 检查是否找到合格query(分级筛选)
|
|
|
+ qualified = find_qualified_queries(evaluations)
|
|
|
+
|
|
|
+ # 优先返回高度满足的query
|
|
|
+ if qualified["highly_qualified"]:
|
|
|
+ return {
|
|
|
+ "success": True,
|
|
|
+ "level": "highly_qualified",
|
|
|
+ "results": qualified["highly_qualified"],
|
|
|
+ "message": f"第{round_num}轮找到{len(qualified['highly_qualified'])}个高度满足的query(知识=1, 动机≥0.9, 相关性≥0.9)"
|
|
|
+ }
|
|
|
+
|
|
|
+ # 其次返回中高满足的query
|
|
|
+ if qualified["moderately_qualified"]:
|
|
|
+ return {
|
|
|
+ "success": True,
|
|
|
+ "level": "moderately_qualified",
|
|
|
+ "results": qualified["moderately_qualified"],
|
|
|
+ "message": f"第{round_num}轮找到{len(qualified['moderately_qualified'])}个中高满足的query(知识=1, 动机≥0.9, 相关性≥0.7)"
|
|
|
+ }
|
|
|
+
|
|
|
+ # 如果是最后一轮,不再生成策略
|
|
|
+ if round_num == max_rounds:
|
|
|
+ break
|
|
|
+
|
|
|
+ # 生成修改策略
|
|
|
+ print(f"\n--- 生成修改策略 ---")
|
|
|
+ strategy = await generate_modification_strategy(current_query, evaluations, annotation, context)
|
|
|
+
|
|
|
+ print(f"\n修改策略:")
|
|
|
+ print(f" 推理过程:{strategy.reasoning}")
|
|
|
+ print(f" 策略类型:{strategy.strategy_type}")
|
|
|
+ print(f" 操作类型:{strategy.operation_type}")
|
|
|
+ print(f" 基础query:{strategy.base_query} (来源: {strategy.base_query_source})")
|
|
|
+ print(f" 修改动作:{', '.join(strategy.modification_actions)}")
|
|
|
+ print(f" 新query:{strategy.new_query}")
|
|
|
+
|
|
|
+ # 记录修改
|
|
|
+ context.operations_history.append({
|
|
|
+ "operation_type": "modify_query",
|
|
|
+ "timestamp": datetime.now().isoformat(),
|
|
|
+ "reasoning": strategy.reasoning,
|
|
|
+ "strategy_type": strategy.strategy_type,
|
|
|
+ "operation_type_detail": strategy.operation_type,
|
|
|
+ "base_query": strategy.base_query,
|
|
|
+ "base_query_source": strategy.base_query_source,
|
|
|
+ "modification_actions": strategy.modification_actions,
|
|
|
+ "original_query": current_query,
|
|
|
+ "new_query": strategy.new_query,
|
|
|
+ })
|
|
|
+
|
|
|
+ # 更新当前query
|
|
|
+ current_query = strategy.new_query
|
|
|
+
|
|
|
+ # 所有轮次后仍未找到高度/中高满足的,降低标准查找
|
|
|
+ print(f"\n{'='*60}")
|
|
|
+ print(f"{max_rounds}轮后未找到高度/中高满足的query,降低标准(相关性 >= 0.4)")
|
|
|
+ print(f"{'='*60}")
|
|
|
+
|
|
|
+ qualified = find_qualified_queries(evaluations)
|
|
|
+ if qualified["lower_qualified"]:
|
|
|
+ return {
|
|
|
+ "success": True,
|
|
|
+ "level": "lower_qualified",
|
|
|
+ "results": qualified["lower_qualified"],
|
|
|
+ "message": f"{max_rounds}轮后找到{len(qualified['lower_qualified'])}个中低满足的query(知识=1, 动机≥0.9, 相关性≥0.4)"
|
|
|
+ }
|
|
|
+
|
|
|
+ # 完全失败:找出最接近的(只满足知识识别,但动机不够)
|
|
|
+ knowledge_ok = [
|
|
|
+ e for e in evaluations
|
|
|
+ if e['knowledge_recognition'] == 1
|
|
|
+ ]
|
|
|
+ if knowledge_ok:
|
|
|
+ # 返回所有满足knowledge的,按motivation_score降序
|
|
|
+ closest_queries = sorted(knowledge_ok, key=lambda x: x['motivation_score'], reverse=True)
|
|
|
+ return {
|
|
|
+ "success": False,
|
|
|
+ "level": "failed",
|
|
|
+ "results": closest_queries[:5], # 只返回前5个
|
|
|
+ "message": f"未找到合格query,但有{len(closest_queries)}个是知识需求(knowledge=1,但motivation<0.9)"
|
|
|
+ }
|
|
|
+
|
|
|
+ return {
|
|
|
+ "success": False,
|
|
|
+ "level": "failed",
|
|
|
+ "results": [],
|
|
|
+ "message": "未找到任何知识类推荐词(所有推荐词的knowledge_recognition均为0)"
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+# ============================================================================
|
|
|
+# 输出格式化
|
|
|
+# ============================================================================
|
|
|
+
|
|
|
+def format_output(optimization_result: dict, context: RunContext) -> str:
|
|
|
+ """格式化输出结果"""
|
|
|
+ results = optimization_result.get("results", [])
|
|
|
+ level = optimization_result.get("level", "")
|
|
|
+
|
|
|
+ # 满足程度映射
|
|
|
+ level_map = {
|
|
|
+ "highly_qualified": "高度满足 (90-100%)",
|
|
|
+ "moderately_qualified": "中高满足 (70-89%)",
|
|
|
+ "lower_qualified": "中低满足 (40-69%)",
|
|
|
+ "failed": "未通过"
|
|
|
+ }
|
|
|
+
|
|
|
+ if optimization_result["success"] and results:
|
|
|
+ output = f"原始问题:{context.q}\n"
|
|
|
+ output += f"满足程度:{level_map.get(level, '未知')}\n"
|
|
|
+ output += f"状态:{optimization_result['message']}\n\n"
|
|
|
+ output += "推荐query(按相关性降序):\n"
|
|
|
+ for i, result in enumerate(results, 1):
|
|
|
+ output += f"\n{i}. {result['query']}\n"
|
|
|
+ output += f" - 知识识别:{'是' if result['knowledge_recognition'] == 1 else '否'} ({result['knowledge_recognition_reason'][:50]}...)\n"
|
|
|
+ output += f" - 动机匹配度:{result['motivation_score']:.2f} (≥0.9通过)\n"
|
|
|
+ output += f" * 核心意图动词: {result['motivation_breakdown'].get('核心意图动词', 0):.2f}\n"
|
|
|
+ output += f" * 目标对象: {result['motivation_breakdown'].get('目标对象', 0):.2f}\n"
|
|
|
+ output += f" * 终极目的: {result['motivation_breakdown'].get('终极目的', 0):.2f}\n"
|
|
|
+ output += f" - 相关性得分:{result['relevance_score']:.2f} (≥0.9高度满足)\n"
|
|
|
+ output += f" * 核心动作: {result['relevance_breakdown'].get('核心动作', 0):.2f}\n"
|
|
|
+ output += f" * 目标对象: {result['relevance_breakdown'].get('目标对象', 0):.2f}\n"
|
|
|
+ output += f" * 使用场景: {result['relevance_breakdown'].get('使用场景', 0):.2f}\n"
|
|
|
+ output += f" * 终极目的: {result['relevance_breakdown'].get('终极目的', 0):.2f}\n"
|
|
|
+ output += f" - 综合评估:{result['overall_reason'][:100]}...\n"
|
|
|
+ return output.strip()
|
|
|
+ else:
|
|
|
+ output = f"原始问题:{context.q}\n"
|
|
|
+ output += f"结果:未找到合格推荐query\n"
|
|
|
+ output += f"满足程度:{level_map.get(level, '未知')}\n"
|
|
|
+ output += f"原因:{optimization_result['message']}\n"
|
|
|
+
|
|
|
+ if results:
|
|
|
+ output += "\n最接近的推荐词:\n"
|
|
|
+ for i, result in enumerate(results[:3], 1): # 只显示前3个
|
|
|
+ output += f"\n{i}. {result['query']}\n"
|
|
|
+ output += f" - 知识识别:{'是' if result['knowledge_recognition'] == 1 else '否'}\n"
|
|
|
+ output += f" - 动机匹配度:{result['motivation_score']:.2f}\n"
|
|
|
+ output += f" - 相关性得分:{result['relevance_score']:.2f}\n"
|
|
|
+ output += f" - 综合评估:{result['overall_reason'][:100]}...\n"
|
|
|
+
|
|
|
+ output += "\n建议:尝试简化问题或调整需求描述"
|
|
|
+ return output.strip()
|
|
|
+
|
|
|
+
|
|
|
+# ============================================================================
|
|
|
+# 主函数
|
|
|
+# ============================================================================
|
|
|
+
|
|
|
+async def main(input_dir: str, max_rounds: int = 20):
|
|
|
+ current_time, log_url = set_trace()
|
|
|
+
|
|
|
+ # 从目录中读取固定文件名
|
|
|
+ input_context_file = os.path.join(input_dir, 'context.md')
|
|
|
+ input_q_file = os.path.join(input_dir, 'q.md')
|
|
|
+
|
|
|
+ q_context = read_file_as_string(input_context_file)
|
|
|
+ q = read_file_as_string(input_q_file)
|
|
|
+ q_with_context = f"""
|
|
|
+<需求上下文>
|
|
|
+{q_context}
|
|
|
+</需求上下文>
|
|
|
+<当前问题>
|
|
|
+{q}
|
|
|
+</当前问题>
|
|
|
+""".strip()
|
|
|
+
|
|
|
+ # 获取当前文件名作为版本
|
|
|
+ version = os.path.basename(__file__)
|
|
|
+ version_name = os.path.splitext(version)[0]
|
|
|
+
|
|
|
+ # 日志保存目录
|
|
|
+ log_dir = os.path.join(input_dir, "output", version_name, current_time)
|
|
|
+
|
|
|
+ run_context = RunContext(
|
|
|
+ version=version,
|
|
|
+ input_files={
|
|
|
+ "input_dir": input_dir,
|
|
|
+ "context_file": input_context_file,
|
|
|
+ "q_file": input_q_file,
|
|
|
+ },
|
|
|
+ q_with_context=q_with_context,
|
|
|
+ q_context=q_context,
|
|
|
+ q=q,
|
|
|
+ log_dir=log_dir,
|
|
|
+ log_url=log_url,
|
|
|
+ )
|
|
|
+
|
|
|
+ # 执行优化流程(代码控制)
|
|
|
+ optimization_result = await optimize_query(run_context, max_rounds=max_rounds)
|
|
|
+
|
|
|
+ # 格式化输出
|
|
|
+ final_output = format_output(optimization_result, run_context)
|
|
|
+ print(f"\n{'='*60}")
|
|
|
+ print("最终结果")
|
|
|
+ print(f"{'='*60}")
|
|
|
+ print(final_output)
|
|
|
+
|
|
|
+ # 保存结果
|
|
|
+ run_context.optimization_result = optimization_result
|
|
|
+ run_context.final_output = final_output
|
|
|
+
|
|
|
+ # 保存 RunContext 到 log_dir
|
|
|
+ os.makedirs(run_context.log_dir, exist_ok=True)
|
|
|
+ context_file_path = os.path.join(run_context.log_dir, "run_context.json")
|
|
|
+ with open(context_file_path, "w", encoding="utf-8") as f:
|
|
|
+ json.dump(run_context.model_dump(), f, ensure_ascii=False, indent=2)
|
|
|
+ print(f"\nRunContext saved to: {context_file_path}")
|
|
|
+
|
|
|
+
|
|
|
+if __name__ == "__main__":
|
|
|
+ parser = argparse.ArgumentParser(description="搜索query优化工具")
|
|
|
+ parser.add_argument(
|
|
|
+ "--input-dir",
|
|
|
+ type=str,
|
|
|
+ default="input/简单扣图",
|
|
|
+ help="输入目录路径,默认: input/简单扣图"
|
|
|
+ )
|
|
|
+ parser.add_argument(
|
|
|
+ "--max-rounds",
|
|
|
+ type=int,
|
|
|
+ default=20,
|
|
|
+ help="最大迭代轮数,默认: 20"
|
|
|
+ )
|
|
|
+ args = parser.parse_args()
|
|
|
+
|
|
|
+ asyncio.run(main(args.input_dir, max_rounds=args.max_rounds))
|