AI 应用上线后,团队最常问的问题是"怎么让它越用越好"。答案不是"换个更强的模型",而是建立一条从生产流量到改进的闭环:采集真实输入、收集反馈、识别失败模式、构建评测集、验证改进。这条闭环被称为"数据飞轮",它的核心不是数据量,而是数据的选择性与可验证性。
专业视角下,数据飞轮要回答三个问题:采什么(不是全部流量)、怎么标(不是全靠人工)、以及怎么证明改进有效。本文给出这条闭环的实现。
飞轮的原料是生产调用记录,但不是全部记录都有价值。采集时必须带上可用于后续分层的元数据:输入、输出、模型版本、prompt 版本、以及最重要的——用户是否对结果做了修改:
# flywheel/capture.py
from dataclasses import dataclass, asdict
from datetime import datetime
import json, hashlib
@dataclass
class Trace:
trace_id: str
ts: str
app: str
input_text: str
output_text: str
model: str
prompt_version: str
user_id: str
# 反馈字段:默认未知,由后续行为或显式评价填充
explicit_rating: int | None = None # 1-5
user_edited: bool | None = None
edited_text: str | None = None
outcome: str | None = None # "accepted" / "rejected" / "abandoned"
def make_trace(app, input_text, output_text, model, prompt_version, user_id) -> Trace:
tid = hashlib.sha256(
f"{app}:{input_text}:{datetime.utcnow().isoformat()}".encode()
).hexdigest()[:16]
return Trace(tid, datetime.utcnow().isoformat(), app, input_text,
output_text, model, prompt_version, user_id)
def record(t: Trace, sink) -> None:
sink.write(json.dumps(asdict(t), ensure_ascii=False) + "\n")user_edited 与 edited_text 是信息量最大的字段。用户改了哪里,直接暴露了模型的失败模式——是事实错误、格式不对、还是语气不合适。这比五星评分有信息量得多。
全量标注成本不可接受,随机抽样又会把预算浪费在"已经很好"的样本上。正确做法是分层采样:按不确定性、按输入类型、按历史失败率分配标注配额:
# flywheel/sample.py
import random
from collections import defaultdict
def stratified_sample(traces: list[Trace], budget: int) -> list[Trace]:
"""三层配额:高不确定性 50%、历史失败类型 30%、随机 20%"""
# 层 1:模型自评置信度低,或输出长度异常
uncertain = [t for t in traces if is_uncertain(t)]
# 层 2:历史失败率高的输入类别
risky = [t for t in traces if t.outcome in ("rejected", "abandoned")]
# 层 3:随机
rest = [t for t in traces if t not in uncertain and t not in risky]
quotas = [int(budget * 0.5), int(budget * 0.3), budget - int(budget * 0.5) - int(budget * 0.3)]
out = []
for pool, q in zip([uncertain, risky, rest], quotas):
random.shuffle(pool)
out.extend(pool[:q])
return out
def is_uncertain(t: Trace) -> bool:
# 简化判据:输出过短、含兜底话术、或用户编辑过
if t.user_edited:
return True
if len(t.output_text) < 20:
return True
return any(k in t.output_text for k in ("无法确定", "不确定", "可能"))分层采样的价值在于"单位标注成本的信息量"。同样标注 500 条,分层采样覆盖的失败模式数量可能是随机采样的数倍。
纯人工标注慢且贵,纯 LLM 标注不可信。折中方案是 LLM 先标、人工只复核"LLM 不确定或与规则冲突"的样本,把人力集中在最需要判断的地方:
# flywheel/label.py
from pydantic import BaseModel
from typing import Literal
class Label(BaseModel):
quality: Literal["good", "minor_issue", "major_issue", "wrong"]
issue_type: Literal["none", "factual", "format", "incomplete", "off_topic", "style"]
confidence: float
reason: str
LABEL_SYSTEM = """你是 AI 输出质量标注器。按以下标准标注:
- good:可直接使用
- minor_issue:小问题,稍作修改可用
- major_issue:需要大幅修改
- wrong:事实错误或答非所问
issue_type 选最严重的一个问题类型。confidence < 0.7 时标注为需人工复核。"""
async def auto_label(llm, trace: Trace) -> Label | None:
resp = await llm.json_call(
LABEL_SYSTEM,
f"输入:{trace.input_text}\n输出:{trace.output_text}",
Label.model_json_schema(),
)
label = Label.model_validate(resp.payload)
return label if label.confidence >= 0.7 else None # 低置信度交给人工confidence < 0.7 的样本进入人工队列,其余直接采用。人工复核的重点不是"重新标一遍",而是"校准 LLM 标注器的偏差"——定期抽检已自动标注的样本,看人工与 LLM 的一致率是否稳定。
标注完的样本不应只用于"看一眼",而应固化为可反复运行的评测集。每个用例带输入、期望输出(或判定标准)、以及来源 trace:
# flywheel/evalset.py
import json
from pathlib import Path
def build_eval_case(trace: Trace, label: Label, expected: str | None = None) -> dict:
return {
"id": trace.trace_id,
"input": trace.input_text,
"expected": expected or (trace.edited_text if trace.user_edited else trace.output_text),
"must_not_contain": extract_forbidden(trace),
"source": {"app": trace.app, "model": trace.model,
"prompt_version": trace.prompt_version},
"label": label.model_dump(),
}
def extract_forbidden(t: Trace) -> list[str]:
"""从被拒绝的样本中提取"不该出现"的内容,作为负向断言"""
if t.outcome == "rejected" and t.output_text:
return [t.output_text[:30]] if len(t.output_text) > 10 else []
return []
def append_cases(cases: list[dict], path: str = "eval/cases.jsonl") -> None:
with open(path, "a", encoding="utf-8") as f:
for c in cases:
f.write(json.dumps(c, ensure_ascii=False) + "\n")"从被拒绝样本中提取负向断言"是这一步的关键设计。正例告诉模型"该怎么答",负例告诉模型"不该怎么答",两者结合才能防止改进 A 问题时把 B 问题带回来。
飞轮的最后一环是用评测集验证每次变更。任何 prompt 修改、模型切换、工具变更,都必须跑一遍完整评测,与基线对比:
# flywheel/verify.py
def compare_runs(baseline: dict, candidate: dict, min_delta: float = 0.0) -> dict:
"""
baseline/candidate: {case_id: {"passed": bool, "score": float}}
"""
ids = set(baseline) & set(candidate)
fixed = [i for i in ids if not baseline[i]["passed"] and candidate[i]["passed"]]
broken = [i for i in ids if baseline[i]["passed"] and not candidate[i]["passed"]]
base_rate = sum(baseline[i]["passed"] for i in ids) / len(ids)
cand_rate = sum(candidate[i]["passed"] for i in ids) / len(ids)
return {
"baseline_pass_rate": round(base_rate, 4),
"candidate_pass_rate": round(cand_rate, 4),
"delta": round(cand_rate - base_rate, 4),
"fixed_cases": fixed,
"broken_cases": broken,
# 关键判据:不能"修好 10 个、弄坏 8 个"就算提升
"net_gain": len(fixed) - len(broken),
"ship": (cand_rate - base_rate >= min_delta) and len(broken) <= len(fixed),
}ship 的双重条件是防"指标虚高"的核心:通过率可以因为修好 10 个、弄坏 8 个而上升,但净收益只有 2。要求 broken <= fixed 保证改进不是以牺牲既有能力为代价。
飞轮的终极形态是把标注数据用于微调。但纪律是:只把"模型曾经失败、改进后成功"的样本纳入训练集,因为这些样本携带了最多的信息量。已经稳定通过的样本重复训练只会导致过拟合。
数据飞轮的专业性,体现在三条纪律上:采集带编辑痕迹而非只有评分、分层采样把标注预算花在高信息量样本上、改进验证要求"净收益为正"而非只看通过率。这三条做到,应用才会真的"越用越好";做不到,所谓的飞轮只是一堆无人查看的日志。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。