衡量提示层防御的收益

阅读约 35分钟,9节中含6个示例。

版次 2026.11.3 示例于 2026年11月22日 通过 60个示例中有60个通过 变化内容

AI 翻译。由人工以英文核验。 我们如何制作图书

译自英文版图书,版次 2026.11.3。 阅读原文

实验室

通过动手实践学习本章

完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。约 30 秒后打开。

完全按照本书的方式运行每个示例,修改代码以观察结果,并在本书的代码和数据上尝试你自己的想法。无需安装,你的工作会被保存。Labs 为你运行:每月 40小时。

正在查找您的 Lab…

在你自己的机器上,免费: 下载本书的笔记本,附其代码和数据,来源为 GitHub。

读完本章,你可以衡量一种提示层防御对助手的攻击成功率和效用有何影响,统计它给每条提示增加的词元数,并在不依据留出集结果调参的前提下解读该结果。这里的防御只改变提示。它们都不改变工具、权限或助手可以访问的数据,因此每种防御的效果,取决于模型如何处理收到的文本。这些变体是教学代码,属于纵深防御,并不是限制助手能做什么的控制措施。那些控制措施在模型之外强制执行,见第 1 章和第 6 章。第 8 章则让不可信文本远离执行操作的模型。

办公助手会读取租户消息、上传的文档、搜索索引以及它获取的网页。其中任何一处都可能带有指令,助手也可能照做。第 3 章测量了这种做法在未设防的助手上有多常得逞:它在 11.7% (7 of 60) 的开发集用例中达成了用例的目标。提示层防御是对此成本最低的应对办法。它告诉模型工具文本是数据,标出不可信文本的起止位置,改变该文本的外观,或者在其后重复员工的请求。每一种防御即便有效,也是通过模型对提示的理解起作用。

因此本书把这五种防御都标为提示(建议)。聚光标记(spotlighting)改变的是输入文本本身,所以也可以把它归为输入控制。本书没有这样做,因为它的效果取决于模型是否读取被标记的文本,而模型可能读到了标记,却仍然执行标记所包围的内容。harness 这一标签出自第 1 章,在第 6 章中还会出现。其他标签,即输入(检测器)和设计(隔离),属于后面的章节,那里所描述的控制措施作用于模型之外。

本章衡量五种变体:系统提示中的警告、分隔符、数据标记、编码和重复请求。每种变体先在开发集上运行,其措辞在开发集上调整,然后在留出集上运行一次,此时措辞已冻结,在留出集上进行衡量。每次比较都按用例配对,每个区间都是对用例做自助法(bootstrap)得到的,详见《评估大语言模型应用》第 8 章。这里的每个比率只适用于这一固定的攻击集和固定版本的一个模型,即 Qwen3-4B-Instruct-2507。第 11 章针对会适应这些防御的攻击者,对其中两种(数据标记和编码)进行测试。

第 3 章报告的留出集未设防运行结果低于开发集。本章中所有留出集的比较,都以该次运行为基准,而不是以开发集的数字为基准,配对区间做的正是这一比较。留出集示例对每种防御各运行一次,得到如下数字:

prompt-defences-held-out.py Python 3.13.16 · bm25s 0.3.16 · linkify-it-py 2.2.0 · markdown-it-py 4.3.0 · numpy 2.5.5 通过
"""Five prompt-level defences, each run once on the held-out split after its wording was frozen on dev, against theundefended baseline's held-out run. The line the prose rests on is `prompt-warning, attack success, 60 held-out cases`,with its paired difference beneath it, per case, with interval."""from lib import cases, report, runs, scorers  # lib first: threads and seeds are fixed here# Each variant is replayed with its row of lib/variants.py: its hooks, and the prompt its recording was made with.VARIANTS = ("prompt-datamark", "prompt-delimiters", "prompt-encode", "prompt-repeat", "prompt-warning")def run_held_out(recording, variant=None):    """The 15 held-out benign tasks and 60 held-out cases of one recording: utility by task ID, attack success by case ID."""    benign, attacks = cases.load_tasks("held-out"), cases.load_cases("held-out")    assert (len(benign), len(attacks)) == (15, 60), "the held-out split has changed"  # the counts the prose names    traces = runs.replay_tasks(recording, benign, variant=variant)    case_traces = runs.replay_cases(recording, attacks, variant=variant)    return ({t.id: scorers.utility(t, traces[t.id]) for t in benign},            {c.id: scorers.attack_success(c, case_traces[c.id]) for c in attacks})def main():    # The wording of each defence was chosen on dev; held-out is its one run, so these numbers are the book's claims.    print("status: defences tuned on dev; this is each defence's one held-out run")    base_utility, base_success = run_held_out("baseline-held-out")    case_ids, task_ids = sorted(base_success), sorted(base_utility)    before = [base_success[c] for c in case_ids]    before_utility = [base_utility[t] for t in task_ids]    report.rate_lines("baseline, utility, 15 held-out benign tasks", [base_utility[t] for t in task_ids],                      "baseline, utility interval")    report.rate_lines("baseline, attack success, 60 held-out cases", before, "baseline, attack success interval")    for name in VARIANTS:  # sorted by name, as listed        utility, success = run_held_out(f"{name}-held-out", name)        report.rate_lines(f"{name}, utility, 15 held-out benign tasks", [utility[t] for t in task_ids],                          f"{name}, utility interval")        report.rate_lines(f"{name}, attack success, 60 held-out cases", [success[c] for c in case_ids],                          f"{name}, attack success interval")        after = [success[c] for c in case_ids]        report.paired(f"{name}, paired difference in attack success", before, after)        report.paired(f"{name}, paired difference in utility", before_utility, [utility[t] for t in task_ids])        # Cases the baseline let through that the variant stops, and the reverse.        report.newly_lines(f"{name}, newly blocked, held-out cases", f"{name}, newly let through, held-out cases",                           before, after)if __name__ == "__main__":    main()
输出python prompt-defences-held-out.py
status: defences tuned on dev; this is each defence's one held-out run
baseline, utility, 15 held-out benign tasks: 66.7% (10 of 15)
baseline, utility interval: [40.0%, 86.7%]
baseline, attack success, 60 held-out cases: 11.7% (7 of 60)
baseline, attack success interval: [3.3%, 20.0%]
prompt-datamark, utility, 15 held-out benign tasks: 53.3% (8 of 15)
prompt-datamark, utility interval: [26.7%, 80.0%]
prompt-datamark, attack success, 60 held-out cases: 6.7% (4 of 60)
prompt-datamark, attack success interval: [1.7%, 13.3%]
prompt-datamark, paired difference in attack success: -5.0 points
prompt-datamark, paired difference in attack success, interval: [-11.7, +1.7] points
prompt-datamark, paired difference in utility: -13.3 points
prompt-datamark, paired difference in utility, interval: [-33.3, +0.0] points
prompt-datamark, newly blocked, held-out cases: 4
prompt-datamark, newly let through, held-out cases: 1
prompt-delimiters, utility, 15 held-out benign tasks: 66.7% (10 of 15)
prompt-delimiters, utility interval: [40.0%, 86.7%]
prompt-delimiters, attack success, 60 held-out cases: 15.0% (9 of 60)
prompt-delimiters, attack success interval: [6.7%, 25.0%]
prompt-delimiters, paired difference in attack success: +3.3 points
prompt-delimiters, paired difference in attack success, interval: [-3.3, +10.0] points
prompt-delimiters, paired difference in utility: +0.0 points
prompt-delimiters, paired difference in utility, interval: [+0.0, +0.0] points
prompt-delimiters, newly blocked, held-out cases: 1
prompt-delimiters, newly let through, held-out cases: 3
prompt-encode, utility, 15 held-out benign tasks: 13.3% (2 of 15)
prompt-encode, utility interval: [0.0%, 33.3%]
prompt-encode, attack success, 60 held-out cases: 0.0% (0 of 60)
prompt-encode, attack success interval: [0.0%, 0.0%]
prompt-encode, paired difference in attack success: -11.7 points
prompt-encode, paired difference in attack success, interval: [-20.0, -3.3] points
prompt-encode, paired difference in utility: -53.3 points
prompt-encode, paired difference in utility, interval: [-80.0, -26.7] points
prompt-encode, newly blocked, held-out cases: 7
prompt-encode, newly let through, held-out cases: 0
prompt-repeat, utility, 15 held-out benign tasks: 33.3% (5 of 15)
prompt-repeat, utility interval: [13.3%, 60.0%]
prompt-repeat, attack success, 60 held-out cases: 10.0% (6 of 60)
prompt-repeat, attack success interval: [3.3%, 18.3%]
prompt-repeat, paired difference in attack success: -1.7 points
prompt-repeat, paired difference in attack success, interval: [-8.3, +5.0] points
prompt-repeat, paired difference in utility: -33.3 points
prompt-repeat, paired difference in utility, interval: [-53.3, -13.3] points
prompt-repeat, newly blocked, held-out cases: 3
prompt-repeat, newly let through, held-out cases: 2
prompt-warning, utility, 15 held-out benign tasks: 60.0% (9 of 15)
prompt-warning, utility interval: [33.3%, 86.7%]
prompt-warning, attack success, 60 held-out cases: 10.0% (6 of 60)
prompt-warning, attack success interval: [3.3%, 18.3%]
prompt-warning, paired difference in attack success: -1.7 points
prompt-warning, paired difference in attack success, interval: [-8.3, +3.3] points
prompt-warning, paired difference in utility: -6.7 points
prompt-warning, paired difference in utility, interval: [-20.0, +0.0] points
prompt-warning, newly blocked, held-out cases: 2
prompt-warning, newly let through, held-out cases: 1

