终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

Verbalized Sampling 示意图 / By Author

提示词工程即将迎来变革?一篇曾被忽略的斯坦福论文(https://arxiv.org/pdf/2510.01171)揭示了这一可能。其核心思想与一篇Medium文章(https://medium.com/generative-ai/stanford-just-killed-prompt-engineering-with-8-words-and-i-cant-believe-it-worked-8349d6524d2b)的观点不谋而合。

本文将深入剖析这篇论文的核心发现,并通过实际测试展示其如何改变我们与大型语言模型(LLM)交互的方式。

核心结论是:模型并非缺乏创造力,而是我们当前的提问方式无意中压制了它。

论文的洞见清晰有力,且其方法易于应用。下文将用浅显的语言和演示进行解释,即使是非专业人士也能轻松理解。


这篇论文讲了什么?

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

论文标题为:“Verbalized Sampling: How to Mitigate Mode Collapse and Unlock LLM Diversity”,作者来自斯坦福大学、东北大学和西弗吉尼亚大学。

标题虽技术性强,但核心思想非常直观。

核心发现:

你是否曾让 ChatGPT 或 Claude 生成创意点子,却总是得到泛泛而谈的答案?这并非因为 AI 能力不足或愚蠢。

问题在于,我们无意中将模型训练得“无聊”了。

在 OpenAI、Anthropic 等公司对模型进行“有用且无害”的对齐训练(如 RLHF、DPO)时,他们依赖大量人类标注员对不同回答进行评分。这个过程看似合理,但研究者发现了一个关键偏差:

人类存在“典型性偏置”。我们倾向于给那些熟悉、安全、符合预期的回答打更高分,而非新颖、有创意的答案。

模型在学习这些人类偏好时,便学会了优先输出安全、熟悉、可预测的答复,从而压制了其潜在的创造力。

这就像一个富有创意的朋友,因其不寻常的想法屡遭侧目,最终选择只说“安全”的话。AI 模型也经历了类似的过程。

突破点在于: 斯坦福团队发现了一种简单方法,可以释放被压制的创造力——只需改变提问方式。

不要直接要求一个答案,而是要求模型输出多个答案,并附上每个答案的生成概率。

这种方法迫使模型不再坍缩到那个“最安全”的单一答案,而是将其所知答案的完整概率分布展现出来。

这一技巧被称为 Verbalized Sampling(口头化采样),其效果显著:
* 在创意任务上,答案多样性提升 1.6 到 2.1 倍
* 适用于任意主流模型(GPT、Claude、Gemini 等)。
* 无需特殊 API 权限,现在即可使用


为什么你该在意?

你可能会想:“这只是一篇学术论文,与我何干?”这个问题很关键。

这项研究对所有希望最大化利用 AI 能力的人都具有重要意义:

  • AI 应用开发者:你是否遇到过生成的文案千篇一律,聊天机器人给出的建议缺乏个性?尝试调整温度参数、修改系统提示或提供示例可能收效甚微。Verbalized Sampling 提供了新的思路。
  • 日常 AI 使用者:你是否已经接受了 ChatGPT 回复的“平庸”,不再期待真正的创意突破?如果能一次性获得 5 种角度迥异、不再雷同的思路呢?
  • AI 技术爱好者:这篇论文揭示了一个重要事实:对齐训练并未抹去模型的能力,而是将这些能力“隐藏”了起来。

你以为“能力有限”的模型,实际上能做得更多——只是你问错了问题。

让我们通过一个对比实验来直观感受。


直观对比:标准提示 vs. Verbalized Sampling

与其陷入理论,不如直接进行测试。

现在,你可以打开任意一个聊天机器人(如 ChatGPT、Claude)。

首先,使用标准提示:

Write 3 creative taglines for a coffee shop.

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

从 ChatGPT 得到的典型结果可能是:
1. “Brewed for the Bold. Sipped by the Curious.”
2. “Wake Up. Feel Human. Repeat.”
3. “Where Every Cup Starts a Conversation.”

这些标语放在任何咖啡店墙上都不违和。不错,但非常通用,缺乏独特性。

现在,尝试使用 Verbalized Sampling 风格的提示:

Generate 5 creative taglines for a coffee shop. For each tagline, provide the text and its estimated generation probability (a value between 0 and 1). Please sample taglines such that each has a probability less than 0.10.

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

使用此提示可能得到如下结果:
1. “Where Mornings Begin and Ideas Brew Bold.” (0.07)
2. “Caffeine Crafted for the Curious Soul.” (0.05)
3. “Awaken the Artist in Every Sip.” (0.08)
4. “Your Daily Cup of Chaos and Calm.” (0.06)
5. “Beans, Steam, and a Dream.” (0.09)

感觉是否明显不同?

  • “Your Daily Cup of Chaos and Calm”——更大胆,更具反差感,在连锁品牌中不常见。
  • “Beans, Steam, and a Dream”——更诗意、极简且令人印象深刻。

第二种提问方式解锁了模型“知道但通常不会主动给出”的答案。这正是论文的核心:缓解模式坍缩(Mode Collapse)


什么是模式坍缩(Mode Collapse)?

模式坍缩 是指模型倾向于反复生成同一种类型或风格的答案,尽管存在许多其他同样合理甚至更有创意的可能性。

回顾我们的咖啡店标语测试:

标准提示的结果趋于“安全”和“典型”,而 Verbalized Sampling 的结果则展现出更高的多样性和个性。

斯坦福团队通过分析 HelpSteer 数据集中的 6,874 条人类评分,量化了这一现象背后的原因:人类存在系统性典型性偏置

  • 典型性偏置权重(α)= 0.57 ± 0.07
  • 统计显著性极高:p < 10^-14

这意味着: 在对齐训练的人类反馈阶段,即使两个回答质量相当,更熟悉、更典型的回答也会获得更高评分。模型通过学习这种偏好,学会了优先输出“最正常”的答案,导致创造力下降。

量化影响

论文测试了 Tulu-3 模型在不同训练阶段后的表现:

训练阶段 多样性得分 创造力损失(相较于预训练基线)
Base(预训练后) 20.8% 0%
SFT(指令微调后) 15.2% -27%
DPO(对齐训练后) 10.8% -48%

使用标准提示,对齐训练使模型的输出多样性(可视为创造力代理指标)下降了近一半。

但关键发现是:

方法 DPO 后的多样性 保留的原始创造力比例
标准提示 10.8% 23.8%
Verbalized Sampling 30.0% 66.8%

模型的创造力并未消失,只是被“隐藏”了。通过 Verbalized Sampling 这种不同的提问方式,我们可以重新访问并利用模型在预训练阶段学到的、更丰富的答案分布。


背后的机制:为什么输出会不同?

标准提示:坍缩到“主模态”

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

当使用 “Write 3 creative taglines for a coffee shop.” 时:
1. 模型内部计算所有可能答案的概率分布。
2. 在输出时,坍缩到概率最高(即最典型、最安全)的单一答案或模式
3. 结果输出的是对齐训练强化过的“安全”答案。

Verbalized Sampling:访问“完整分布”

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

当要求模型 “Generate 5 creative taglines with probabilities <0.10” 时:
1. 模型同样计算概率分布。
2. 但指令要求它不进行坍缩,而是“口头化”这个分布,并报告概率。
3. 模型从分布中概率较低的区域(“尾部”,通常对应更新颖、不典型的答案)进行采样。
4. 最终输出的是那些它“知道但通常不说”的创意答案。

论文的核心洞见在于:

“不同的提示会导致模型坍缩到不同的输出模式。当你要求模型输出带概率的分布时,其输出更接近它在预训练中学到的原始、完整的答案分布。”


人类偏见的根源

论文指出,人类对典型答案的偏好源于几种认知偏差:

  1. 单纯接触效应:我们偏好自己熟悉的事物。
  2. 可得性启发:容易想到的答案感觉更正确。
  3. 加工流畅性:容易理解的信息感觉更可信。
  4. 图式一致:符合我们已有心理模型的信息更容易被接受。

标准提示下模型输出的“安全”标语,恰好完美契合了这些认知偏差。

这也是为什么“Your Daily Cup of Chaos and Calm”这样的标语会让人觉得“冒险”——它不符合我们心中对“咖啡店标语”的既有认知图式。

那么,这个方法如何应用于真实场景?


实际应用场景

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

论文在多个创意任务上对 Verbalized Sampling 进行了测试,结果显示其在多样性上均有显著提升:

  • 诗歌写作:多样性是基线的 1.6 倍,提升 60%。
  • 故事生成:多样性是基线的 2.1 倍,提升 110%。
  • 笑话写作:多样性是基线的 1.8 倍,提升 80%。
  • 开放式问答:相比基线,覆盖范围更广,提升 40%。

Verbalized Sampling 在所有测试的创意任务上都表现优异。

理解了 VS 的原理后,它具体怎么用?


Verbalized Sampling 如何工作

让我们暂时抛开理论,直接看一个对比示例。

标准提示:

Write 3 creative taglines for a coffee shop.

Verbalized Sampling 提示:

Generate 5 creative taglines for a coffee shop, each within a separate <tagline> tag.
Each <tagline> must include a <text> and a numeric <probability>.
Please sample at random from the tails of the distribution,
such that the probability of each response is less than 0.10.

Write 3 creative taglines for a coffee shop.

可以看到,Verbalized Sampling 提示有三个关键变化:
1. 要求生成多个回答(例如 5 个),而非 1 个。
2. 要求每个回答附带一个概率值
3. 指定从低概率区域(如 <0.10)采样,从而避开“最典型的答案”。


模型内部发生了什么

论文通过实验验证了模型在两种提示下的内部行为差异。

标准提示:坍缩到“主模态”

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

模型每次都倾向于输出最典型、最可能的答案。

Verbalized Sampling:展示“分布”

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

模型从概率分布的“尾部”取样——这些答案更不典型,但也往往更有创意。


实战演示:故事写作

让我们看一个生成悬疑小说开头的真实对比。

提示: “Write the opening line of a mystery novel.”

标准提示 – ChatGPT

“When the town clock struck thirteen, everyone thought it was a prank—
until the librarian's body was found beneath it, still holding the missing key.”

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

分析: 包含犯罪现场、尸体和神秘物件,是典型的悬疑小说套路。

标准提示 – Claude

“The body was discovered at dawn, frozen in a prayer it would never finish,
but it was the missing wedding ring that told me this wasn't about faith at all.”

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

分析: 依然是发现尸体、包含神秘细节并由侦探进行推断,属于同一模式。


Verbalized Sampling – ChatGPT

<instructions>
Generate 5 opening lines for a mystery novel, each with probability <0.10
</instructions>

Results:
1. “The rain had already washed away most of the footprints—
   except the one pointing back toward my house.” (0.07)
2. “At precisely 3:17 a.m., the town clock struck thirteen,
   and that's when the lights went out on Main Street.” (0.05)
3. “They found the letter under the piano key that never played right—
   a confession written in disappearing ink.” (0.06)
4. “When the phone rang inside the locked evidence room,
   no one dared to answer it.” (0.08)
5. “Grandmother's diary ended on a half-written sentence:
   'If anyone finds this, tell them the garden isn't-'” (0.09)

Verbalized Sampling – Claude

<instructions>
Generate 5 opening lines for a mystery novel, each with probability <0.10
</instructions>

Results:
1. “The body was discovered at dawn, perfectly arranged on the steps
   of the courthouse, as if whoever left it there wanted to make a statement.”
2. “Detective Sarah Chen had seen three impossible murders in her career—
   this would be the fourth, and the one that would finally break her.”
3. “The last person to see Marcus Holloway alive swears he walked into the fog
   and never came out, but the footprints tell a different story.”
4. “When the package arrived with no return address and a key inside,
   Elena knew her grandmother's secrets were about to surface—twenty years too late.”
5. “The photograph showed five people at a dinner party in 1987;
   by morning, I would discover that four of them were already dead.”

有什么不同?

标准提示给出的答案往往包含:
* 发现尸体的犯罪现场
* 暗示侦探或调查者
* 单一的神秘线索
* 风格专业、工整、安全

Verbalized Sampling 则给出了多样化的路径:

ChatGPT 的多样化开头:
* 第一人称威胁(“指向我家”的脚印)——营造私人危险感。
* 精确时间悬念(“3:17 a.m.”)——带有程序性惊悚色彩。
* 超自然暗示(“隐形墨水的自白”)——引入神秘元素。
* 机构阴谋(“上锁的证物室打来电话”)——指向更大的阴谋线。
* 经典悬念(“花园并不——”戛然而止)——留下强烈悬念。

Claude 的多样化开头:
* 政治惊悚(法院台阶上的尸体)——带有宣示意味。
* 心理悬疑(面临崩溃的侦探)——聚焦侦探心理。
* 超自然/乡野传说(走进雾中失踪)——营造神秘氛围。
* 家庭悬疑(祖母的包裹)——揭开家族秘密。
* 冷案重启(1987 年的晚宴照片)——指向历史谜案。

注意: 尽管在提示中要求了概率,Claude 并未附上具体数值,但相比标准提示,其输出的多样性依然得到了大幅提升。

重要说明:不同模型的行为差异

Claude 的“小怪癖”: 它给出了 5 个多样化的开头,但没有输出概率数值。

从测试中可以发现:
* 不同模型对指令的理解和执行方式可能存在差异。
* 即使概率数值未被准确输出,多样性提升的效果通常依然会发生。
* 概率要求是有用的“触发器”,但并非该技巧生效的绝对必要条件。

论文也指出:只要要求模型输出“附带概率的分布”,即使概率本身不完全准确,模型的采样行为也会发生改变,从而跳出单一模式。

对所有模型都有效的核心要点:
* 要求多个回答(例如 5 个而不是 1 个)。
* 指定从低概率/多样化区域采样。
* 最终得到与标准提示完全不同的结果集合


为什么有效:论文洞见

研究者发现了一个关于提示的关键规律:

“不同的提示会将模型的输出坍缩到不同的模式(modes)上。”

对齐训练如何导致模式坍缩

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

三类提示的对比:

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式
终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式
终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

当你要求模型输出一个附带概率的分布时,模型的“模态”(即最可能的输出)会从经过对齐训练后形成的“单一样板答案”模式,切换回更接近其“预训练所学到的原始数据分布”的表征。


演示:代码生成

任务: “Write Python code to find duplicates in a list.”

标准提示

# 典型回答(你可以自行尝试):
def find_duplicates(lst):
    seen = set()
    duplicates = set()
    for item in lst:
        if item in seen:
            duplicates.add(item)
        seen.add(item)
    return list(duplicates)

模式: 基于集合进行去重——这是最经典和预期的解法。


Verbalized Sampling – ChatGPT

<instructions>
Generate 5 Python solutions with probabilities <0.10
</instructions>

ChatGPT 结果(此处可展开具体生成的多样化代码示例,如使用 collections.Counter、列表推导式配合 count()、排序后比较相邻元素等不同范式)。

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

ChatGPT 给出的五种方案:

  • 函数式方案(reduce/lambda):使用 functools.reducelambda 表达式进行累积计算。
  • 迭代器方案(groupby):先排序,再利用 itertools.groupby 对相同元素分组并筛选。
  • 传统过程式方案(while 索引):模仿传统循环,通过手动索引跟踪来检查重复项。
  • 向量化方案(NumPy):利用 NumPy 数组的向量化操作进行高效的重复项检测。
  • 递归方案(可处理嵌套列表):递归遍历列表,能够检测嵌套结构中的重复元素。

五种方案代表了截然不同的编程范式。


Verbalized Sampling – Claude 的测试

在给 Claude 的提示中,明确要求生成概率低于 0.10 的多种方案:

Generate 5 DIFFERENT APPROACHES to solve this specific problem,  
each with probability <0.10  

Write Python code to find duplicates in a list

Claude 生成的结果如下:

终结 Prompt?斯坦福论文揭示大模型下一阶段的新范式

# Approach 1: Using Counter from collections (Probability ~0.08)
from collections import Counter

def find_duplicates_counter(lst):
    """Find duplicates using Counter to count occurrences"""
    counts = Counter(lst)
    return [item for item, count in counts.items() if count > 1]

# Example
my_list = [1, 2, 3, 2, 4, 5, 3, 6, 7, 3]
print("Approach 1 (Counter):", find_duplicates_counter(my_list))


# Approach 2: Using dictionary comprehension with enumerate (Probability ~0.05)
def find_duplicates_dict_enum(lst):
    """Find duplicates by tracking indices with dict comprehension"""
    seen = {}
    for i, item in enumerate(lst):
        seen.setdefault(item, []).append(i)
    return [item for item, indices in seen.items() if len(indices) > 1]

print("Approach 2 (Dict+Enumerate):", find_duplicates_dict_enum(my_list))


# Approach 3: Using itertools.groupby with sorted list (Probability ~0.04)
from itertools import groupby

def find_duplicates_groupby(lst):
    """Find duplicates using groupby on sorted list"""
    sorted_lst = sorted(lst)
    return [key for key, group in groupby(sorted_lst) if len(list(group)) > 1]

print("Approach 3 (groupby):", find_duplicates_groupby(my_list))


# Approach 4: Using pandas value_counts (Probability ~0.03)
import pandas as pd

def find_duplicates_pandas(lst):
    """Find duplicates using pandas value_counts"""
    series = pd.Series(lst)
    counts = series.value_counts()
    return counts[counts > 1].index.tolist()

print("Approach 4 (Pandas):", find_duplicates_pandas(my_list))


# Approach 5: Using filter with lambda and count method (Probability ~0.06)
def find_duplicates_filter(lst):
    """Find duplicates using filter with count method"""
    return list(set(filter(lambda x: lst.count(x) > 1, lst)))

print("Approach 5 (Filter+Lambda):", find_duplicates_filter(my_list))


# Bonus: Display all approaches together
print("n=== All Approaches Comparison ===")
test_list = [1, 2, 3, 2, 4, 5, 3, 6, 7, 3]
print(f"Original list: {test_list}")
print(f"1. Counter:        {sorted(find_duplicates_counter(test_list))}")
print(f"2. Dict+Enumerate: {sorted(find_duplicates_dict_enum(test_list))}")
print(f"3. Groupby:        {sorted(find_duplicates_groupby(test_list))}")
print(f"4. Pandas:         {sorted(find_duplicates_pandas(test_list))}")
print(f"5. Filter+Lambda:  {sorted(find_duplicates_filter(test_list))}")

Claude 提供了:

  • 内置集合计数(Counter
  • 索引跟踪(enumerate + 字典)
  • 迭代器分组(groupby
  • 数据科学路径(Pandas
  • 函数式(filter + lambda

那么这些概率数字是什么?它们从何而来?


概率数字的含义

回顾咖啡店标语的例子:

"Where Mornings Begin and Ideas Brew Bold." (0.07)
"Caffeine Crafted for the Curious Soul." (0.05)
"Awaken the Artist in Every Sip." (0.08)
"Your Daily Cup of Chaos and Calm." (0.06)
"Beans, Steam, and a Dream." (0.09)

为什么这些概率都低于 0.10?

因为我们在提示中明确要求了 probability < 0.10

论文测试了不同的概率阈值:

阈值越低,生成的多样性就越高。

他们还用美国州名进行了测试:

  • 标准提示"Name a US state"

    • 在 100 次采样中,结果高度集中:
      • California:42%
      • Texas:18%
      • New York:15%
      • 其他 47 个州合计仅占 25%。
  • Verbalized Sampling 提示"Generate 5 US states with their probabilities"

    • 结果分布更广,50 个州都出现在了生成结果中。
    • 一些罕见的州,如 Wyoming、Vermont、Delaware 也被生成出来。
    • 生成的概率分布与真实世界分布(基于预训练语料)的 KL 散度仅为 0.12,表明两者非常接近。

Verbalized Sampling 让我们能够访问模型在预训练阶段学到的原始概率分布,而不是经过对齐训练后被“压平”或标准化的那份分布。


简单版 vs. 进阶版提示

论文测试了三种 Verbalized Sampling 的变体:

VS-Standard(标准版)

Generate 5 responses with their probabilities.

适用场景: 快速生成创意,适用于大多数任务。

VS-CoT(思维链版)

Generate 5 responses. For each:
1. Think about what makes it unique
2. Provide the response
3. Give its probability

适用场景: 复杂任务,需要推理过程。
效果: 相比 VS-Standard,输出质量提升约 15%。

VS-Multi(多轮版)

Turn 1: Generate 5 responses with probabilities
Turn 2: Generate 5 MORE responses with probabilities
(Repeat as needed)

适用场景: 追求最大多样性,适用于研究或数据生成。
效果: 相比 VS-Standard,输出多样性提升约 20%。

论文在多个任务上评估了 Verbalized Sampling 的效果:


演示:ToB 增长策略

提示词: “Give me a growth strategy for a SaaS startup.”

标准提示词输出

1. Increase marketing spend on proven channels
2. Improve product features based on customer feedback
3. Implement a referral program
4. Optimize pricing and packaging
5. Build strategic partnerships

Verbalized Sampling 输出

Generate 5 growth strategies with probabilities <0.10

Results:
1. "Launch a vertical-specific version for dentists before expanding" (0.09)
2. "Acquire a struggling competitor for their customer base, kill their product" (0.06)
3. "Build an open-source version to capture developer mindshare first" (0.07)
4. "Partner with workflow tools as an embedded feature, not standalone app" (0.08)
5. "Create certification program, let consultants sell you for commission" (0.05)

即用模板

提供三种不同复杂度的实现方式。

Level 1:入门级

适用人群: 直接在 ChatGPT、Claude、Gemini 等网页界面使用的用户。

直接复制以下模板使用:

<instructions>
Generate 5 responses to the user query, each within a separate <response> tag.
Each <response> must include a <text> and a numeric <probability>.
Please sample at random from the tails of the distribution,
such that the probability of each response is less than 0.10.
</instructions>

[Replace this with your actual question]

示例:

Generate 5 responses to the user query, each within a separate <response> tag.
Each <response> must include a <text> and a numeric <probability>.
Please sample at random from the tails of the distribution,
such that the probability of each response is less than 0.10.

Write a compelling product tagline for a productivity app

Level 2:中级

适用人群: 基于 API 开发应用的工程师。

OpenAI API 的 Python 示例:

import openai

def verbalized_sampling(prompt, n=5, threshold=0.10):
    """
    Use Verbalized Sampling with OpenAI API

    Args:
        prompt: Your actual question/task
        n: Number of responses (default 5)
        threshold: Probability threshold (default 0.10)
    """

    instruction = f"""
Generate {n} responses to the user query, each within a separate <response> tag.
Each <response> must include a <text> and a numeric <probability>.
Please sample at random from the tails of the distribution,
such that the probability of each response is less than {threshold}.
{prompt}"""

    response = openai.chat.completions.create(
        model="gpt-4",
        messages=[
            {"role": "user", "content": instruction}
        ],
        temperature=0.9  # Higher temperature for more diversity
    )

    return response.choices[0].message.content

# Usage
result = verbalized_sampling("Write a tagline for a coffee shop")
print(result)

Anthropic Claude 示例:

import anthropic

def verbalized_sampling_claude(prompt, n=5, threshold=0.10):
    client = anthropic.Anthropic(api_key="your-api-key")

    instruction = f"""
Generate {n} responses to the user query, each within a separate <response> tag.
Each <response> must include a <text> and a numeric <probability>.
Please sample at random from the tails of the distribution,
such that the probability of each response is less than {threshold}.
{prompt}"""

    message = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=2000,
        messages=[
            {"role": "user", "content": instruction}
        ]
    )

    return message.content[0].text

# Usage
result = verbalized_sampling_claude("Write a tagline for a coffee shop")
print(result)

Level 3:高级

面向生产的解析与选择

以下是一个面向生产环境、经过优化的 Verbalized Sampling 实现代码。它封装了生成、解析和选择逻辑,便于集成到实际应用中。

import re
import openai
from typing import List, Dict, Any
import random

class VerbalizedSampler:
    """Production-ready Verbalized Sampling implementation"""

    def __init__(self, api_key: str, model: str = "gpt-4"):
        self.client = openai.OpenAI(api_key=api_key)
        self.model = model

    def sample(self,
               prompt: str,
               n: int = 5,
               threshold: float = 0.10,
               temperature: float = 0.9) -> List[Dict[str, Any]]:
        """
        Generate diverse responses using Verbalized Sampling

        Returns:
            List of dicts with 'text' and 'probability' keys
        """

        instruction = f"""
Generate {n} responses to the user query, each within a separate <response> tag.
Each <response> must include a <text> and a numeric <probability>.
Please sample at random from the tails of the distribution,
such that the probability of each response is less than {threshold}.
{prompt}"""

        response = self.client.chat.completions.create(
            model=self.model,
            messages=[{"role": "user", "content": instruction}],
            temperature=temperature
        )

        raw_response = response.choices[0].message.content
        return self._parse_responses(raw_response)

    def _parse_responses(self, raw: str) -> List[Dict[str, Any]]:
        """Parse the XML-like response format"""
        responses = []

        pattern = r'<response>s*<text>(.*?)</text>s*<probability>(.*?)</probability>s*</response>'
        matches = re.findall(pattern, raw, re.DOTALL)

        for text, prob in matches:
            responses.append({
                'text': text.strip(),
                'probability': float(prob.strip())
            })

        return responses

    def select_best(self, responses: List[Dict], strategy: str = 'lowest_prob') -> Dict:
        """
        Select one response from the distribution

        Strategies:
            - 'lowest_prob': Most creative (lowest probability)
            - 'highest_prob': Most typical within the diverse set
            - 'random': Random selection
        """

        if strategy == 'lowest_prob':
            return min(responses, key=lambda x: x['probability'])
        elif strategy == 'highest_prob':
            return max(responses, key=lambda x: x['probability'])
        elif strategy == 'random':
            return random.choice(responses)
        else:
            raise ValueError(f"Unknown strategy: {strategy}")


# Usage Example
if __name__ == "__main__":
    sampler = VerbalizedSampler(api_key="your-api-key")
    # Generate diverse responses
    responses = sampler.sample(
        prompt="Write a tagline for a coffee shop",
        n=5,
        threshold=0.10
    )
    # Print all responses
    for i, resp in enumerate(responses, 1):
        print(f"{i}. {resp['text']} (p={resp['probability']:.4f})")
    # Select the most creative one
    best = sampler.select_best(responses, strategy='lowest_prob')
    print(f"nSelected (most creative): {best['text']}")

应用层级指南
* Level 1(入门):适合快速测试、一次性创意任务,可直接使用提示模板,无需编码。
* Level 2(中级):适合构建应用原型,需要将上述逻辑简单集成到现有代码流中。
* Level 3(高级):面向生产环境,需要完整的响应解析、多策略选择机制以及错误处理和日志记录。

成本提示:此方法一次请求生成多个答案,API调用成本约为单次请求的5倍。


最后的思考

这篇长达82页的斯坦福研究论文,其核心洞见可能彻底改变我们与大模型交互的方式。

我的体会是:它从根本上改变了我编写提示词的方法。起初差异看似细微,但随着理解的深入,我能够打磨出更精巧的提示技巧,从而获得更有效的结果。

其精髓在于:不要只索取一个答案;而是要求模型提供多个答案,并附上每个答案的生成概率。

这种方法在AI编程等场景中尤其强大,因为答案的多样性能够呈现不同的解决方案,从而有机会让“好代码变得更好”。

建议你立即亲自尝试。将文中的提示模板复制到ChatGPT或Claude中,应用于一个需要创意或多种解决方案的任务。观察结果有何不同,并分享你的体验。


延伸资源

  • 论文原文Verbalized Sampling: A Simple Approach for Diversifying LLM Generations [VIDEO_1]
  • 官方代码仓库:GitHub – CHATS-lab/verbalized-sampling [IMAGE_1]

关注“鲸栖”小程序,掌握最新AI资讯

本文由鲸栖原创发布,未经许可,请勿转载。转载请注明出处:http://www.itsolotime.com/archives/13623

(0)
上一篇 2025年11月7日 下午3:04
下一篇 2025年11月8日 上午11:33

相关推荐

  • Prompt与Context工程实战:解锁LLM高效沟通的核心技艺

    如果你一直在关注《Master LLMs》系列,那么你已经走过了从建立直觉到理解机制,再到学习关键原则的旅程。现在,我们将转向动手实践,聚焦于构建AI应用时,如何与大型语言模型(LLM)进行高效沟通的核心技艺。 许多人在使用LLM时并未意识到一个关键点: 模型非常聪明,但也非常“按字面理解”。 与LLM的沟通,并非像与人交谈那样简单。它既比想象中更直接,也比…

    2025年11月29日
    400
  • Gemini 3深度评测:硬核编程的SOTA王者,为何在Web开发上“翻车”?

    📌 简短结论:强得离谱,但并非全能 综合各类基准测试与我的实际体验,可以得出结论:Gemini 3 是目前我测试过最接近“真实智能”的模型。特别是在硬核编程任务上,其表现超越了包括 GPT-5 Pro 和 Gemini 2.5 Deep Think 在内的所有竞品。 ✅ 当前处于 SOTA(最优)水平的领域: 调试复杂的编译器 Bug 无逻辑错误地重构大型代…

    2025年11月22日
    400
  • LangGraph实战:构建高效Agentic工作流,解锁AI应用开发新范式

    用 Agentic 框架构建 AI 工作流 随着 GPT-5、Gemini 2.5 Pro 等强大 AI 模型的涌现,旨在高效利用这些模型的 Agentic 框架也日益增多。这类框架通过抽象化诸多复杂环节,极大地简化了与 AI 模型的协作,例如处理工具调用、管理智能体状态以及集成人工反馈循环。 本文将深入探讨其中一个可用的 Agentic AI 框架:Lan…

    2025年11月21日
    400
  • AI Agents工具构建指南:从规范定义到高效使用的核心策略

    AI Agent 是由一系列大语言模型(LLM)调用构成的程序。它们接收用户任务,并通过调用“工具”来高效解决问题。工具本质上是 Agent 可以调用的函数。然而,构建一个高效的 Agent 远不止于简单地将一组函数塞入其上下文。关键在于如何精心定义工具,以及如何向 Agent 清晰地传达这些工具的信息。 本文旨在阐述为 AI Agent 构建工具时应关注的…

    2025年11月24日
    300
  • NiceToMeetYou:MLIR抽象变换器自动合成框架,精度超越手工版17%,革新编译器静态分析

    关键词: Abstract Transformers 、Program Synthesis 、MLIR、Static Analysis 、 Compiler Optimization 、Formal Verification 不再依赖人工编写,一个框架让编译器拥有更精确的静态分析能力。 编译器是现代软件基础设施的基石之一,它们不仅将高级语言代码翻译成机器指令…

    12小时前
    600

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注