使用函式呼叫的串流
你已經看過具備函式呼叫能力的 LLM 如何解鎖許多應用情境,而且它們有各自的事件類型。當模型正準備呼叫工具時,這能即時回饋給使用者,或用於記錄以追蹤工具使用情況,非常實用。
先前你定義了 convert_timezone() 函式,用來在時區之間轉換日期時間;此外,我們也為你準備了 Responses API 所需的 tools 清單,其中包含該函式的定義。
本練習屬於課程
使用 OpenAI Responses API
練習說明
- 透過呼叫
client.responses.create()完成 串流(streaming) 情境管理器,並傳入模型"gpt-5.4-mini"、prompt與tools清單。 - 在回圈內,檢查是否為
"function_call_arguments.delta"事件。 - 加入條件以檢查
"function_call_arguments.done"事件。 - 最後加入條件,當事件類型為
"response.completed"時,印出最終完成訊息。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
prompt = "What time is 2:30pm on January 20th in New York in Tokyo time?"
# Open the streaming connection and enable tool-calling
with ____ as stream:
for event in stream:
# Filter for function call arguments delta events
if ____:
print(f"\nTool args streaming: {event.delta}")
# Filter for function call arguments complete events
elif ____:
print("Tool call args complete.")
# Filter for response completed events
elif ____:
print("\n--- Completed ---")