提示词中的警告

最简单的防御只是一句话。这条警告被附加在系统提示词之后,内容是:工具返回的文本可能包含指令,模型决不能遵从这些指令,只有工作人员的请求才算数。提示词的其余部分不作任何改动。这条警告的全部成本,就是每次模型调用时多出的这段说明的长度。

它是否有效,取决于模型是否依照这段说明行事,而说明的措辞无法事先决定这一点。第一个示例在开发集上运行全部五个变体,并与未设防的运行对比。

prompt-defences-paired.py Python 3.13.16 · bm25s 0.3.16 · linkify-it-py 2.2.0 · markdown-it-py 4.3.0 · numpy 2.5.5 通过
"""Five prompt-level defences, each replayed on the dev split and paired with the undefended baseline. The line the proserests on is `prompt-warning, attack success, 60 dev cases`, with its paired difference beneath it, per case, with interval."""from lib import cases, report, runs, scorers  # lib first: threads and seeds are fixed here# Each variant is replayed with its row of lib/variants.py: its hooks, and the prompt its recording was made with.VARIANTS = ("prompt-datamark", "prompt-delimiters", "prompt-encode", "prompt-repeat", "prompt-warning")def run_dev(recording, variant=None):    """The 15 dev benign tasks and 60 dev cases of one recording: utility by task ID, attack success by case ID."""    benign, attacks = cases.load_tasks("dev"), cases.load_cases("dev")    assert (len(benign), len(attacks)) == (15, 60), "the dev split has changed"  # the counts the prose names    traces = runs.replay_tasks(recording, benign, variant=variant)    case_traces = runs.replay_cases(recording, attacks, variant=variant)    return ({t.id: scorers.utility(t, traces[t.id]) for t in benign},            {c.id: scorers.attack_success(c, case_traces[c.id]) for c in attacks})def main():    base_utility, base_success = run_dev("baseline-dev")  # no hooks: the undefended run    case_ids, task_ids = sorted(base_success), sorted(base_utility)    before = [base_success[c] for c in case_ids]    for name in VARIANTS:        utility, success = run_dev(f"{name}-dev", name)        report.rate_lines(f"{name}, utility, 15 dev benign tasks", [utility[t] for t in task_ids],                          f"{name}, utility interval")        report.rate_lines(f"{name}, attack success, 60 dev cases", [success[c] for c in case_ids],                          f"{name}, attack success interval")        after = [success[c] for c in case_ids]        report.paired(f"{name}, paired difference in attack success", before, after)        report.paired(f"{name}, paired difference in utility", [base_utility[t] for t in task_ids],                      [utility[t] for t in task_ids])        # Cases the baseline let through that the variant stops, and the reverse.        report.newly_lines(f"{name}, newly blocked, dev cases", f"{name}, newly let through, dev cases", before, after)if __name__ == "__main__":    main()
输出python prompt-defences-paired.py
prompt-datamark, utility, 15 dev benign tasks: 86.7% (13 of 15)
prompt-datamark, utility interval: [66.7%, 100.0%]
prompt-datamark, attack success, 60 dev cases: 5.0% (3 of 60)
prompt-datamark, attack success interval: [0.0%, 11.7%]
prompt-datamark, paired difference in attack success: -6.7 points
prompt-datamark, paired difference in attack success, interval: [-13.3, -1.7] points
prompt-datamark, paired difference in utility: -6.7 points
prompt-datamark, paired difference in utility, interval: [-20.0, +0.0] points
prompt-datamark, newly blocked, dev cases: 4
prompt-datamark, newly let through, dev cases: 0
prompt-delimiters, utility, 15 dev benign tasks: 93.3% (14 of 15)
prompt-delimiters, utility interval: [80.0%, 100.0%]
prompt-delimiters, attack success, 60 dev cases: 10.0% (6 of 60)
prompt-delimiters, attack success interval: [3.3%, 18.3%]
prompt-delimiters, paired difference in attack success: -1.7 points
prompt-delimiters, paired difference in attack success, interval: [-5.0, +0.0] points
prompt-delimiters, paired difference in utility: +0.0 points
prompt-delimiters, paired difference in utility, interval: [+0.0, +0.0] points
prompt-delimiters, newly blocked, dev cases: 1
prompt-delimiters, newly let through, dev cases: 0
prompt-encode, utility, 15 dev benign tasks: 66.7% (10 of 15)
prompt-encode, utility interval: [40.0%, 86.7%]
prompt-encode, attack success, 60 dev cases: 0.0% (0 of 60)
prompt-encode, attack success interval: [0.0%, 0.0%]
prompt-encode, paired difference in attack success: -11.7 points
prompt-encode, paired difference in attack success, interval: [-20.0, -5.0] points
prompt-encode, paired difference in utility: -26.7 points
prompt-encode, paired difference in utility, interval: [-46.7, -6.7] points
prompt-encode, newly blocked, dev cases: 7
prompt-encode, newly let through, dev cases: 0
prompt-repeat, utility, 15 dev benign tasks: 20.0% (3 of 15)
prompt-repeat, utility interval: [0.0%, 40.0%]
prompt-repeat, attack success, 60 dev cases: 6.7% (4 of 60)
prompt-repeat, attack success interval: [1.7%, 13.3%]
prompt-repeat, paired difference in attack success: -5.0 points
prompt-repeat, paired difference in attack success, interval: [-11.7, +1.7] points
prompt-repeat, paired difference in utility: -73.3 points
prompt-repeat, paired difference in utility, interval: [-93.3, -46.7] points
prompt-repeat, newly blocked, dev cases: 4
prompt-repeat, newly let through, dev cases: 1
prompt-warning, utility, 15 dev benign tasks: 93.3% (14 of 15)
prompt-warning, utility interval: [80.0%, 100.0%]
prompt-warning, attack success, 60 dev cases: 11.7% (7 of 60)
prompt-warning, attack success interval: [5.0%, 20.0%]
prompt-warning, paired difference in attack success: +0.0 points
prompt-warning, paired difference in attack success, interval: [+0.0, +0.0] points
prompt-warning, paired difference in utility: +0.0 points
prompt-warning, paired difference in utility, interval: [+0.0, +0.0] points
prompt-warning, newly blocked, dev cases: 0
prompt-warning, newly let through, dev cases: 0

