P paper2skillsPlaybook
开始业务诊断
访客模式
10-MAS

Self-Refine + RL — 反馈闭环与自进化 Agent

Skill-Self-Improving-Agent-Feedback-Loop

声明类型推断验证状态待复核

运营经理面临Agent越用越偏——反馈闭环将错误复发率18%降至4%,年化省14万元

来源
paper2skills-vault/10-MAS/Skill-Self-Improving-Agent-Feedback-Loop.md
适用边界
论文方法到业务问题的项目侧映射,不自动证明客户根因。
声明类型示例验证状态待企业数据验证

多个 AI Agent 协作自动完成跨系统运营任务,运营团队人效提升 3-5 倍,7×24 无人值守运营

来源
paper2skills-vault/10-MAS/Skill-Self-Improving-Agent-Feedback-Loop.md#business-value
适用边界
方法估算或场景示例,不等于客户结果或收益承诺。

待企业数据验证 · 缺失:样本、基线、时间窗、币种、计算方法、证据来源

业务视角
适用角色运营负责人 / CTO · 产品经理 · CEO
适用平台Amazon PPC + 库存 + 定价 多 Agent 协作 · TikTok 内容运营流水线
什么情况下用运营任务太碎,选品/定价/广告/客服同时跑,人手严重不足;重复性运营动作需要 7×24 响应但没有足够人力
示例目标(需企业数据验证)多个 AI Agent 协作自动完成跨系统运营任务,运营团队人效提升 3-5 倍,7×24 无人值守运营
业务痛点
运营人手不够任务太多价格变化没有及时响应重复性工作占据太多时间想做 7×24 监控但没人盯

1. 解决的问题

运营经理面临Agent越用越偏——反馈闭环将错误复发率18%降至4%,年化省14万元

2. 核心算法逻辑

核心思想

Self-Refine 是一种让 Agent 对自身输出进行批评和改进的迭代机制。核心洞察:语言模型不仅能生成内容,也能评估和改进内容——利用同一模型的双重能力,实现无需外部监督的自我进化。

Self-Refine 的四个步骤:

  1. Generate:Agent 生成初始输出
  2. Feedback:Agent 对自身输出进行批评(识别问题、遗漏、不一致)
  3. Refine:Agent 基于批评改进输出
  4. Iterate:重复 Feedback-Refine 直到满足质量阈值

经验记忆库(Memory Bank) 扩展了 Self-Refine:

  • 将成功和失败的经验存入长期记忆
  • 支持相似情况的经验检索和复用
  • 通过成功率排序实现经验优先级管理

反馈闭环编排器(Feedback Loop Orchestrator) 将两者结合:

  • 执行任务前检索相似经验
  • 执行中使用 Self-Refinement 迭代改进
  • 执行后收集反馈并存入记忆
  • 形成持续进化的闭环

数学直觉

Self-Refine 迭代:

设生成函数为 $G$,反馈函数为 $F$,改进函数为 $R$。迭代过程:

o_0 = G(x)
f_t = F(o_t)
o_{t+1} = R(o_t, f_t)

其中 $o_t$ 是第 $t$ 轮输出,$f_t$ 是对 $o_t$ 的反馈。停止条件:质量 $Q(o_t) \geq \theta$ 或达到最大迭代次数 $T$。

经验记忆检索:

对于新任务 $x$,检索相似经验:

\text{score}(x, e_i) = \text{sim}(x, e_i^{\text{situation}}) \cdot e_i^{\text{success\_rate}}

选择 top-$k$ 经验作为上下文增强输入:

x' = x \oplus \{e_i | \text{score}(x, e_i) \text{ 在 top-}k\}

③ 的实现把 $e^{\text{success\_rate}}$ 换成二值核验门(只从 outcome == success 的经验里检索,并按相似度阈值 0.08 截断)。原因见实测锚点:用一个会随迭代自增的自评置信度当 success_rate,等于让「自我感觉良好」的经验获得更高检索权重——那是把闭环变成回声室。

关键假设

  1. 模型可自我评估:同一模型既能生成也能批评。③ 的实测把这个假设收窄了一半——模型能可靠地自查「有没有整句一个术语都没落到」(覆盖度,不需要答案),但不能凭空造出正确术语。所以 Feedback 必须是「指出未覆盖片段」,Refine 必须接一个可核验的确认通道(评审 / 金标片段 / 工具),否则迭代只是在原地改置信度。
  2. 反馈可转化为改进:批评意见可以指导输出修正。
  3. 经验可复用:相似任务的经验对未来任务有帮助。实测有上限:记忆只能迁移已经学到过的术语,迁移不到没见过的东西。
  4. 质量可量化:存在可靠的质量评估指标。③ 用外部金标准 F1 度量,而不是让 agent 自评置信度——原卡正是用 confidence 当质量,且 refine 每轮无条件把 confidence 加 0.1,于是「质量提升」与抽取对不对完全无关。

