流式响应
本课属于 Coddy AI Engineering 学习旅程的“在代码中调用模型”单元。第 9 课,共 22 课。
生成一个长回答可能需要好几秒钟。使用 create 时,你的程序需要等待所有内容生成完毕。而使用流式传输,文本会在模型生成时分小块到达,因此聊天窗口可以立即显示出文字。
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=200,
messages=[{"role": "user", "content": "What is the largest ocean?"}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
message = stream.get_final_message()
print()
print(message.stop_reason)client.messages.stream 接收与 create 相同的参数,并在 with 块中使用。stream.text_stream 会生成文本片段。print(text, end="", flush=True) 可以将它们保持在同一行并立即显示每个片段。循环结束后,stream.get_final_message() 会返回完整的 Message,其中包含它的 stop_reason 和 usage。对于设置了较大 max_tokens 的请求,流式传输也是更安全的选择,因为单次等待调用可能会耗时过长。这里的替代实现每个片段生成一个 token,而实际片段通常会更长。
挑战
中等流式传输回答并汇报相关信息。初始代码会读取输入的问题。
- 打印
Answer:且不换行(end="")。 - 使用
model="claude-opus-5-5"和max_tokens=200流式传输回复。在同一行打印每段文本并统计块数。 - 流式传输结束后,获取最终消息,并打印一个空行以结束回答所在行。
- 打印
Chunks:以及块数,Stop:以及停止原因,Output tokens:以及输出 token 数量。
例如,对于输入 What is the capital of France?,程序输出:
Answer: The capital of France is Paris.
Chunks: 8
Stop: end_turn
Output tokens: 8亲手试试
import coddy_ai as anthropic # 在生产环境中:import anthropic
client = anthropic.Anthropic()
question = input()
# 在 "Answer: " 之后流式输出答案,然后打印 chunk 数量、
# 最终消息的停止原因和输出 token 数量
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
在代码中调用模型中的所有课
自己练习: Python 在线编译器