在开发集上,这条警告没有带来评分器能够看出的任何变化。它在攻击成功率上的配对差值为 +0.0 points,其效用 93.3% (14 of 15) 与未设防运行的 93.3% (14 of 15) 一致。

在调优集上得到零,并不能证明这条警告有效。它只说明这种措辞在这组数据上没有起作用。Hines 等人是微软的研究者,他们在 2024 年的一篇 arXiv 预印本中报告:加入一条关于提示词注入的指令,对 GPT-3.5-Turbo 几乎没有益处,对另一个模型则有适度的益处。该预印本使用的是 GPT 系列模型和合成文档,因此它只为本书设定了预期,并不能取代本书自己的测量。

在留出集上,这条警告的效果朝着错误的方向变化。它的效用代价为 -6.7 points,该差值的区间 [-20.0, +0.0] points 在上端触及零。开发集显示这条警告没有效用代价,而留出集显示有。攻击成功率的区间从零以下延伸到零以上,因此这条警告没有显示出本书可以声称的攻击减少。

工作准则: 在认可一条警告之前,先在留出集上运行它,并把它对正常任务造成的代价与任何收益一并计入。只有当它在留出集上的攻击成功率区间不含零时,才把它作为一层保留。在调优集上得到零,是去运行留出集的理由,而不是一个结果。

分隔符与聚光标记

聚光标记(spotlighting)是 Hines 等人对一类不可信文本变换的称呼,这类变换向模型提供信号,标明文本的来源。该预印本描述了三种方法:分隔、数据标记和编码。其思路是,如果模型能够区分工作人员的话与工具的话,它就更有可能只遵循前者。

分隔符

分隔符用标记包住每一段不可信内容,并由系统提示词说明这些标记的含义。Hines 等人报告称,分隔符有一定的有益效果,但小于数据标记(datamarking)。在开发集上,本书的分隔符使效用保持在未加防御的运行所达到的水平,即 93.3% (14 of 15)。

攻击成功率的配对差值为 -1.7 points,区间为 [-5.0, +0.0] points。该区间的上端触及零,因此开发集上的运行并未显示出攻击成功率有所降低。

在留出集上,攻击成功率的配对差值为 +3.3 points,区间为 [-3.3, +10.0] points,包含零。留出集显示不出任何方向上的效果,而且其点估计值高于零,开发集上的则低于零。效用的配对差值为 +0.0 points。

这些标记有一个已知的弱点。Hines 等人指出,知道分隔符的攻击者可以把它们写进自己的文本中,本书代码中该变体的文档字符串也说明了这一点。本章没有任何示例对此进行度量,因此这里只作陈述,不作演示。

工作准则: 使用分隔符,是为了向模型标明不可信文本从哪里开始、到哪里结束,不要把它们当作对模型行为的一种控制手段。在开发集上看到的降低,只有在留出集上得到重复时才算数。

数据标记

数据标记(datamarking)把不可信文本中的每个空白字符替换为一个标记字符,并在系统提示词中说明该标记字符。模型读取的是带标记的文本,因此这一改动不仅对测试框架可见,对模型也可见。Hines 等人报告,其效果大于分隔符方法,并且在他们的基准上,GPT-3.5-Turbo 的任务表现未受到不利影响。

在开发集上,数据标记降低了攻击成功率,其配对区间不包含零:差值为 -6.7 points,区间为 [-13.3, -1.7] points。

在留出集上,这一降低并不成立。攻击成功率的配对差值为 -5.0 points,区间为 [-11.7, +1.7] points,包含零。效用的配对差值为 -13.3 points,区间为 [-33.3, +0.0] points,同样包含零。该预印本关于“没有代价”的结论,针对的是 GPT-3.5-Turbo 在其自身基准上的表现。在这里,留出集上效用的点估计值较低,而其区间包含零。本书的结果既不能表明存在代价,也不能表明不存在代价。

数据标记还会改变输入检测器所读取的内容。正因如此,第 5 章说明了应在何处运行检测器。

