読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
SDKの client.messages.stream を使うと、答えの文を、書かれた順に受け取れます。
def stream_reply(client, question):
with client.messages.stream(
model=model_main(),
max_tokens=800,
messages=[{"role": "user", "content": question}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
return stream.get_final_text()
| 部分 | 意味 |
|---|---|
stream.text_stream | 答えの文の断片が、順に取り出せる |
stream.get_final_text() | 最後まで受け取った後の、答えの文の全体 |
stream.get_final_message() | 最後まで受け取った後の、応答の全体(stop_reason や usage を含む) |
長い答えでも、最初の文がすぐに表示されるため、早紀は待たずに読み始められます。
14 / 20