開始使用免費開始

串流 OpenAI 回應

你正在打造一個能即時產生食譜的烹飪助理應用。OpenAI 用戶端已為你初始化並完成設定。你將使用 Responses API 串流產生食譜,並在文字到達時即時顯示,打造動態的使用者體驗。

本練習屬於課程

使用 OpenAI Responses API

檢視課程

練習說明

  • 使用 client.responses.create()、模型 "gpt-5.4-mini",以及提供的提示詞,開啟「串流」情境。
  • 迴圈遍歷串流事件,檢查事件型別是否為 "response.output_text.delta";若是,將 event.delta 接到 current_text 後並印出累積的文字。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

prompt = "List the core ingredients to make classic egg pasta pasta in a single line."

# Open a connection for a streaming request
____ client.responses.create(model="gpt-5.4-mini", input=____, ____=____) as stream:
    current_text = ""

    # Complete the output text streaming
    for event in stream:
        if event.type == "____":
            current_text += ____
            print(current_text)
編輯並執行程式碼