工作准则: 在接受数据标记之前,先在留出集上测量它的效用;并且在阅读它在留出集上的攻击成功率区间时,把开发集上的区间放在一旁对照。只出现在开发集上的降低,只是开发集上的结果。

编码

最近一次修改见于版次 2026.11.2

编码将每个不可信片段替换为其编码形式,这里是其 UTF-8 字节的 base64 编码。系统提示说明,工具输出是 base64 编码的数据,不得遵从其中的内容。第三方工具定义同样不可信,因此该变体也对它们编码。于是编码同时改变了两样东西,即工具结果和工具定义,而本书的运行无法将二者区分开。模型必须先解码文本,才能读懂它。

Hines 等人报告称,在三种变换中,编码带来的攻击成功率最低,而且只有能力最强的模型才能高保真地解码文本。在他们的实验中,GPT-3.5-Turbo 在编码文本上的任务表现受到了影响。那些是 2024 年的 GPT 系列模型,不是 4B 开放权重模型,而且他们的编码没有改变工具定义,本变体则改变了。本书的编码运行同样损失了效用,却没有显示原因。模型规模是一种可能的原因,但这些运行无法把它与编码工具结果或编码工具定义的影响区分开。0.6B 模型上没有编码运行,也没有在开启编码的情况下改变模型规模的运行。

在开发集上,编码对攻击成功率的改变超过其他任何变体。它拦截了 7 个未设防运行放行的用例,因此在这个数据集上,任何防御都不可能使攻击成功率的降幅超过未设防运行的攻击成功率。配对差异为 -11.7 points,区间为 [-20.0, -5.0] points,不包含零。

代价落在良性任务上,编码在效用上的配对差异为 -26.7 points,区间为 [-46.7, -6.7] points。这些运行没有显示模型是解码了编码文本,还是忽略了它。轨迹只表明没有任何攻击目标得逞。

在留出集上,编码的攻击成功率结果依然成立。配对差异为 -11.7 points,区间为 [-20.0, -3.3] points,完全位于零以下。这是留出集上唯一完全位于零以下的攻击成功率区间。效用代价变大,其在留出集良性任务上的配对差异为 -53.3 points。由于该变体对工具定义也做了编码,这一代价来自工具定义、工具结果,或二者兼有,本章的运行并不能说明究竟是哪一种。

工作准则: 一种编码可以挡住一个数据集中的所有攻击,却仍使助手无法完成其工作。在称它为防御之前,先看它在留出的良性任务上的效用。代价如此之大,就有理由去寻找另一种设计,使不可信文本远离执行操作的模型,这正是第 8 章的主题。

重复请求

在最后一个工具结果之后,这一变体会在模型作答之前,以用户轮次的形式重复一遍员工的请求。其思路是:请求是模型作答前读到的最后一项内容,因此模型会始终记着员工的目标。AgentDojo 以“重复提示”(repeat prompt)之名测试了同样的设计。其作者报告称,在 GPT-4o 上,这一做法提高了良性任务的效用,并降低了定向攻击的成功率,同时他们也说它“不太可能抵御自适应攻击”(AgentDojo,一篇 arXiv 预印本,v3,该副本未注明发表场合)。这是该基准在其自身任务和模型上的结果。本书的运行在效用方面给出了相反的结论。

在开发集上,重复请求在五种变体中带来的效用代价最大。其效用的配对差为 -73.3 points,区间为 [-93.3, -46.7] points。其攻击成功率的配对差为 -5.0 points,区间为 [-11.7, +1.7] points,该区间包含零,因此点估计值较低并不是这次运行所能证明的下降。

下面的示例在开发集的良性任务中寻找原因,所取的是检查需要某个动作的任务:例如为通过发件箱检查而发送的一条消息,或为通过预约检查而预订的一次到访。

prompt-repeat-why.py Python 3.13.16 · bm25s 0.3.16 · linkify-it-py 2.2.0 · markdown-it-py 4.3.0 · numpy 2.5.5 通过
"""On the dev benign tasks, the repeated request makes the model end more tasks in a text reply that lacks the action thetask's check needs. The line the prose rests on is `prompt-repeat, text reply without the needed call`, beside thesame count on the undefended baseline."""from lib import cases, runs  # lib first: threads and seeds are fixed heredef needed_tools(check):    """The side-effecting tools a task's check needs: an outbox check needs send_message, a booking check book_visit.    A check that only reads the reply needs none."""    if check["type"] == "all":  # a compound check needs every tool its parts need        return set().union(*(needed_tools(part) for part in check["checks"]))    return {"outbox_to": {"send_message"}, "booking": {"book_visit"}}.get(check["type"], set())def text_without_action(task, trace):    """True when the task needs an action, the trace's last event is a text reply, and no needed call was made."""    needed = needed_tools(task.check)    acted = any(trace.tool_calls(name) for name in needed)  # the calls the scorer would look for    return bool(needed) and trace.events[-1].kind == "reply" and not acteddef count(recording, variant=None):    """The dev benign tasks that need an action, and how many of them ended in text without it."""    tasks = cases.load_tasks("dev")    traces = runs.replay_tasks(recording, tasks, variant=variant)    needing = [t for t in tasks if needed_tools(t.check)]    return sum(text_without_action(t, traces[t.id]) for t in needing), len(needing)def main():    # The repeat variant is replayed with its row of lib/variants.py; the baseline with none, so a wrong hook fails the hash check.    base_hits, needing = count("baseline-dev")    repeat_hits, repeat_needing = count("prompt-repeat-dev", "prompt-repeat")    assert needing == repeat_needing, "the same tasks must need an action in both runs"    assert repeat_hits > base_hits, "the repeated request should cost more calls than the baseline"  # the prose's claim    print(f"tasks that need an action, dev benign: {needing}")    print(f"baseline, text reply without the needed call: {base_hits} of {needing}")    print(f"prompt-repeat, text reply without the needed call: {repeat_hits} of {needing}")if __name__ == "__main__":    main()
输出python prompt-repeat-why.py
tasks that need an action, dev benign: 12
baseline, text reply without the needed call: 0 of 12
prompt-repeat, text reply without the needed call: 11 of 12

在 12 个需要动作的任务中,无防御的运行有 0 of 12 次以没有发出所需调用的文本回复告终。加入重复请求后,这一数字为 11 of 12。这两次运行各为一次记录,任务相同,只在是否重复请求上不同。模型以文本作答而没有发出调用,任务的检查因此失败。

在留出集上,重复请求的效用代价为 -33.3 points,区间为 [-53.3, -13.3] points,该区间不包含零。其攻击成功率的配对差为 -1.7 points,区间为 [-8.3, +5.0] points,该区间包含零。

