为您的使用场景选择参数
针对事实问答、创意写作、代码和聊天的推荐设置。
为您的使用场景选择参数 是 CoddyKit 上的免费 AI Prompt Engineering 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Prompt Engineering 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Prompt Engineering 课程共包含 4 节课。
参数决策框架
选择采样参数并不是靠猜测——它遵循一套基于任务要求的逻辑。两个关键维度决定了合适的配置:
- 输出准确性:输出正确且可预测有多重要?
- 输出多样性:输出有所变化并进行探索有多重要?
高准确性 → 低温度。高多样性 → 高温度。大多数任务都处于这两个极端之间的某个位置。
事实性问答:准确性至关重要
对于事实性问答,通常只有一个正确答案。任何随机性都会增加回答错误的可能性。请使用:
- 温度 = 0:贪心解码,完全确定
- top-p = 1.0:不加限制;在温度=0 时,top-p 不会产生任何影响
这样可以确保模型始终选择它最有把握的答案,而这通常也是最可能正确的答案。
import openai
client = openai.OpenAI(api_key='sk-...')
# Factual Q&A configuration
def factual_qa(question):
resp = client.chat.completions.create(
model='gpt-4o',
messages=[
{'role': 'system', 'content': 'Answer factual questions concisely and accurately.'},
{'role': 'user', 'content': question}
],
temperature=0,
top_p=1.0
)
return resp.choices[0].message.content
answer = factual_qa('What is the boiling point of water at sea level?')
print(answer) # Always: '100 degrees Celsius (212 degrees Fahrenheit).'代码生成:接近贪心解码
代码必须在语法上正确、在语义上精确。随机性会导致语法错误、变量名错误或逻辑错误。请使用:
- 温度 = 0–0.2:几乎采用贪心解码——允许细微变化,但会强烈偏好正确的词元选择
- top-p = 0.95:排除可能导致语法错误的极低概率尾部词元
# Code generation configuration
def generate_code(task):
resp = client.chat.completions.create(
model='gpt-4o',
messages=[
{'role': 'system', 'content': 'You are an expert Python programmer. Write clean, correct code.'},
{'role': 'user', 'content': task}
],
temperature=0.1,
top_p=0.95
)
return resp.choices[0].message.content
code = generate_code('Write a Python function that merges two sorted lists.')
print(code)摘要:适中的设置
摘要需要准确性(不要歪曲事实),但适度的变化也有好处(不同运行结果可以强调不同方面)。请使用:
- 温度 = 0.3–0.5:轻微的随机性能够保持自然的措辞
- top-p = 1.0:在低温度下无需限制核心集合
# Summarization configuration
def summarize(text):
resp = client.chat.completions.create(
model='gpt-4o',
messages=[
{'role': 'system', 'content': 'Summarize the following text in 3 sentences.'},
{'role': 'user', 'content': text}
],
temperature=0.4,
top_p=1.0
)
return resp.choices[0].message.content
summary = summarize(long_article)
print(summary)对话聊天:自然变化
聊天响应得益于自然的变化——同一个问题不应总是产生完全相同的措辞。随机性过大会使响应缺乏连贯性。请使用:
- 温度 = 0.7–0.9:自然且多变的对话
- top-p = 0.9–0.95:排除会产生不自然措辞的低概率尾部词元
# Chat configuration
def chat_response(user_message, history):
messages = history + [{'role': 'user', 'content': user_message}]
resp = client.chat.completions.create(
model='gpt-4o',
messages=[
{'role': 'system', 'content': 'You are a friendly, helpful assistant.'},
*messages
],
temperature=0.8,
top_p=0.9
)
reply = resp.choices[0].message.content
history.append({'role': 'user', 'content': user_message})
history.append({'role': 'assistant', 'content': reply})
return reply, history创意写作:高多样性
创意写作重视原创性和出人意料的效果。低温度会产生陈词滥调且可预测的输出。高温度会带来生动、出人意料的选择——但温度过高会导致内容缺乏连贯性。请使用:
- 温度 = 0.9–1.2:多样的词汇和不明显的用词选择
- top-p = 0.95:防止出现缺乏连贯性的尾部词元,同时允许广泛探索
# Creative writing configuration
def write_story_opening(prompt):
resp = client.chat.completions.create(
model='gpt-4o',
messages=[
{'role': 'system', 'content': 'You are a creative fiction writer. Write vivid, original prose.'},
{'role': 'user', 'content': f'Write a story opening for: {prompt}'}
],
temperature=1.1,
top_p=0.95
)
return resp.choices[0].message.content
opening = write_story_opening('A detective discovers her partner is the killer.')
print(opening)头脑风暴与构思
对于头脑风暴,目标是让想法尽可能多样——即使其中有些不寻常或出人意料。请使用实际可行的最高温度:
- 温度 = 1.0–1.5:广泛探索想法空间
- top-p = 0.95–1.0:只施加极少限制
多次运行并收集所有输出,然后手动筛选出最好的想法。头脑风暴提示受益于明确要求多样化,例如:“请给出 10 种不同的方法,其中包括不寻常的方法。”
# Brainstorming: run multiple times for variety
def brainstorm(topic, n_runs=5):
ideas = []
for _ in range(n_runs):
resp = client.chat.completions.create(
model='gpt-4o',
messages=[
{'role': 'system', 'content': 'Generate creative, diverse ideas. Include unusual approaches.'},
{'role': 'user', 'content': f'Give me 3 ideas for: {topic}'}
],
temperature=1.3,
top_p=0.95
)
ideas.append(resp.choices[0].message.content)
return ideas
all_ideas = brainstorm('reducing customer churn')参数敏感性测试
在确定参数之前,请运行参数敏感性测试:保持提示不变,每次只改变一个参数,并评估每种设置下的输出质量。
def sensitivity_test(prompt, evaluator, temperatures, n_samples=5):
results = {}
for temp in temperatures:
scores = []
for _ in range(n_samples):
resp = client.chat.completions.create(
model='gpt-4o',
messages=[{'role': 'user', 'content': prompt}],
temperature=temp
)
score = evaluator(resp.choices[0].message.content)
scores.append(score)
results[temp] = sum(scores) / len(scores)
for temp, score in sorted(results.items()):
print(f'T={temp}: avg score = {score:.2f}')
best_temp = max(results, key=results.get)
print(f'Best temperature: {best_temp}')
return best_temp何时保留默认值
并非每个应用都需要自定义参数。出现以下情况时,请保留默认值:
- 使用场景是一般聊天——默认温度(大多数 API 为 1.0)已经过良好调校
- 您正在进行原型设计,还不知道合适的设置
- 任务在准确性和创意之间保持平衡(例如起草电子邮件)
经验法则:只有当默认行为在测试中造成了可测量的质量问题时,才自定义参数。过早调优参数会增加复杂性,却没有可测量的收益。
# Defaults are often correct
default_resp = client.chat.completions.create(
model='gpt-4o',
messages=[{'role': 'user', 'content': 'Draft a professional email declining a meeting.'}]
# No temperature or top_p specified — API defaults apply
# OpenAI default: temperature=1, top_p=1
)
print(default_resp.choices[0].message.content)快速参考卡
按使用场景列出的推荐设置汇总表:
PARAMETER_PRESETS = {
# task: (temperature, top_p, notes)
'factual_qa': (0.0, 1.0, 'greedy, max accuracy'),
'classification': (0.0, 1.0, 'deterministic labels'),
'code_generation': (0.1, 0.95, 'near-greedy, avoid tail tokens'),
'data_extraction': (0.2, 1.0, 'slight variation for robustness'),
'summarization': (0.4, 1.0, 'preserve facts, vary phrasing'),
'translation': (0.3, 1.0, 'accurate but natural'),
'chat': (0.8, 0.9, 'natural conversation'),
'email_drafting': (0.7, 0.9, 'professional but varied'),
'creative_writing': (1.1, 0.95, 'vivid, original'),
'brainstorming': (1.3, 0.95, 'maximum diversity'),
}
for task, (temp, top_p, notes) in PARAMETER_PRESETS.items():
print(f'{task:22} temp={temp}, top_p={top_p} | {notes}')频率惩罚与存在惩罚
另外两个参数可以补充温度和 top-p:
- 频率惩罚(0–2):根据词元在当前输出中已经出现的次数按比例降低其概率——防止词语重复
- 存在惩罚(0–2):只要某个词元出现过,就降低其概率——鼓励主题多样性
对于创意写作:添加频率惩罚=0.5,以减少重复用词,同时不改变温度。
resp = client.chat.completions.create(
model='gpt-4o',
messages=[{'role': 'user', 'content': 'Write a paragraph about coffee.'}],
temperature=1.0,
top_p=0.95,
frequency_penalty=0.5, # discourage repeating the same words
presence_penalty=0.3 # encourage introducing new topics/aspects
)
print(resp.choices[0].message.content)知识检查
对于生成将在生产环境中执行的 Python 代码的任务,哪种参数配置最合适?
回顾:选择采样参数
根据您对准确性和多样性的需求匹配参数:
- 事实性内容/代码:温度=0–0.2,top-p=0.95——准确性优先
- 摘要:温度=0.3–0.5——保持平衡
- 聊天:温度=0.7–0.9,top-p=0.9——自然变化
- 创意内容:温度=0.9–1.2,top-p=0.95——多样性
- 头脑风暴:温度=1.3,top-p=0.95——最大程度地探索
请运行参数敏感性测试。如果没有观察到质量问题,请保留默认值。如果存在重复问题,请添加频率惩罚。本课程 19 到此结束。下一部分:提示测试与回归。
用 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 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「为您的使用场景选择参数」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Prompt Engineering 课中编写并运行代码吗?
能。每节 AI Prompt Engineering 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- LLM 中的温度是什么?
- Top-p 核采样
- Top-k 采样
- 为您的使用场景选择参数