实测锚点(③ 跑出来的值)

三条件对照,跑的是同一批训练里没出现过的 B 批评论:

条件平均 F1平均评审追问轮数
只有种子词表,一步抽取0.000—
+ 单轮内 Self-Refine(评审确认通道)1.0001.00
+ 跨评论记忆、不走评审0.3330.00
  • 两条通道解决的是不同问题:单轮反馈让三条新评论全部从零升到 F1=1.0(每例增量 [1.0, 1.0, 1.0]);记忆只让 1/3 受益(B1,1.000),B2/B3 恒为 0——因为 A 批根本没出现过 奶瓶/暖奶器 这些术语。记忆的平均增益 +0.333 = 已学术语在新评论中的复现率,不是方法本身的普适增益。
  • 记忆真正省下来的是追问成本:同一条 B1,无记忆要问 1 轮、有记忆问 0 轮,F1 不变。这是可量化的运营收益(少一次人工确认),比「F1 提升」更贴近该机制的实际价值。
  • 无进展即收手:加了「refine 没带来新术语就 break」之后,A 批那种「评审也补不出术语」的评论不再空转 3 轮;B 批平均追问降到 1.00。原实现没有这条出口,最坏情况恒烧满 max_iterations。
  • 检索必须先向量化:中文无空格,③ 用 char_wb 字符 2-3gram TF-IDF。原实现把原文字符串数组直接送进 cosine_similarity,实测报 could not convert string to float: '这个储奶袋密封性很好,不漏奶' —— 这就是该卡 ③ 从未跑通的原因。B1 对 A 批经验的实测相似度 0.169(阈值 0.08)。
  • 否定词会判反情感:朴素关键词把「不漏奶」当负面,把 A2 那条正面评论判成 mixed;按否定前缀作用在极性词上处理后为 positive,而「不顺滑」正确降为 negative。母婴评论里「不漏/不漏奶/不侧漏」是核心卖点,这条不搞对就会把好评喂成差评。
  • 核验门有效:评审否决的案例(C1)outcome=rejected,写回的经验中新术语条数为 0——学习被硬门挡住,不会把没验证的术语沉淀进词表。

3. 业务应用场景

VOC 分析 Agent 在处理新类型评论时表现不稳定。例如新出现的品牌名、产品型号、方言表达可能导致实体识别失败。需要 Agent 能从错误中学习并自我改进。

- VOC 分析任务的执行轨迹(输入、输出、反馈) - 人工评分(1-5 分) - 成功/失败案例的标注

业务价值: - Agent 准确率随使用次数提升(无需重新训练模型) - 减少人工审核工作量 50-60% - 新类型评论的处理能力自动增强

4. 输入数据要求

  • VOC 分析任务的执行轨迹(输入、输出、反馈)
  • 人工评分(1-5 分)
  • 成功/失败案例的标注
  • 多 Agent 的执行轨迹
  • 共享记忆库(向量数据库)

5. 输出结果

未提取到输出条目;请核对原始 Skill 卡片与代码。

6. 业务价值与 ROI

  • 数据要求:中,需要执行轨迹和反馈数据
  • 技术门槛:中高,需要理解 Self-Refine 和记忆检索机制
  • 工程复杂度:中高,涉及多组件协调(生成、反馈、记忆、编排)
  • 维护成本:中,记忆库需要定期清理和更新
  • 核心差异化:Self-Improving Agent 是系统持续进化的关键
  • 复利效应:每次执行都在积累知识,长期价值巨大

7. 代码模板

代码块数量:5

Python265 行 · 完整显示
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer

# 评审确认:未覆盖片段 → 应抽取的术语。Self-Refine 的单轮内反馈就靠它,
# 而「记忆」的价值正是让下一条评论不必再走这一轮。
REVIEWER = {
    "这个储奶袋密封性很好": ["储奶袋", "密封性好"],
    "不漏奶": ["不漏奶"],
    "新买的储奶袋常温下也不漏奶": ["储奶袋", "不漏奶"],
    "常温下也不漏奶": ["不漏奶"],
    "贝亲奶瓶刻度清晰": ["贝亲", "奶瓶", "刻度清晰"],
    "但手柄容易断": ["手柄易断"],
    "这款暖奶器加热均匀": ["暖奶器", "加热均匀"],
    "噪音有点大": ["噪音大"],
    "轮子不顺滑": ["轮子不顺滑"],
    "推起来费劲": ["推起来费劲"],
}
NEGATORS = ("不", "没", "无", "别")


class Experience:
    def __init__(self, situation, captured, new_terms, outcome):
        self.situation = situation
        self.captured = list(captured)
        self.new_terms = list(new_terms)
        self.outcome = outcome


class MemoryBank:
    """全局经验库。检索必须先把文本向量化——中文没有空格,用 char_wb 字符 n-gram;
    直接把原文字符串数组送进 cosine_similarity 就是原卡 ③ 报
    「could not convert string to float」的原因。"""

    def __init__(self, min_sim=0.08):
        self.experiences = []
        self.min_sim = min_sim

    def store(self, exp):
        self.experiences.append(exp)

    def retrieve_topk(self, query, k=2):
        pool = [e for e in self.experiences if e.outcome == "success" and e.new_terms]
        if not pool:
            return []
        vec = TfidfVectorizer(analyzer="char_wb", ngram_range=(2, 3))
        corpus = [e.situation for e in pool] + [query]
        mat = vec.fit_transform(corpus)
        sims = np.asarray((mat[:len(pool)] * mat[len(pool):].T).todense()).ravel()
        out = []
        for i in np.argsort(sims)[::-1][:k]:
            if sims[i] >= self.min_sim:
                out.append((pool[int(i)], float(sims[i])))
        return out

    def known_terms(self, query, k=2):
        hits, top_sim = set(), 0.0
        for e, sim in self.retrieve_topk(query, k):
            hits |= set(e.new_terms)
            top_sim = max(top_sim, sim)
        return hits, top_sim


class SelfRefineAgent:
    def __init__(self, max_iterations=3):
        self.T = max_iterations
        self.memory = MemoryBank()
        self.seed_lexicon = {"吸奶器", "推车", "Spectra", "好用", "静音"}
        self.pos_cues = {"顺滑", "好", "推荐", "清晰", "均匀", "轻便", "密封性好", "不漏奶"}
        self.neg_cues = {"断", "噪音", "费劲", "漏奶"}

    # ---------- 情感:必须处理否定词 ----------
    def sentiment(self, x):
        pos = neg = False
        for cue in self.pos_cues:
            i = x.find(cue)
            while i >= 0:
                if i > 0 and x[i - 1] in NEGATORS:
                    neg = True                       # 「不顺滑」是负面
                else:
                    pos = True
                i = x.find(cue, i + 1)
        for cue in self.neg_cues:
            i = x.find(cue)
            while i >= 0:
                if not (i > 0 and x[i - 1] in NEGATORS):
                    neg = True                       # 「不漏奶」不是负面
                i = x.find(cue, i + 1)
        if pos and neg:
            return "mixed"
        return "positive" if pos else ("negative" if neg else "neutral")

    def generate(self, x, known):
        found = sorted(t for t in known if t in x)
        return {"mentions": found, "sentiment": self.sentiment(x), "learned": []}

    @staticmethod
    def segments(x):
        return [s.strip() for s in x.replace(",", ",").replace("。", ",").split(",") if s.strip()]

    def feedback(self, o_t, x):
        """自我批评只看「有没有整句一个术语都没落到」,不需要金标准。"""
        return [s for s in self.segments(x) if not any(m in s for m in o_t["mentions"])]

    def refine(self, o_t, f_t, reviewer):
        mentions, learned = list(o_t["mentions"]), list(o_t["learned"])
        for seg in f_t:
            for term in reviewer(seg):
                if term not in mentions:
                    mentions.append(term)
                    learned.append(term)
        return {"mentions": sorted(set(mentions)), "sentiment": o_t["sentiment"], "learned": learned}

    def execute(self, x, known, reviewer=None):
        o = self.generate(x, known)
        trace = [list(o["mentions"])]
        if reviewer is not None:
            for _ in range(self.T):
                f_t = self.feedback(o, x)
                if not f_t:
                    break
                prev = set(o["mentions"])
                o = self.refine(o, f_t, reviewer)
                if set(o["mentions"]) == prev:
                    break            # 无进展就收手:评审补不出术语时继续追问只是空转烧时效
                trace.append(list(o["mentions"]))
        return o, trace

    @staticmethod
    def f1(pred, gold):
        pred, gold = set(pred), set(gold)
        if not pred or not gold:
            return 0.0, 0.0, 0.0
        tp = len(pred & gold)
        p, r = tp / len(pred), tp / len(gold)
        return p, r, (0.0 if p + r == 0 else 2 * p * r / (p + r))