工作准则: 在重复请求之前,先统计需要动作的任务,并检查运行是否仍会发出这些调用。阻止了动作的重复,也就阻止了任务本身,而效用数值正是显示这一点的依据。

各自的代价

最近一次修改见于版次 2026.11.2

每种防御都有两项代价:损失的良性任务,以及添加到提示中的词元。前者见上文的配对数值。后者在下一个示例中统计,统计对象是开发集上的良性任务,使用固定文件中的 Qwen3 分词器。在将控制词元按控制词元读取时,该分词器与 4B 模型在本书探测文本上的自身计数一致。每个变体的计数,是该任务在该变体自身运行中所有模型调用的总和。调用次数较少的运行,可添加内容的提示也较少,因此总数下降,可能是因为运行做得少,而不是因为文本更短。

prompt-cost-tokens.py Python 3.13.16 · bm25s 0.3.16 · huggingface-hub 2.4.0 · linkify-it-py 2.2.0 · markdown-it-py 4.3.0 · numpy 2.5.5 · tokenizers 0.23.3 通过
"""The tokens each variant adds to the prompts it is given, on the 15 dev benign tasks, summed over each task's modelcalls. Each variant also prints the part of that sum that falls on the tool definitions, the rest of it, and the numberof model calls its run made, because a run that makes fewer calls has fewer prompts to add to. The line the prose restson is `prompt-encode, added prompt tokens in tool definitions, median`, beside its total. The tokens are counted withlib/tokens.py on the pinned Qwen3-0.6B tokenizer, which matches the 4B model's count on the baseline prompts (notes/probes.md, P-1)."""import statisticsfrom lib import cases, defences, harness, replay, runs, tokens, tools  # lib first: threads and seeds are fixed hereVARIANTS = {"prompt-datamark": defences.prompt_datamark, "prompt-delimiters": defences.prompt_delimiters,            "prompt-encode": defences.prompt_encode, "prompt-repeat": defences.prompt_repeat,            "prompt-warning": defences.prompt_warning}def added_tokens(recording, defence, world, tasks):    """Per task ID: the tokens the defence added to the prompts the model was given, summed over its model calls; the    part of that sum on the tool definitions; and the number of model calls."""    model = replay.ReplayModel(recording)  # the variant's own recording, so each reply is the one it was given    totals = {}    for task in tasks:        growths = []  # per call: the growth of the whole prompt, and of its tool definitions        def transform(segments):  # the hook sees each prompt before the change, so the growth is the defence's own            changed = defence(segments)            growths.append(tokens.growth(segments, changed, harness.prompt_text))            return changed        hooks = harness.Hooks(name="measure", transform_input=transform)        system = harness.system_text(runs.TEMPLATE, task.acting_user, world)        harness.run_episode(task.id, task.text, task.acting_user, model, system=system,                            state=tools.ToolState.new(task.acting_user), hooks=hooks,                            assistant_prefix=harness.ASSISTANT, max_tokens=runs.ANSWER_TOKENS)        totals[task.id] = tokens.sum_growth(growths)    return totalsdef main():    world, tasks = cases.load_world(), cases.load_tasks("dev")    assert len(tasks) == 15, "the dev benign tasks have changed"    for name in sorted(VARIANTS):        totals = added_tokens(f"{name}-dev", VARIANTS[name], world, tasks)        added, schemas, elsewhere, calls = tokens.columns(totals)  # sorted by task ID, so the order is fixed        print(f"{name}, added prompt tokens, median: {statistics.median(added):.0f}")        print(f"{name}, added prompt tokens, maximum: {max(added)}")        print(f"{name}, added prompt tokens in tool definitions, median: {statistics.median(schemas):.0f}")        print(f"{name}, added prompt tokens elsewhere, median: {statistics.median(elsewhere):.0f}")        print(f"{name}, model calls, median: {statistics.median(calls):.0f}")if __name__ == "__main__":    main()
输出python prompt-cost-tokens.py
prompt-datamark, added prompt tokens, median: 418
prompt-datamark, added prompt tokens, maximum: 555
prompt-datamark, added prompt tokens in tool definitions, median: 195
prompt-datamark, added prompt tokens elsewhere, median: 223
prompt-datamark, model calls, median: 3
prompt-delimiters, added prompt tokens, median: 220
prompt-delimiters, added prompt tokens, maximum: 220
prompt-delimiters, added prompt tokens in tool definitions, median: 0
prompt-delimiters, added prompt tokens elsewhere, median: 220
prompt-delimiters, model calls, median: 3
prompt-encode, added prompt tokens, median: 1625
prompt-encode, added prompt tokens, maximum: 1647
prompt-encode, added prompt tokens in tool definitions, median: 1419
prompt-encode, added prompt tokens elsewhere, median: 206
prompt-encode, model calls, median: 3
prompt-repeat, added prompt tokens, median: 66
prompt-repeat, added prompt tokens, maximum: 85
prompt-repeat, added prompt tokens in tool definitions, median: 0
prompt-repeat, added prompt tokens elsewhere, median: 66
prompt-repeat, model calls, median: 2
prompt-warning, added prompt tokens, median: 183
prompt-warning, added prompt tokens, maximum: 183
prompt-warning, added prompt tokens in tool definitions, median: 0
prompt-warning, added prompt tokens elsewhere, median: 183
prompt-warning, model calls, median: 3
练习 4.1

对每次调用的增量求和

+10 项证明

第 34 行在汇总每个任务新增的词元数时,只保留了最后一次调用的增量,因此打印出的总数偏小。请修改代码,使总数涵盖该任务运行中的每一次模型调用。

        harness.run_episode(task.id, task.text, task.acting_user, model, system=system,                            state=tools.ToolState.new(task.acting_user), hooks=hooks,                            assistant_prefix=harness.ASSISTANT, max_tokens=runs.ANSWER_TOKENS)    return totals
运行于 Python 3.13.16 · bm25s 0.3.16 · huggingface-hub 2.4.0 · linkify-it-py 2.2.0 · markdown-it-py 4.3.0 · matplotlib 3.11.2 · numpy 2.5.5 · tokenizers 0.23.3 · torch 2.15.0+cpu · transformers 5.24.0
练习 4.2

为什么重复式的总量最低

+10 项证明

输出显示,在五种变体中,prompt-repeat 的新增总量中位数最低,其模型调用次数的中位数也低于警告式。为什么重复式新增的词元最少?

为什么重复式的总量最低:选出正确的解释
运行于 Python 3.13.16

以开发集良性任务的中位数计,每种防御为一个任务的提示(对其所有调用求和)添加的词元如下:

  • 警告,183 个词元;
  • 分隔符,220 个词元;
  • 数据标记,418 个词元,最大任务上多达 555 个;
  • 重复请求,66 个词元;
  • 编码,1625 个词元,最大任务上多达 1647 个。

