业务问题:AI 自动生成 Amazon/TikTok Shop Listing 时,容易写出“guaranteed safe”“no certification needed”等违规承诺,也可能泄露供应商联系人或测试报告中的 PII
Compliance-Scored Guardrail Orchestration — 合规评分 Best-of-N 守护编排
Skill-Compliance-Scored-Guardrail-Orchestration
上架前自动完成合规预扫描,0 合规下架事故,新市场合规准备时间从 3 个月缩短到 2 周
待企业数据验证 · 缺失:样本、基线、时间窗、币种、计算方法、证据来源
1. 解决的问题
业务问题:AI 自动生成 Amazon/TikTok Shop Listing 时,容易写出“guaranteed safe”“no certification needed”等违规承诺,也可能泄露供应商联系人或测试报告中的 PII
2. 核心算法逻辑
核心思想:把 LLM 自动生成的合规风险控制从“生成后人工看一眼”升级为同步的加权评分系统。系统并行生成多个候选输出,对每个候选运行 PII、内容安全、schema、领域规则和证据引用检查,计算合规得分;一旦最佳候选超过阈值就提前返回,否则进入人工复核。
数学直觉:
C(y) = sum_j w_j * g_j(y) / sum_j w_jg_j(y) 是规则 j 对候选输出 y 的通过程度,范围 [0,1];w_j 是规则严重度权重。高权重规则(如 PII 泄漏、违规承诺、缺强制安全字段)对最终分数影响更大。输出不只包含文本,还包含 attempts、latency、规则失败原因和 config version,方便审计。
关键假设:
- 合规规则可以拆成可执行 checker,并能返回
[0,1]分数。 - 自动发布阈值必须由业务和法务共同校准。
- 低于阈值不等于失败,而是转入 human review。
- 论文公开结果是 operational scenario comparison,不是随机 A/B test;业务迁移时应重新验证。
3. 业务应用场景
场景 A:Listing 合规文案自动发布门控
- 业务问题:AI 自动生成 Amazon/TikTok Shop Listing 时,容易写出“guaranteed safe”“no certification needed”等违规承诺,也可能泄露供应商联系人或测试报告中的 PII。 - 数据要求:候选 Listing 文案、目标市场、品类、供应商测试报告摘要、图片 OCR 文本、平台政策规则。 - 预期产出: - `compliance_score`,如 0.92。 - 命中规则:PII、schema、CPSC/FDA/EU GPSR 规则、证据引用。 - 决策:`accepted` / `human_review_required`。
场景 B:召回/认证行动摘要的人工复核路由
4. 输入数据要求
- 候选 Listing 文案、目标市场、品类、供应商测试报告摘要、图片 OCR 文本、平台政策规则。
- CPSC/RAPEX 更新、SKU 类目映射、测试报告、历史召回记录、客服投诉摘要。
5. 输出结果
- compliance_score,如 0.92。
- 命中规则:PII、schema、CPSC/FDA/EU GPSR 规则、证据引用。
- 决策:accepted / human_review_required。
- 审计元数据:attempts、threshold、violations。
- 通过 Best-of-N 选择最高合规摘要。
6. 业务价值与 ROI
- ROI 预估:以每日 300 条 AI 生成 Listing/客服/合规摘要计算,若 70% 达到自动通过阈值、每条节省 4 分钟人工初筛,则每月节省约 840 小时;按 $25/hour 估算,约 $21,000/月。
- 风险降低:PII、违规承诺、缺证据引用从人工抽检变成每次输出必检,适合高风险品类和多市场上架。
- 实施难度:⭐⭐⭐☆☆。标准库版本可立即落地;生产版需要接入 OCR、DLP、moderation 和 trace。
- 优先级评分:⭐⭐⭐⭐☆。当前合规域已有规则类 Skill,但缺少一个统一的“生成输出门控 + 审计元数据”编排层。
- 评估依据:论文公开 readout 报告 5 次候选尝试、20 秒预算、91% compliance;业务侧收益主要来自减少人工初筛和减少违规输出,而非直接复用论文中的 payments win-rate。
7. 代码模板
代码块数量:3 · 路径:paper2skills-code/compliance/compliance_scored_guardrail_orchestration
"""Compliance-Scored Guardrail Orchestration — 加权护栏 Best-of-N(自洽可运行版)
实现 ① 的 C(y) = Σ wⱼ·gⱼ(y) / Σ wⱼ:并行候选逐个打分,超阈值提前返回,
低于阈值不等于失败而是转人工复核;输出带 attempts / latency / 违规原因 / 规则集版本,供审计。
纯标准库。
"""
import re
import time
from dataclasses import dataclass, field
from typing import Callable, Iterable
@dataclass(frozen=True)
class GuardrailRule:
"""一条权重化的 [0,1] 打分规则;blocking_threshold 命中时该候选直接失去被选资格。"""
name: str
weight: float
checker: Callable[[dict], tuple]
blocking_threshold: float = 0.0
def evaluate(self, candidate: dict) -> tuple:
score, reasons = self.checker(candidate)
score = max(0.0, min(1.0, float(score)))
blocked = score <= self.blocking_threshold and bool(reasons)
return score, reasons, blocked
@dataclass
class SelectionResult:
selected: object
compliance_score: float
status: str
attempts: int
elapsed_ms: float
threshold: float
config_version: str
violations: list = field(default_factory=list)
scored_candidates: list = field(default_factory=list)
def as_dict(self) -> dict:
return {"selected": self.selected, "compliance_score": round(self.compliance_score, 4),
"status": self.status, "attempts": self.attempts,
"elapsed_ms": round(self.elapsed_ms, 2), "threshold": self.threshold,
"config_version": self.config_version, "violations": self.violations,
"scored_candidates": self.scored_candidates}
def _text(c: dict) -> str:
return "\n".join(str(c.get(k) or "") for k in ("title", "body", "evidence_summary", "image_ocr"))
def schema_rule(required_fields):
required = tuple(required_fields)
def check(c: dict) -> tuple:
missing = [f for f in required if not c.get(f)]
if not missing:
return 1.0, []
return max(0.0, 1.0 - len(missing) / len(required)), [f"missing_field:{f}" for f in missing]
return check
def pii_rule(c: dict) -> tuple:
text = _text(c)
patterns = {
"email": r"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b",
"phone": r"\b(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b",
"card": r"\b(?:\d[ -]*?){13,16}\b",
}
hits = [n for n, p in patterns.items() if re.search(p, text, flags=re.IGNORECASE)]
if not hits:
return 1.0, []
return max(0.0, 1.0 - 0.35 * len(hits)), [f"pii:{h}" for h in hits]
def moderation_rule(c: dict) -> tuple:
banned = ["hide the defect", "ignore the recall", "guaranteed safe",
"no certification needed", "bypass policy"]
lowered = _text(c).lower()
hits = [t for t in banned if t in lowered]
if not hits:
return 1.0, []
return max(0.0, 1.0 - 0.4 * len(hits)), [f"policy_term:{t}" for t in hits]
def baby_product_domain_rule(c: dict) -> tuple:
"""母婴品类必须同时讲清:目标市场 / 风险性质 / 下一步动作,缺一即信息不完整。"""
text = _text(c).lower()
required_concepts = {
"market": ("us", "eu", "uk", "cpsc", "fda", "gpsr", "rapex", "ce"),
"risk": ("risk", "hazard", "recall", "injury", "safety"),
"action": ("review", "test", "certification", "evidence", "manual", "human"),
}
missing = [k for k, aliases in required_concepts.items()
if not any(a in text for a in aliases)]
if not missing:
return 1.0, []
return max(0.0, 1.0 - len(missing) / len(required_concepts)), \
[f"missing_domain_concept:{m}" for m in missing]
def evidence_grounding_rule(c: dict) -> tuple:
evidence = str(c.get("evidence_summary") or "")
body = str(c.get("body") or "").lower()
cited = any(t in body for t in ("based on", "evidence", "record"))
if len(evidence.strip()) >= 20 and cited:
return 1.0, []
if len(evidence.strip()) >= 20:
return 0.75, ["evidence_not_explicitly_cited"]
return 0.25, ["missing_evidence_summary"]
def baby_compliance_guardrails() -> list:
"""权重即严重度:schema 与 PII 各 0.25,内容与领域规则 0.20,证据引用 0.10。"""
return [
GuardrailRule("schema", 0.25, schema_rule(("title", "body", "evidence_summary",
"recommended_action"))),
GuardrailRule("pii", 0.25, pii_rule),
# 违规承诺是「命中即阻断」的硬规则,不参与加权平均的分数竞争(①:严重度最高的一类)
GuardrailRule("moderation", 0.20, moderation_rule, blocking_threshold=1.0),
GuardrailRule("baby_domain_rules", 0.20, baby_product_domain_rule),
GuardrailRule("evidence_grounding", 0.10, evidence_grounding_rule),
]
class ComplianceScoredGuardrailOrchestrator:
def __init__(self, rules: Iterable[GuardrailRule], threshold: float = 0.9,
timeout_seconds: float = 20.0, config_version: str = "guardrails-2026-10") -> None:
self.rules = list(rules)
if not self.rules:
raise ValueError("At least one guardrail rule is required")
self.threshold, self.timeout_seconds = threshold, timeout_seconds
self.config_version = config_version
def score(self, candidate: dict) -> dict:
total_weight = sum(r.weight for r in self.rules)
weighted, violations, blocked = 0.0, [], False
per_rule = {}
for r in self.rules:
s, reasons, is_blocked = r.evaluate(candidate)
per_rule[r.name] = s
weighted += r.weight * s
if reasons:
violations.append({"rule": r.name, "score": round(s, 4), "reasons": reasons})
blocked = blocked or is_blocked
return {"candidate": candidate, "compliance_score": weighted / total_weight,
"per_rule": per_rule, "blocked": blocked, "violations": violations}
def select_best(self, candidates: list) -> SelectionResult:
start = time.perf_counter()
best, scored_list, attempts = None, [], 0
for cand in candidates:
if time.perf_counter() - start > self.timeout_seconds:
break
attempts += 1
scored = self.score(cand)
scored_list.append({"title": cand.get("title"),
"compliance_score": round(scored["compliance_score"], 4),
"blocked": scored["blocked"], "violations": scored["violations"]})
if not scored["blocked"] and (best is None
or scored["compliance_score"] > best["compliance_score"]):
best = scored
if best is not None and best["compliance_score"] >= self.threshold:
break # ① 的提前返回:已经拿到够好的候选就不必再跑完
elapsed = (time.perf_counter() - start) * 1000
if best is None:
return SelectionResult(None, 0.0, "human_review_required", attempts, elapsed,
self.threshold, self.config_version,
[v for item in scored_list for v in item["violations"]],
scored_list)
status = "accepted" if best["compliance_score"] >= self.threshold else "human_review_required"
return SelectionResult(best["candidate"], best["compliance_score"], status, attempts,
elapsed, self.threshold, self.config_version, best["violations"],
scored_list)
# ── 演示与断言(② 场景 A:Listing 文案门控)────────────────────
good_listing = {
"title": "Compliance-gated listing response",
"body": ("Based on certification evidence, route the US launch through CPSC safety review, "
"confirm EU GPSR traceability, and send missing battery-test records to human review."),
"evidence_summary": "Supplier provided battery report, draft manual, and US/EU target-market plan.",
"recommended_action": "human_review_before_publish",
}
unsafe_listing = {
"title": "Unsafe launch copy",
"body": ("This baby monitor is guaranteed safe. No certification needed. "
"Contact the plant manager at jane.doe@example.com or 415-555-2671."),
"evidence_summary": "Draft listing copy from supplier intake form.",
"recommended_action": "publish",
}
orchestrator = ComplianceScoredGuardrailOrchestrator(
baby_compliance_guardrails(), threshold=0.88)
# 断言 1:C(y) 必须真按 ① 的加权平均算出来,与逐规则分数对得上
detail = orchestrator.score(good_listing)
manual = sum(r.weight * detail["per_rule"][r.name] for r in orchestrator.rules) / \
sum(r.weight for r in orchestrator.rules)
print(f"good listing C(y)={detail['compliance_score']:.4f}(手算 {manual:.4f})per_rule={detail['per_rule']}")
assert abs(detail["compliance_score"] - manual) < 1e-12
# 断言 2:违规候选的分数明显更低,且违规原因可读(reviewer 看得懂为什么被拦)
bad_detail = orchestrator.score(unsafe_listing)
print(f"unsafe listing C(y)={bad_detail['compliance_score']:.4f}")
reasons = {v["rule"]: v["reasons"] for v in bad_detail["violations"]}
assert bad_detail["compliance_score"] < detail["compliance_score"]
assert "pii:email" in reasons["pii"], reasons
assert "policy_term:guaranteed safe" in reasons["moderation"], reasons
assert bad_detail["blocked"] is True, "过度安全承诺属阻断级,不能只扣分"
# 断言 3:Best-of-N 先给坏候选、后给好候选 → 选中好候选
result = orchestrator.select_best([unsafe_listing, good_listing])
print(f"status={result.status} attempts={result.attempts} score={result.compliance_score:.4f}")
assert result.status == "accepted" and result.selected is good_listing
assert result.attempts == 2, result.attempts
# 断言 4:① 的提前返回——第一个候选已达标就不再跑后面的
early = orchestrator.select_best([good_listing, unsafe_listing])
assert early.attempts == 1, early.attempts
# 断言 5:被阻断的候选即使分数更高也不得入选(分数不是唯一裁判)
sneaky = dict(good_listing, body=good_listing["body"] + " It is guaranteed safe.")
sneaky_detail = orchestrator.score(sneaky)
print(f"过度承诺候选 C(y)={sneaky_detail['compliance_score']:.4f} blocked={sneaky_detail['blocked']}")
assert sneaky_detail["blocked"] is True, sneaky_detail
# 另一个候选没有违规承诺,但缺 recommended_action 且未显式引用证据 → 分数更低却合格
weaker = {k: v for k, v in good_listing.items() if k != "recommended_action"}
weaker = dict(weaker, body="Route the US launch through CPSC safety review; "
"EU GPSR traceability still to be confirmed.")
weaker_detail = orchestrator.score(weaker)
assert weaker_detail["blocked"] is False
assert weaker_detail["compliance_score"] < sneaky_detail["compliance_score"], \
(weaker_detail["compliance_score"], sneaky_detail["compliance_score"])
picked = orchestrator.select_best([sneaky, weaker])
print(f"Best-of-N 选择:跳过 blocked 的高分候选,选中 {picked.selected['title']} "
f"score={picked.compliance_score:.4f} status={picked.status}")
assert picked.selected is weaker, picked.selected
assert picked.scored_candidates[0]["blocked"] is True
only_blocked = orchestrator.select_best([sneaky])
assert only_blocked.selected is None and only_blocked.status == "human_review_required"
# 断言 6(② 场景 B):缺证据引用 / 缺领域要素 → 转人工而不是失败,且给出复核清单
no_evidence = {"title": "Recall action summary",
"body": "Route the US launch through CPSC safety review for the recalled SKU.",
"evidence_summary": "", "recommended_action": "human_review"}
res = orchestrator.select_best([no_evidence])
print(f"缺证据摘要 → status={res.status},attempts={res.attempts}")
assert res.status == "human_review_required"
viol_names = [v["rule"] for v in res.violations]
assert "evidence_grounding" in viol_names or any("missing_evidence" in str(v) for v in res.violations), res.violations
# 断言 7:审计元数据齐全(① 要求 attempts / latency / 违规原因 / 规则集版本)
audit = result.as_dict()
for key in ("attempts", "elapsed_ms", "threshold", "violations", "config_version",
"scored_candidates", "status"):
assert key in audit, key
print(f"审计字段齐备:threshold={audit['threshold']} config={audit['config_version']} "
f"elapsed={audit['elapsed_ms']} ms")
# 断言 8(① 关键假设 3:低于阈值不等于失败):同一候选,阈值是政策参数
loose = ComplianceScoredGuardrailOrchestrator(baby_compliance_guardrails(), threshold=0.88)
strict = ComplianceScoredGuardrailOrchestrator(baby_compliance_guardrails(), threshold=0.95)
r_loose, r_strict = loose.select_best([weaker]), strict.select_best([weaker])
print(f"weaker 候选 C={r_loose.compliance_score:.4f}:阈值 0.88 → {r_loose.status};"
f"阈值 0.95 → {r_strict.status}")
assert r_loose.compliance_score == r_strict.compliance_score # 分数不随阈值变
assert r_loose.status == "accepted" and r_strict.status == "human_review_required"
# 转人工时必须把「扣在哪几条规则上」交给人,而不是只给一个总分
assert r_strict.violations and all("rule" in v and "reasons" in v for v in r_strict.violations)
print("[✓] Compliance Scored Guardra 测试通过")Agent:品牌合规卫士
测试输入:文案=含clinically proven/prevents colic,品类=母婴,市场=US
输出摘要:3处禁用词+2处慎用词,合规评分64->94/100,逐句合规改写建议
验证状态:✅ 本地计算通过 | 2026-06-11
8. 论文来源
论文链接用于核验方法来源,不自动证明本页商业结果。