例外狀況處理
你在一家物流公司開發一個使用 OpenAI API 的應用程式,用來檢查你前三大客戶的送貨地址。這個應用程式將在內部使用,你希望在發生錯誤時,其他團隊能看到易讀的訊息。
為了達成這個需求,你決定在使用者未提供有效的驗證金鑰時,印出自訂訊息,並使用 try 與 except 區塊來處理。
變數 message 已經匯入。
本練習屬於課程
使用 OpenAI API 開發 AI 系統
練習說明
- 使用
try陳述式嘗試向 API 發出請求。 - 如果請求成功,印出回應。
- 使用
except陳述式處理可能發生的驗證錯誤。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
client = OpenAI(api_key="")
# Use the try statement
____:
response = ____(
model="gpt-4o-mini",
messages=[message]
)
# Print the response
print(response.____)
# Use the except statement
____:
print("Please double check your authentication key and try again, the one provided is not valid.")