Max Tokens 与停止原因
本课属于 Coddy AI Engineering 学习旅程的“在代码中调用模型”单元。第 6 课,共 22 课。
max_tokens 是一个硬性限制。当回复达到该限制时,模型会在单词中间停止,并且 stop_reason 为 "max_tokens":
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=5,
messages=[{"role": "user", "content": "What is the largest planet?"}],
)
print(response.content[0].text)
print(response.stop_reason)这会输出 Jupiter is the larges 以及 max_tokens。模型在生成文本时并不知道限制,因此它绝不会为了适应限制而缩短回答。在信任文本之前请检查停止原因:可以显示警告,或者使用更高的限制再次请求。
stop_sequences 是一个提前结束回复的字符串列表。文本会在找到的第一个匹配项之前停止,stop_reason 为 "stop_sequence",且 stop_sequence 保存匹配到的字符串。当使用 stop_sequences=[","] 时,关于最高山峰的问题会返回 Mount Everest is the tallest mountain above sea level。
挑战
简单编写一个程序,检测回答何时被截断。
- 起始代码会将一个问题和 Token 数量限制读取到
limit中。 - 使用
model="claude-opus-5-5"和max_tokens=limit发送该问题。 - 打印
Answer:和回复文本,然后打印Stop:和停止原因。 - 仅当停止原因为
max_tokens时,打印Note: the answer was cut short.。
例如,对于输入 What is the capital of Japan? 和 4,程序输出:
Answer: The capital of
Stop: max_tokens
Note: the answer was cut short.当限制为 100 时,回答是完整的,停止原因为 end_turn,并且不会打印提示。
亲手试试
import coddy_ai as anthropic # 生产环境中:import anthropic
client = anthropic.Anthropic()
question = input()
limit = int(input())
# 发送问题并设置 max_tokens=limit,打印答案和停止原因,
# 并在答案被截断时打印提示信息
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
在代码中调用模型中的所有课
自己练习: Python 在线编译器