以語意事件進行串流
你正在建立一個能提供即時天氣預報的助理。OpenAI 用戶端已初始化並設定為可搭配 Responses API 使用。你將串流語意事件,以追蹤回應開始的時間、每個文字區塊完成的時間,以及完整回應完成的時間。這能在模型生成預報的同時顯示進度,提供更具互動性的使用者體驗。
本練習屬於課程
使用 OpenAI Responses API
練習說明
- 處理
"response.created"事件,印出啟動訊息。 - 處理
"response.output_text.done"事件,印出區塊完成的訊息。 - 處理
"response.completed"事件,印出儲存在current_text的完整回應文字。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
prompt = "Explain how to read a weather forecast in one sentence for a beginner hiker."
with client.responses.create(model="gpt-5.4-mini", input=prompt, stream=True) as stream:
for event in stream:
# Find response created events
if event.type == "____":
print("Forecast generation started...\n")
# Find output text completed events
elif event.type == "____":
print("\n--- Forecast complete ---\n")
# Find response completed events
elif event.type == "____":
print(f"\nFull forecast:\n{current_text}")