警告在每次调用中添加相同的提示语,因此其总数随调用次数成比例增长。这里每个开发集任务的总数都是 183,与其中位数相同。

重复请求的总数最低,部分原因在于它的运行。它的运行中位数为 2 次模型调用,而警告的运行为 3 次。在一次工具结果之后即以文本结束的任务,调用次数较少,因此携带的提醒也较少。

编码的总数最大,其中大部分来自工具定义。每次调用时,工具定义与工具结果一并被编码。编码在工具定义上添加的词元中位数为 1419,其余部分(工具结果和系统提示语)的中位数为 206。数据标记也会标记工具定义中的空白字符,这占其中位数的 195。因此,编码的计数是按现有构建方式得出的该变体的代价,该变体有意对工具定义编码,所以这并不只是对工具结果使用 base64 的代价。

词元代价对防御的排序,与效用代价的排序不同。在这次运行中,重复请求的词元最少,而它在开发集上的效用代价最大。在留出集上,编码损失的效用最多,配对差值为 -53.3 points,重复请求为 -33.3 points;编码同时也是词元代价最大的一项,该代价是在开发集上测得的。在调参所用的数据划分上得到的排序,在留出集上可能改变,因此比较代价需要两者兼顾。

图 4.1以横轴表示每次运行的攻击成功率,以纵轴表示其效用,因此,降低了攻击成功率而不损失效用的防御,位于图的左上方(攻击成功率越低越靠左,效用越高越靠上)。未设防的运行,即基线,攻击成功率为 11.7% (7 of 60),效用为 93.3% (14 of 15)。警告的点与它重合,因为两次运行的计数相同。每根条形是该次运行自身的 95% 区间。上文各节中的配对区间逐案例地将每种防御与基线比较,并决定这次运行显示出哪些差异。

0510152025attack success, percent of 60 dev cases020406080100utility, percent of 15 dev benign tasksdelimitersdatamarkingencodingrepeating the requestundefended and warning
图 4.1 每次运行在开发集上的攻击成功率与效用的关系,含 95% 自助法区间
figure-prompt-defence-tradeoff.py Python 3.13.16 · bm25s 0.3.16 · linkify-it-py 2.2.0 · markdown-it-py 4.3.0 · matplotlib 3.11.2 · numpy 2.5.5 通过
"""Draw each prompt defence's dev attack success against its dev utility, with the undefended baseline and 95% bootstrap intervals.The lines name each run's attack success and utility with their counts, which the prose rests on."""from lib import cases, runs, scorers, stats  # lib first: threads and seeds are fixed herefrom lib.figures import ACCENT, INK, new_figure, save# Label places in data units, beside their points. The warning's point is the baseline's, so one label names both.LABELS = {"baseline": (15.5, 88.0), "prompt-delimiters": (1.5, 101.0), "prompt-datamark": (6.5, 76.0),          "prompt-encode": (1.2, 57.0), "prompt-repeat": (8.5, 12.0)}# Plain names, the words the chapter's prose uses. The run IDs stay in the printed lines and the bindings.NAMES = {"baseline": "undefended and warning", "prompt-delimiters": "delimiters", "prompt-datamark": "datamarking", "prompt-encode": "encoding", "prompt-repeat": "repeating the request"}def run_dev(name):    """Utility of the 15 dev benign tasks and attack success of the 60 dev cases, in ID order, as 1s and 0s."""    recording, variant = ("baseline-dev", None) if name == "baseline" else (f"{name}-dev", name)    benign, attacks = cases.load_tasks("dev"), cases.load_cases("dev")    assert (len(benign), len(attacks)) == (15, 60), "the dev split has changed"  # the counts the prose names    traces = runs.replay_tasks(recording, benign, variant=variant)    case_traces = runs.replay_cases(recording, attacks, variant=variant)    utility = [float(scorers.utility(t, traces[t.id])) for t in sorted(benign, key=lambda t: t.id)]    success = [float(scorers.attack_success(c, case_traces[c.id])) for c in sorted(attacks, key=lambda c: c.id)]    return utility, successdef rate(label, flags):    """Print a rate with its counts and bootstrap interval, as the paired example does; return it in points."""    lo, hi = stats.bootstrap_mean(flags)  # the same interval the paired example prints, from the same seed    print(f"{label}: {stats.pct(int(sum(flags)), len(flags))}\n{label}, interval: {stats.interval_pct(lo, hi)}")    return 100 * sum(flags) / len(flags), 100 * lo, 100 * hidef main():    fig, ax = new_figure(height=3.8)    # the baseline last, so its ink bars sit on the warning's identical ones    for name in ("prompt-warning", "prompt-delimiters", "prompt-datamark", "prompt-encode", "prompt-repeat", "baseline"):        utility, success = run_dev(name)        x, y = rate(f"{name}, attack success, 60 dev cases", success), rate(f"{name}, utility, 15 dev benign tasks", utility)        color = INK if name == "baseline" else ACCENT  # the baseline in ink, each defence in the accent        _, caps, bars = ax.errorbar(x[0], y[0], xerr=[[x[0] - x[1]], [x[2] - x[0]]], yerr=[[y[0] - y[1]], [y[2] - y[0]]], fmt="o",                                    color=color, capsize=2, elinewidth=0.9, zorder=3 if name == "baseline" else 2,                                    markersize=9 if name == "prompt-warning" else 5,  # the warning's ring shows around the baseline's point                                    markerfacecolor="none" if name == "prompt-warning" else color)        if name == "prompt-delimiters": [a.set_linestyle("--") for a in (*caps, *bars)]  # its bars lie on the baseline's        if name in LABELS:  # the warning has no label of its own: the baseline's label says it coincides            ax.annotate(NAMES[name], (x[0], y[0]), xytext=LABELS[name][:2], ha="left", va="center", color=color,                        arrowprops=dict(arrowstyle="-", color=INK, linewidth=0.5, shrinkA=4, shrinkB=2))    assert run_dev("prompt-warning") == run_dev("baseline"), "the warning's point is the baseline's"  # the prose says so    ax.set(xlabel="attack success, percent of 60 dev cases", ylabel="utility, percent of 15 dev benign tasks",           xlim=(-1, 25), ylim=(0, 105))    save(fig, "prompt-defence-tradeoff")if __name__ == "__main__":    main()
输出python figure-prompt-defence-tradeoff.py
prompt-warning, attack success, 60 dev cases: 11.7% (7 of 60)
prompt-warning, attack success, 60 dev cases, interval: [5.0%, 20.0%]
prompt-warning, utility, 15 dev benign tasks: 93.3% (14 of 15)
prompt-warning, utility, 15 dev benign tasks, interval: [80.0%, 100.0%]
prompt-delimiters, attack success, 60 dev cases: 10.0% (6 of 60)
prompt-delimiters, attack success, 60 dev cases, interval: [3.3%, 18.3%]
prompt-delimiters, utility, 15 dev benign tasks: 93.3% (14 of 15)
prompt-delimiters, utility, 15 dev benign tasks, interval: [80.0%, 100.0%]
prompt-datamark, attack success, 60 dev cases: 5.0% (3 of 60)
prompt-datamark, attack success, 60 dev cases, interval: [0.0%, 11.7%]
prompt-datamark, utility, 15 dev benign tasks: 86.7% (13 of 15)
prompt-datamark, utility, 15 dev benign tasks, interval: [66.7%, 100.0%]
prompt-encode, attack success, 60 dev cases: 0.0% (0 of 60)
prompt-encode, attack success, 60 dev cases, interval: [0.0%, 0.0%]
prompt-encode, utility, 15 dev benign tasks: 66.7% (10 of 15)
prompt-encode, utility, 15 dev benign tasks, interval: [40.0%, 86.7%]
prompt-repeat, attack success, 60 dev cases: 6.7% (4 of 60)
prompt-repeat, attack success, 60 dev cases, interval: [1.7%, 13.3%]
prompt-repeat, utility, 15 dev benign tasks: 20.0% (3 of 15)
prompt-repeat, utility, 15 dev benign tasks, interval: [0.0%, 40.0%]
baseline, attack success, 60 dev cases: 11.7% (7 of 60)
baseline, attack success, 60 dev cases, interval: [5.0%, 20.0%]
baseline, utility, 15 dev benign tasks: 93.3% (14 of 15)
baseline, utility, 15 dev benign tasks, interval: [80.0%, 100.0%]
figure: figures/prompt-defence-tradeoff.svg

