開始使用免費開始

用重試機制避免觸發速率限制

你已建立一個使用自訂訊息來執行 Chat Completions 的函式,但發現有時會因為速率限制而失敗。你決定使用 tenacity 函式庫的 @retry 裝飾器,在可行時避免錯誤。

本練習屬於課程

使用 OpenAI API 開發 AI 系統

檢視課程

練習說明

  • 匯入 tenacity 函式庫中需要的函式:retrywait_random_exponentialstop_after_attempt
  • 建立一個 OpenAI API 用戶端。
  • 完成重試裝飾器,設定從 5 秒開始重試,最高到 40 秒,並在嘗試 4 次後停止。

如果練習逾時,請確認你的間隔與嘗試次數與上面指定的數值完全相符。

動手互動練習

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

# Import the tenacity library
from ____ import ____

client = OpenAI(api_key="")

# Add the appropriate parameters to the decorator
@retry(____, ____)
def get_response(model, message):
    response = client.chat.completions.create(
      model=model,
      messages=[message]
    )
    return response.choices[0].message.content
print(get_response("gpt-4o-mini", {"role": "user", "content": "List ten holiday destinations."}))
編輯並執行程式碼