AI Prompt Engineering · 课时

人工智能如何生成响应

了解令牌预测、概率,以及人工智能为何不会像人类一样“思考”。

第 3 / 4 课13 个步骤

人工智能如何生成响应 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。

将文本视为概率问题

从根本上说,语言模型只做一件事:根据此前的所有词元预测下一个词元。

词元是文本的一个小单位,大致相当于一个单词或单词片段。模型会为其词汇表中的每个词元分配一个概率,然后选择其中一个。接着,模型会逐个词元地重复这一过程,直到生成完整的响应。

什么是词元

词元是 LLM 文本处理的基本单位。英语文本大致会按以下方式进行词元化:

  • 常见单词 → 每个 1 个词元(the、run)
  • 不常见单词 → 拆分为 2 至 3 个词元(running → run + ning)
  • 标点和空格 → 通常各自作为词元

GPT-4o 和 Claude 等模型使用的词元分析器包含 10 万多个词汇条目,其中包括跨多种语言的子词。

import tiktoken

encoding = tiktoken.encoding_for_model('gpt-4o')

sentence = 'The temperature parameter controls randomness in token selection.'
tokens = encoding.encode(sentence)
token_strings = [encoding.decode([t]) for t in tokens]

print(f'Sentence: {sentence}')
print(f'Token count: {len(tokens)}')
print(f'Tokens: {token_strings}')

自回归生成

生成过程是自回归的:每个新词元都会附加到输入中,然后模型再预测下一个词元。

因此,在生成“天空是蓝色的”时,模型会:

  • 看到“天空” → 预测“是”
  • 看到“天空 是” → 预测“蓝色”
  • 看到“天空 是 蓝色” → 预测“的”
  • 看到“天空 是 蓝色 的” → 预测序列结束标记

这就是为什么很长的输出会生成得更慢——每个词元都需要一次完整的前向传播。

# Simulated autoregressive token-by-token output via streaming
import openai

client = openai.OpenAI(api_key='sk-your-key-here')

stream = client.chat.completions.create(
    model='gpt-4o',
    stream=True,     # receive tokens as they are generated
    messages=[{'role': 'user', 'content': 'Name five planets in our solar system.'}]
)

print('Tokens arriving one by one:')
for chunk in stream:
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end='', flush=True)
print()  # newline at end

温度:控制随机性

温度是一个介于 0 和 2 之间的数值,会在采样前缩放概率分布:

  • 温度 0:始终选择概率最高的词元——确定性强,但容易重复
  • 温度 1:按照原始概率进行采样——较为均衡
  • 温度 2:拉平概率分布——随机性很高,有时会不连贯

事实性任务使用较低的温度;创意工作使用较高的温度。

import openai

client = openai.OpenAI(api_key='sk-your-key-here')

prompt = 'Continue this sentence with one word: The ocean is'

for temp in [0.0, 0.7, 1.5]:
    response = client.chat.completions.create(
        model='gpt-4o',
        temperature=temp,
        max_tokens=5,
        messages=[{'role': 'user', 'content': prompt}]
    )
    word = response.choices[0].message.content.strip()
    print(f'Temperature {temp}: "{word}"')

为什么每次运行的响应会不同

即使使用相同的提示,同一个模型运行两次也可能产生不同的输出。这是因为:

  • 采样具有概率性——模型从概率分布中抽取结果,而不是查找表
  • 浮点运算中的微小数值差异可能层层累积
  • 硬件并行处理会引入不确定性

将 temperature=0 和 seed(如果受支持)设定好,可以最大限度地提高可复现性。

import openai

client = openai.OpenAI(api_key='sk-your-key-here')

prompt = 'Give me a one-word color that feels calm.'

for run in range(3):
    response = client.chat.completions.create(
        model='gpt-4o',
        temperature=1.0,   # randomness ON
        max_tokens=5,
        messages=[{'role': 'user', 'content': prompt}]
    )
    print(f'Run {run + 1}: {response.choices[0].message.content.strip()}')

# For reproducible outputs use seed + temperature=0
response = client.chat.completions.create(
    model='gpt-4o',
    temperature=0,
    seed=42,
    max_tokens=5,
    messages=[{'role': 'user', 'content': prompt}]
)
print(f'Deterministic: {response.choices[0].message.content.strip()}')

核采样

核采样是另一种控制随机性的方式。它不会缩放所有概率,而是将采样限制在一个最小词元集合中,使该集合的累积概率超过 p。

  • top_p=0.1:只有最靠前的词元(较保守)
  • top_p=0.9:更大的候选范围(更有创意)
  • top_p=1.0:所有词元(完整分布)

实际上,大多数团队会调整温度,并将核采样参数保持为 1.0。

import openai

client = openai.OpenAI(api_key='sk-your-key-here')

# Conservative generation: top_p=0.1 restricts to high-confidence tokens
response_conservative = client.chat.completions.create(
    model='gpt-4o',
    top_p=0.1,
    max_tokens=30,
    messages=[{'role': 'user', 'content': 'What is the capital of Japan?'}]
)

# Creative generation: top_p=0.95 allows broader token pool
response_creative = client.chat.completions.create(
    model='gpt-4o',
    top_p=0.95,
    max_tokens=30,
    messages=[{'role': 'user', 'content': 'Write a poetic one-liner about the moon.'}]
)

print('Conservative:', response_conservative.choices[0].message.content)
print('Creative:    ', response_creative.choices[0].message.content)

不具备真正理解——模式匹配

LLM 并不像人类那样理解语言。它们是经过海量文本语料训练的极其复杂的模式匹配器。

当模型回答“光合作用是什么?”时,它并不是在检索某个已存储的事实——而是根据训练期间见过数百万份相似文档的经验,生成在统计上接续这个问题模式的词元序列。

