開始使用免費開始

使用 tiktoken 估算嵌入向量成本

現在我們已經建立了資料庫與集合,用來儲存 Netflix 電影與影集,接下來就能開始製作嵌入向量(embedding)。

在為大型資料集建立嵌入向量前,先估算成本很重要,才能避免超出預算。因為 OpenAI 模型的計費依輸入的權杖(token)數量而定,我們會使用 OpenAI 的 tiktoken 函式庫來計算權杖數,並換算成美元成本。

你已拿到 documents,這是一個包含所有待嵌入資料的清單。你將迭代這個清單,編碼每個文件,並計算權杖總數。最後,你會根據模型的定價將其轉換為成本。

本練習屬於課程

Introduction to Embeddings with the OpenAI API

檢視課程

練習說明

  • 載入 text-embedding-3-small 模型的編碼器。
  • documents 中的每段文字進行編碼,將結果加總以得到此資料集的權杖總數 total_tokens
  • 使用已為你定義的模型 cost_per_1k_tokens,列印權杖總數與其成本。

動手互動練習

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

# Load the encoder for the OpenAI text-embedding-3-small model
enc = tiktoken.encoding_for_model("____")

# Encode each text in documents and calculate the total tokens
total_tokens = ____(____(____) for ____ in documents)

cost_per_1k_tokens = 0.00002

# Display number of tokens and cost
print('Total tokens:', ____)
print('Cost:', ____)
編輯並執行程式碼