開始使用免費開始

設定權杖上限

一家電商平台剛聘請你來改善他們以 OpenAI API 建置的客服機器人效能。你決定先從避免輸入訊息造成速率限制問題著手,設定上限為 100 個權杖,並以一則範例輸入訊息進行測試。

已預先載入 tiktoken 函式庫。

本練習屬於課程

使用 OpenAI API 開發 AI 系統

檢視課程

練習說明

  • 使用 tiktoken 函式庫為 gpt-4o-mini 模型建立編碼。
  • 檢查輸入訊息的權杖數是否符合預期。
  • 若訊息通過兩項檢查,列印回應。

動手互動練習

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

client = OpenAI(api_key="")
input_message = {"role": "user", "content": "I'd like to buy a shirt and a jacket. Can you suggest two color pairings for these items?"}

# Use tiktoken to create the encoding for your model
encoding = tiktoken.____(____)
# Check for the number of tokens
num_tokens = ____

# Run the chat completions function and print the response
if num_tokens <= ____:
    response = client.chat.completions.create(model="gpt-4o-mini", messages=[input_message])
    print(____)
else:
    print("Message exceeds token limit")
編輯並執行程式碼