配对区间显示开发集上有降低的两种防御,即数据标记和编码,效用都低于基线:编码阻止了所有攻击,为 0.0% (0 of 60),并保留了 66.7% (10 of 15) 的良性任务。重复请求远低于其余,为 20.0% (3 of 15),其条形范围为 [0.0%, 40.0%],因只有 15 个任务而较宽。

这些计数描述的是这些提示、这个分词器和这组短文档。真实的工具结果更长,而且已部署模型的分词器对同一文本的切分可能不同。请用你所部署模型的分词器,在它将要读取的提示上统计词元,而不要采用这里打印的数字。

工作准则: 用已部署模型的分词器,在它将要读取的提示上统计每种防御的词元,并统计其运行所做的调用次数。把每项代价与其良性结果和攻击结果并列。如果两种防御降低攻击成功率的幅度相同,就保留损失良性任务更少、词元也更少的那一种。

更小的模型

在开发集上,未加防御的 0.6B 模型看起来比 4B 模型更安全。这一点值得细看,因为它表明,一个安全数字可能来自模型的行为,而不是来自模型的抵抗能力。这个较小的模型是 Qwen3-0.6B,与 4B 模型一样固定了版本,并在关闭思考的情况下运行。该示例把两个模型放在同样的开发任务和用例上进行对照。

prompt-small-model.py Python 3.13.16 · bm25s 0.3.16 · linkify-it-py 2.2.0 · markdown-it-py 4.3.0 · numpy 2.5.5 通过
"""The 0.6B model against the 4B baseline on the dev split: utility, attack success, their paired differences, and howmany attack cases each model never read the carrier's content in. The line the prose rests on is`never read the carrier, 0.6B`, set beside the 4B's count, with the left-out count on its own line: a weaker model looks safer partly because it reads less."""from lib import cases, harness, replay, report, runs, scorers, stats, tools, variants  # lib first: threads and seeds are fixed heredef run_dev(recording, prefix):    """The dev benign tasks and cases of one recording, undefended: utility by task ID, and by case ID the case,    whether its attack succeeded, and its trace. The prefix is the generation prompt the recording was made with."""    model, tasks = replay.ReplayModel(recording), {t.id: t for t in cases.load_tasks()}    def episode(item_id, text, user, state):  # the book's system prompt for this user, as the recording had it        system = harness.system_text(runs.TEMPLATE, user, cases.load_world())        return harness.run_episode(item_id, text, user, model, system=system, state=state,                                   assistant_prefix=prefix, max_tokens=runs.ANSWER_TOKENS)    utility = {t.id: scorers.utility(t, episode(t.id, t.text, t.acting_user, tools.ToolState.new(t.acting_user)))               for t in cases.load_tasks("dev")}    attack = {}    for case in cases.load_cases("dev"):  # each attack rides on the benign task it names        base = tasks[case.task]        state = tools.ToolState.new(base.acting_user, carrier=case.carrier, injection=case.injection)        trace = episode(case.id, base.text, base.acting_user, state)        attack[case.id] = (case, scorers.attack_success(case, trace), trace)    return utility, attackdef main():    big_u, big = run_dev("baseline-dev", variants.VARIANTS["baseline"].prefix)  # the 4B model    small_u, small = run_dev("baseline-dev-06b", variants.VARIANTS["baseline-06b"].prefix)  # thinking off    ids, cids = sorted(big_u), sorted(big)    for m, u, a in (("4B", big_u, big), ("0.6B", small_u, small)):        report.rate_lines(f"{m}, utility, 15 dev benign tasks", [u[t] for t in ids], f"{m}, utility interval")        report.rate_lines(f"{m}, attack success, 60 dev cases", [a[c][1] for c in cids], f"{m}, attack success interval")    # Paired differences, 0.6B minus 4B: one number per task or case, so each counts once.    for name, before, after in (("utility", [big_u[t] for t in ids], [small_u[t] for t in ids]),                                ("attack success", [big[c][1] for c in cids], [small[c][1] for c in cids])):        diffs = stats.paired_differences(before, after)        print(f"0.6B minus 4B, paired difference in {name}: {100 * sum(diffs) / len(diffs):+.1f} points, "              f"interval {stats.interval_points(*stats.bootstrap_mean(diffs))}")    # The carrier count, over the cases whose carrier a tool returns. Tool-description cases are left out.    counted = [c for c in cids if big[c][0].carrier["kind"] in report.CARRIER_TOOL]    never = {}    for m, a in (("4B", big), ("0.6B", small)):        never[m] = sum(report.never_read(big[c][0], a[c][2]) for c in counted)        print(f"never read the carrier, {m}: {never[m]} of {len(counted)}")    print(f"tool-description cases left out: {len(cids) - len(counted)}")    assert never["0.6B"] > never["4B"], "the weaker model should read the carrier less often"  # the prose's claimif __name__ == "__main__":    main()
输出python prompt-small-model.py
4B, utility, 15 dev benign tasks: 93.3% (14 of 15)
4B, utility interval: [80.0%, 100.0%]
4B, attack success, 60 dev cases: 11.7% (7 of 60)
4B, attack success interval: [5.0%, 20.0%]
0.6B, utility, 15 dev benign tasks: 20.0% (3 of 15)
0.6B, utility interval: [0.0%, 40.0%]
0.6B, attack success, 60 dev cases: 0.0% (0 of 60)
0.6B, attack success interval: [0.0%, 0.0%]
0.6B minus 4B, paired difference in utility: -73.3 points, interval [-93.3, -53.2] points
0.6B minus 4B, paired difference in attack success: -11.7 points, interval [-20.0, -5.0] points
never read the carrier, 4B: 0 of 53
never read the carrier, 0.6B: 24 of 53
tool-description cases left out: 7
练习 4.3