# Demonstration: the model can produce plausible-sounding but wrong answers
import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

# Asking about something nonsensical — model may still try to answer
response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=128,
    messages=[{
        'role': 'user',
        'content': (
            'What is the boiling point of happiness in degrees Celsius? '
            'Please just say "I cannot answer this" if the question makes no sense.'
        )
    }]
)
print(response.content[0].text)

训练与推理

模型的“知识”在大型文本语料上的训练期间被冻结。在推理阶段(当您发送提示时),模型会基于这些冻结的知识生成文本——它不会学习,也不会搜索互联网。

这意味着它无法了解训练截止日期之后发生的事件,无法访问网址,也无法验证某个事实自训练以来是否发生了变化。

import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

# Asking the model about its own knowledge cutoff
response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=128,
    messages=[{
        'role': 'user',
        'content': (
            'What is your knowledge cutoff date? '
            'And can you access the internet right now to look up today\'s news?'
        )
    }]
)
print(response.content[0].text)

一次前向传播中发生了什么

从高层次来看,每次词元预测都包括:

  1. 将所有输入词元转换为数值嵌入
  2. 让它们经过许多变换器层(注意力 + 前馈)
  3. 针对整个词汇表生成概率分布
  4. 从该分布中采样一个词元

现代模型拥有数十亿个参数,这些参数塑造了整个转换过程——它们都是在训练期间从人类文本中学习到的。

# You can inspect logprobs (token probabilities) to see the model's confidence
import openai

client = openai.OpenAI(api_key='sk-your-key-here')

response = client.chat.completions.create(
    model='gpt-4o',
    max_tokens=5,
    logprobs=True,
    top_logprobs=3,
    messages=[{'role': 'user', 'content': 'The opposite of hot is'}]
)

for token_info in response.choices[0].logprobs.content:
    print(f'Chosen token: "{token_info.token}"')
    for alt in token_info.top_logprobs:
        import math
        prob = round(math.exp(alt.logprob) * 100, 1)
        print(f'  Option "{alt.token}": {prob}% probability')

停止序列

停止序列会告诉模型:当生成特定字符串时停止生成。它们适用于:

  • 防止模型在列表中生成多个答案
  • 在遇到类似 ### 或 ---END--- 的分隔符时停止
  • 强制输出仅包含一行

如果没有停止序列,模型会一直生成,直到达到 max_tokens,或预测出序列结束词元。

import openai

client = openai.OpenAI(api_key='sk-your-key-here')

# Stop after the first item in a numbered list
response = client.chat.completions.create(
    model='gpt-4o',
    max_tokens=64,
    stop=['2.'],   # halt as soon as '2.' appears
    messages=[{
        'role': 'user',
        'content': 'List 5 programming languages, numbered 1 through 5.'
    }]
)
print(response.choices[0].message.content)
print('Stop reason:', response.choices[0].finish_reason)

面向提示编写者的实际意义

了解文本生成机制有助于您编写更好的提示:

  • 使用温度 0,处理需要一致且基于事实的输出的任务
  • 使用温度 0.7-1.0,进行创意写作
  • 核实事实——模型生成的是看似合理的文本,并不保证真实
  • 使用停止序列,精确控制输出长度
  • 较短的提示 → 输出更有创意,但控制力更弱
  • 详细的提示 → 输出受到更多约束,也更加聚焦
import anthropic

client = anthropic.Anthropic(api_key='sk-ant-your-key-here')

# Low temperature for factual classification
fact_response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=8,
    temperature=0,   # deterministic
    messages=[{'role': 'user', 'content': 'Is Paris the capital of France? Answer YES or NO only.'}]
)
print('Factual (temp=0):', fact_response.content[0].text.strip())

# Higher temperature for creative tasks
creative_response = client.messages.create(
    model='claude-opus-4-5',
    max_tokens=64,
    temperature=1.0,
    messages=[{'role': 'user', 'content': 'Write a surprising one-line poem about code.'}]
)
print('Creative (temp=1):', creative_response.content[0].text.strip())

知识检查

您已经了解 LLM 如何逐个词元生成文本。现在来检验您对温度的理解。

一名开发人员正在构建一个客服聊天机器人,它必须针对账单问题给出一致且准确的回答。哪种温度设置最合适?

人工智能如何生成回答——回顾

现在您已经了解每个人工智能回答背后的机制:

  • 模型一次预测一个下一个词元——这就是自回归生成
  • 温度控制词元选择中注入的随机程度
  • 核采样将采样限制在由高概率词元组成的核心集合中
  • 模型并不理解语言——它只是在极大规模上进行模式匹配
  • 知识在训练时被冻结——没有实时数据,也无法访问互联网
  • 停止序列让您可以精确控制输出结束的位置
免费开始

用 AI 导师学习 AI Prompt Engineering — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
53
课程
199

常见问题解答

「人工智能如何生成响应」课时是免费的吗?

是的 — 「人工智能如何生成响应」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Prompt Engineering 课程的其余内容,请升级到 CoddyKit PRO。 AI Prompt Engineering 课程共包含 4 节课。

「人工智能如何生成响应」这节课中我会学到什么?

了解令牌预测、概率,以及人工智能为何不会像人类一样“思考”。 你通过在浏览器中直接运行的动手代码来练习 AI Prompt Engineering,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Prompt Engineering 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Prompt Engineering 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「人工智能如何生成响应」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Prompt Engineering 课中编写并运行代码吗?

能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 理解聊天界面
  2. 人工智能可以处理的请求类型
  3. 人工智能如何生成响应
  4. 人工智能无法完成的事情
← 返回 AI Prompt Engineering