读取响应
本课属于 Coddy AI Engineering 学习旅程的“在代码中调用模型”单元。第 4 课,共 22 课。
回复是一个 Message 对象。它的 content 是一个块列表,每个块都有一个 type。"text" 块在 .text 中保存答案。当模型先进行思考时,其前面会出现一个 "thinking" 块,因此读取 content[0].text 的代码会报错。请改为根据类型来查找对应的块:
for block in response.content:
if block.type == "text":
print(block.text)
print(response.stop_reason)
print(response.usage.input_tokens, response.usage.output_tokens)对于 What is the capital of Canada?,这会打印出答案,接着是 end_turn,然后是 15 8。
stop_reason 说明了模型停止的原因:"end_turn" 表示它自己完成了生成。usage 统计了你发送的 token 数量(input_tokens)和它生成的 token 数量(output_tokens),这也是你计费的依据。model 和 id 指明了模型和请求,这在你记录调用日志时很有帮助。
挑战
简单打印程序从回复中需要的全部内容。起始代码已经以高 effort 发送了问题,因此模型会先进行思考。
- 打印
Blocks:以及response.content中每个块的类型,并用逗号和空格分隔。 - 打印
Answer:以及文本块的文本内容。 - 打印
Stop:以及停止原因。 - 使用来自
usage的两个计数打印Tokens: <input> in, <output> out。
例如,对于输入 What is the capital of Egypt?,程序会打印:
Blocks: thinking, text
Answer: The capital of Egypt is Cairo.
Stop: end_turn
Tokens: 15 in, 72 out亲手试试
import coddy_ai as anthropic # 在生产环境中:import anthropic
client = anthropic.Anthropic()
question = input()
# 高 effort 会让模型在回答前先思考(下一章会解释 effort)
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=300,
output_config={"effort": "high"},
messages=[{"role": "user", "content": question}],
)
# 打印块类型、答案、停止原因和 token 数量
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
在代码中调用模型中的所有课
自己练习: Python 在线编译器