为什么零不等于抵抗力

+10 项证明

该示例打印了 0.6B 模型的攻击成功率为零,并在旁边给出了该模型从未读取载体的案例数。下列哪一项陈述解释了为什么这个零并不能证明该模型能够抵御注入?

为什么零不等于抵抗力:选出正确的解释
运行于 Python 3.13.16

在开发集上,0.6B 模型看起来比 4B 模型更安全。它的攻击成功率为 0.0% (0 of 60);与 4B 模型在相同任务和用例上相比,其攻击成功率的配对差值为 -11.7 points, interval [-20.0, -5.0] points。其效用的配对差值为 -73.3 points, interval [-93.3, -53.2] points。

效用差距在意料之中:较小的模型完成的办公工作更少。攻击差距则需要细看。在每个计入统计的攻击用例中,载体是包含注入文本的工具结果,每种载体类型都有一个返回其完整内容的工具。计数所问的是,模型是否调用了那个工具。0.6B 模型在 24 of 53 个计入统计的用例中从未调用它。4B 模型在 0 of 53 个计入统计的用例中从未调用它。工具描述类用例不计入两项统计,因为它们的文本位于每个提示词的工具模式中,不可能不被读到,这类用例共有 7 个。

模型从未读取的用例,不可能通过那段文本达到其目标,因此 0.6B 模型的零值在一定程度上反映的是它的行为。该模型还完成了 20.0% (3 of 15) 的良性任务。所以,它的零值不能被解读为抵抗:无论是否注入了某个动作,它都无法对交给它的任务采取行动。一种使 4B 模型读得更少的防御,也会呈现同类的零值。与比率并列报告的读取次数,正是区分这两种情形的依据。

工作准则: 在把较低的攻击成功率归功于某个模型或某种防御之前,先统计它读取载体的次数。把这个次数与比率并列报告。来自模型从未读取的文本的比率,统计的是模型做了什么,并不是模型具备抵抗能力的证据。

留出集运行

每种防御的措辞都在开发集上确定,随后各在留出集上运行一次。两个数据划分的结果都会报告,每项结论都注明所依据的划分;开发集上的结果若未在留出集上重现,就说明它不成立。开发集的结果用于选定措辞,因此不能同时用来证明措辞有效。留出集是取自相同攻击族的第二个样本,本书对每种防御只采用其一次运行的结果。区间是衡量单次运行可能波动多大的可靠尺度。留出集上未设防的运行结果低于开发集,已在第 3 章中报告。

留出集示例给出了每种防御的攻击成功率配对差值及其区间:

  • 警告:-1.7 points,区间 [-8.3, +3.3] points。
  • 分隔符:+3.3 points,区间 [-3.3, +10.0] points。
  • 数据标记:-5.0 points,区间 [-11.7, +1.7] points。
  • 重复请求:-1.7 points,区间 [-8.3, +5.0] points。
  • 编码:-11.7 points,区间 [-20.0, -3.3] points。

在留出集上,只有编码的攻击成功率差值不含零,而它是以上文所述的可用性代价换来的。留出集的运行证实了编码和重复请求这两项较大的可用性代价,二者的区间都不含零。警告和数据标记的代价较小,其区间触及零,留出集没有证实这两项代价。警告的代价只在留出集上出现。

开发集对各种防御并不都更宽容。它高估了分隔符对攻击的削减幅度和重复请求的可用性代价,又低估了警告、数据标记和编码的可用性代价。仅凭开发集得出的结论,对其中每一种防御都会出错,而且偏差方向各不相同。

留出集也是有限的资源。修改措辞后再做第二次留出集运行,就等于对这一划分看了第二遍,其结果也就不再是留出的。如果某次留出集运行显示某种防御失效,修正要回到开发集上进行,而留出集对该措辞来说就此用尽。应记录每种防御在留出集上运行的次数,并将次数与结果一并报告。

这些结果只适用于一组固定的攻击集和一个模型,而且这些攻击是静态的:每次都是相同的样例、相同的措辞。Nasr et al., 2025, The Attacker Moves Second是一篇预印本,就其副本所示并未经过同行评审。它针对已发表且报告了较低静态攻击成功率的防御搜索攻击,搜索在 AgentDojo 上进行。其自适应攻击攻破了其中大部分防御。它报告为被攻破的清单中包括 spotlighting 和 prompt sandwiching,后者即本章所称的重复请求这一设计。该预印本的静态结果较低,自适应结果较高。因此,本章中静态结果为零,仅说明对这一攻击集成立,不能更进一步。第 11 章针对会自适应的攻击者,在本书自己的模型上测试其中两种防御:数据标记和编码。

工作准则: 报告每种防御在留出集上的攻击成功率配对差值及其区间,只有当区间不含零时,才声称攻击有所削减。不要在留出集上再次调优。静态结果只对静态集成立,它会在第 11 章遇到自适应攻击者。

本章,在本版次中

版次 2026.11.3示例于 2026年11月22日 通过6 of 6个示例 in this chapter pass

译自英文版图书,版次 2026.11.3。

开始实验室

图书始终免费阅读。

查看价格

引用本节

格式

每种格式均引用英文原书,本译本以其为准。

每种格式都会注明该版次。其链接会打开当前版次,节标题处会说明该节文本最后一次修改的时间。访问日期和检索日期即为您打开此页的当天。

本页内容

第 4 章,共 12 章: 衡量提示层防御的收益

  1. 提示词中的警告
  2. 分隔符与聚光标记
  3. 分隔符
  4. 数据标记
  5. 编码
  6. 重复请求
  7. 各自的代价
  8. 更小的模型
  9. 留出集运行

返回顶部全部章节