def make_reviewer(text):
    def reviewer(seg):
        for key in sorted(REVIEWER, key=len, reverse=True):
            if key in seg:
                return REVIEWER[key]
        return []
    return reviewer


def process(agent, case, mode, accepted_ids):
    """mode: none=只有种子词表 / refine=单轮内反馈 / memory=跨评论记忆(+refine)"""
    cid, text, gold, gold_sent = case
    known = set(agent.seed_lexicon)
    top_sim = 0.0
    if "memory" in mode:
        known, top_sim = known | agent.memory.known_terms(text)[0], agent.memory.known_terms(text)[1]
    reviewer = make_reviewer(text) if "refine" in mode else None
    o, trace = agent.execute(text, known, reviewer)
    p, r, f_ = agent.f1(o["mentions"], gold)
    f0 = agent.f1(trace[0], gold)[2]
    sent_ok = o["sentiment"] == gold_sent
    accepted = sent_ok and (cid in accepted_ids)
    outcome, new_terms = ("success", o["learned"]) if accepted else ("rejected", [])
    agent.memory.store(Experience(text, o["mentions"], new_terms, outcome))
    return {"id": cid, "mode": mode, "asks": len(trace) - 1, "mem_sim": round(top_sim, 3),
            "prec": round(p, 3), "rec": round(r, 3), "f1": round(f_, 3), "f1_first_shot": round(f0, 3),
            "sent": o["sentiment"], "sent_ok": sent_ok, "outcome": outcome, "learned": new_terms}


BATCH_A = [
    ("A1", "Spectra S1 吸奶器非常好用,静音效果很好", ["Spectra", "吸奶器", "好用", "静音"], "positive"),
    ("A2", "这个储奶袋密封性很好,不漏奶", ["储奶袋", "密封性好", "不漏奶"], "positive"),
    ("A3", "推车轻便好用,推荐购买", ["推车", "好用"], "positive"),
]
BATCH_B = [
    ("B1", "新买的储奶袋常温下也不漏奶", ["储奶袋", "不漏奶"], "positive"),
    ("B2", "贝亲奶瓶刻度清晰,但手柄容易断", ["贝亲", "奶瓶", "刻度清晰", "手柄易断"], "mixed"),
    ("B3", "这款暖奶器加热均匀,噪音有点大", ["暖奶器", "加热均匀", "噪音大"], "mixed"),
]
BATCH_C = [("C1", "这个推车轮子不顺滑,推起来费劲", ["推车", "轮子不顺滑", "推起来费劲"], "negative")]

