终结 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资讯

本文来自网络搜集,不代表鲸林向海立场,如有侵权,联系删除。转载请注明出处:https://www.itsolotime.com/archives/13623

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

相关推荐

  • 周末实战:5个能放进作品集的Agentic AI项目,助你求职脱颖而出

    人们常把“Agentic AI”描绘成只有大型实验室才能驾驭的高深技术。事实并非如此。 你完全可以在几天内,构建出真正能放进作品集的智能体项目。这些项目能解决实际问题,从而在求职时为你加分,而不是只会运行花哨提示词的玩具。 这里有五个你马上就可以动手实践的项目,即使你只有一台在卧室里、电量只剩一半的笔记本电脑。 我们将通过简单的示例逐一讲解,让你看清各个组件…

    2025年12月8日
    8600
  • 揭秘大模型幻觉根源:清华大学发现“讨好神经元”H-Neurons

    大模型胡说八道的根源,可能并非数据或算法问题,而在于它试图“讨好”用户。 清华大学OpenBMB团队在最新研究中,首次识别出专门负责产生幻觉的神经元——H-Neurons。这一发现颇具反直觉色彩:模型说谎并非因为能力不足,而是它将“满足用户指令”的优先级,置于“陈述事实”之上。 核心发现可归纳为三点: 精准定位:H-Neurons仅占模型总神经元的不到0.1…

    2025年12月22日
    9800
  • LangGraph 2026版:从核心概念到实战,构建自适应AI Agents的完整指南

    用 LangGraph 构建 AI Agents(2026 版):保姆级指南 过去两年里,LangGraph 已成为我在 AI 领域构建各类应用的核心工具。无论是聊天机器人、MCP助手、语音机器人还是内部自动化智能体,只要涉及推理、工具调用或多步骤工作流,我几乎都会选择 LangGraph。它反复出现在我的客户项目、个人实验乃至日常的生产系统中。 去年我撰写…

    2026年1月24日
    4800
  • TOON vs JSON:为LLM优化的结构化数据格式革命

    在提示词日益冗长、AI模型愈发强大的当下,一个核心问题反复浮现:如何同时降低使用成本和处理时间? 在以编程方式使用大语言模型时,结构化输出已成为标准实践。开发者可以要求模型按特定格式输出,例如JSON。通过定义一个模型架构并阐明各字段含义,AI会尽力理解上下文,并在其能力范围内填充输出。 这使得处理AI的响应变得前所未有的便捷。然而,输入环节呢? 即便我们能…

    5天前
    2600
  • Twill:斯坦福与NVIDIA联手打造Tensor Core GPU自动优化引擎,终结手工内核调优时代

    关键词: Tensor Core GPU 、Software Pipelining 、Warp Specialization 、Twill、Constraint Solving、 Modulo Scheduling 随着 AI 大模型向“更大参数、更长序列”发展,Tensor Core GPU 的优化需求将持续增长。Twill 所代表的“约束求解驱动的最优优…

    2025年12月29日
    7600

发表回复

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