以語意事件進行串流

使用 OpenAI Responses API

James Chapman

AI Curriculum Manager, DataCamp

為什麼要串流?

串流關閉示意

使用 OpenAI Responses API

為什麼要串流?

串流開啟示意

使用 OpenAI Responses API

語意事件

  • 用結構化更新描述正在發生的事
使用 OpenAI Responses API

語意事件

  • 用結構化更新描述正在發生的事
事件類型 說明
response.created 模型開始產生
response.output_text.delta 文字增量更新
response.output_text.done 文字區塊完成
response.function_call.arguments.delta 工具引數串流
response.completed 整個回應已完成
使用 OpenAI Responses API

範例:基本文字串流

prompt = "Explain the seasons of the year concisely to a child."

with client.responses.create(model="gpt-5.4-mini", input=prompt, stream=True) as stream:
current_text = ""
for event in stream: if event.type == "response.output_text.delta":
current_text += event.delta print(current_text)
使用 OpenAI Responses API

範例:基本文字串流

文字串流示意

使用 OpenAI Responses API

範例:處理多種事件

prompt = "Explain how a neural network learns concisely for a child."

with client.responses.create(model="gpt-5.4-mini", input=prompt, stream=True) as stream:

for event in stream: if event.type == "response.created":
print("Response started...\n")
elif event.type == "response.output_text.done":
print("\n\n--- Text block finished ---\n")
elif event.type == "response.completed":
print(f"\nFull response:\n{current_text}")
使用 OpenAI Responses API

範例:處理多種事件

多事件處理示意

使用 OpenAI Responses API

範例:工具事件串流

convert_currency() -> str:

  • date_time: str
  • from_timezone: str
  • to_timezone: str
tools = [
    {
        "type": "function",
        "name": "convert_currency",
        ...
     }
]

Frankfurter 標誌

使用 OpenAI Responses API

範例:工具事件串流

prompt = "How much is 120 euros in British pounds using the current exchange rate?"

with client.responses.create(model="gpt-5.4-mini", input=prompt, tools=tools, stream=True) as stream:
current_args = ""
for event in stream: if event.type == "response.function_call_arguments.delta":
current_args += event.delta print("Streaming args:", current_args)
elif event.type == "response.function_call_arguments.done":
print("\nFinal arguments:", event.arguments)
elif event.type == "response.completed":
print("\n--- Completed ---")
使用 OpenAI Responses API

範例:工具事件串流

工具事件串流示意

使用 OpenAI Responses API

重點整理

ChatGPT 語意事件示意

1 ChatGPT 中的語意事件應用
使用 OpenAI Responses API

一起來練習吧!

使用 OpenAI Responses API

Preparing Video For Download...