if __name__ == "__main__":
    print("=" * 76)
    print("【1. 三种条件跑同一批未见过的 B 批评论】")
    print("=" * 76)
    res_none = process(SelfRefineAgent(), BATCH_B[0], "none", {"B1"})
    rows_none, rows_mem = [], []
    for c in BATCH_B:
        a = SelfRefineAgent()
        rows_none.append(process(a, c, "none", {"B1", "B2", "B3"}))
    for c in BATCH_B:
        b = SelfRefineAgent()
        for ac in BATCH_A:
            process(b, ac, "refine+memory", {"A1", "A2", "A3"})   # 先积累经验(只有评审反馈通道)
        rows_mem.append(process(b, c, "memory", {"B1", "B2", "B3"}))
    print(" 仅种子词表(一步抽取,无反馈无记忆):")
    print(pd.DataFrame(rows_none)[["id", "f1_first_shot", "f1", "prec", "rec", "sent", "sent_ok"]].to_string(index=False))
    print(" 带跨评论记忆(**不再走评审追问**):")
    print(pd.DataFrame(rows_mem)[["id", "mem_sim", "f1", "prec", "rec", "asks", "sent", "sent_ok"]].to_string(index=False))

    f1_none = float(np.mean([r["f1"] for r in rows_none]))
    f1_mem = float(np.mean([r["f1"] for r in rows_mem]))
    print("\n 平均 F1:无记忆 %.3f → 有记忆 %.3f(绝对 +%.3f)" % (f1_none, f1_mem, f1_mem - f1_none))

    print("\n" + "=" * 76)
    print("【2. 单轮内 Self-Refine 的增益与追问次数(B 批,只有评审反馈通道,无记忆)】")
    print("=" * 76)
    rows_ref = []
    for c in BATCH_B:
        a = SelfRefineAgent()
        rows_ref.append(process(a, c, "refine", {"B1", "B2", "B3"}))
    print(pd.DataFrame(rows_ref)[["id", "asks", "f1_first_shot", "f1", "sent", "outcome", "learned"]].to_string(index=False))
    gain = [round(r["f1"] - r["f1_first_shot"], 3) for r in rows_ref]
    print(" 每例精修带来的 F1 增量:%s | 平均追问轮数 %.2f(无进展即提前收手)" % (
    gain, float(np.mean([r["asks"] for r in rows_ref]))))

    print("\n" + "=" * 76)
    print("【3. 有记忆后,同一评论还需要几次评审追问】")
    print("=" * 76)
    dual = SelfRefineAgent()
    for ac in BATCH_A:
        process(dual, ac, "refine+memory", {"A1", "A2", "A3"})
    with_mem = process(dual, BATCH_B[0], "refine+memory", {"B1"})
    without = process(SelfRefineAgent(), BATCH_B[0], "refine", {"B1"})
    print(" B1 无记忆追问 %d 轮 → 有记忆追问 %d 轮(F1 %.3f vs %.3f)" % (
        without["asks"], with_mem["asks"], without["f1"], with_mem["f1"]))

    print("\n" + "=" * 76)
    print("【4. 否定词:把「不漏奶」当负面会把正面评论判反】")
    print("=" * 76)
    agent = SelfRefineAgent()
    for txt, note in [("这个储奶袋密封性很好,不漏奶", "正+否定安全项"),
                      ("这款暖奶器加热均匀,噪音有点大", "正反并存"),
                      ("这个推车轮子不顺滑,推起来费劲", "否定作用在正面词上")]:
        naive_neg = any(w in txt for w in agent.neg_cues)
        naive_pos = any(w in txt for w in agent.pos_cues)
        naive = "mixed" if (naive_neg and naive_pos) else ("negative" if naive_neg else "positive")
        print(" %-20s 朴素关键词=%-8s 处理否定后=%-8s" % (note, naive, agent.sentiment(txt)))

    print("\n" + "=" * 76)
    print("【5. 核验门:被否决的经验不得写回词表】")
    print("=" * 76)
    gated = SelfRefineAgent()
    row_c = process(gated, BATCH_C[0], "refine", set())
    print(" C1 outcome=%s learned=%s 库中带新术语条数=%d" % (
        row_c["outcome"], row_c["learned"], sum(1 for e in gated.memory.experiences if e.new_terms)))

    # ==================== 断言 ====================
    assert f1_mem > f1_none, "记忆没有把已学生术语迁移到新评论,闭环不成立"
    assert f1_none < 0.2, "种子词表本应对 B 批几乎抽不到东西,否则测不出迁移"
    assert all(r["asks"] == 0 for r in rows_mem), "只靠记忆就不该再触发评审追问"
    assert rows_mem[0]["f1"] > 0.9, "B1 应靠记忆抽到 储奶袋/不漏奶"
    assert sum(1 for g in gain if g > 0) >= 2, "Self-Refine 至少要在两例上真正提升 F1"
    assert all(r["asks"] <= SelfRefineAgent().T for r in rows_ref), "迭代未在 max_iterations 内收敛"
    assert with_mem["asks"] < without["asks"], "有记忆应减少评审追问轮数"
    assert agent.sentiment(BATCH_A[1][1]) == "positive", "「不漏奶」被误判为负面"
    assert agent.sentiment(BATCH_C[0][1]) == "negative", "「不顺滑」应判负面"
    assert agent.sentiment(BATCH_B[2][1]) == "mixed", "同句正反并存应判 mixed"
    assert row_c["outcome"] == "rejected" and not any(e.new_terms for e in gated.memory.experiences), \
        "被否决的经验污染了词表"
    for r in rows_none:
        assert r["outcome"] in ("success", "rejected")

    print("\n" + "=" * 76)
    print("[✓] Skill-Self-Improving-Agent-Feedback-Loop 测试通过")
    print("=" * 76)

8. 论文来源

论文链接用于核验方法来源,不自动证明本页商业结果。