gpt cost estimator
verride, Updated Prices
CostEstimator類提供了一種方便的方式來估計使用OpenAI的GPT-3.5和GPT-4型號的成本。它旨在在帶有tqdm的循環中用於實時跟踪和顯示成本估計。
tqdm驅動的循環中,並顯示每個API調用的成本和累積的總成本。Costimimator類旨在用於Jupyter筆記本電腦中,請參閱示例筆記本以進行演示。
裝飾您的API呼叫功能:
import openai
from gpt_cost_estimator import CostEstimator
@ CostEstimator ()
def query_openai ( model , messages , ** kwargs ):
args_to_remove = [ 'mock' , 'completion_tokens' ]
for arg in args_to_remove :
if arg in kwargs :
del kwargs [ arg ]
return openai . ChatCompletion . create (
model = model ,
messages = messages ,
** kwargs )從循環中調用API :
for message in tqdm ( messages ):
response = query_openai ( model = "gpt-3.5-turbo-0613" , messages = [ message ], mock = False )
# Or if you're mocking the API call:
response = query_openai ( model = "gpt-3.5-turbo-0613" , messages = [ message ], mock = True )
print () # We need to print a newline to show the total cost重置總成本:
CostEstimator . reset ()閱讀總成本:
CostEstimator . get_total_cost ()**新價格覆蓋**
from cost_estimator import CostEstimator
# Define custom prices for models
custom_prices = {
"gpt-4o-mini" : { "input" : 0.0002 , "output" : 0.0007 },
}
# Instantiate the CostEstimator with custom prices
estimator = CostEstimator ( price_overrides = custom_prices )
# Use the estimator as usual
@ estimator
def query_openai ( model , messages , ** kwargs ):
args_to_remove = [ 'mock' , 'completion_tokens' ]
for arg in args_to_remove :
if arg in kwargs :
del kwargs [ arg ]
return openai . ChatCompletion . create (
model = model ,
messages = messages ,
** kwargs )tiktoken :用於確定字符串中的令牌數,而無需進行API調用。openai :官方Openai Python客戶。tqdm :提供顯示成本細節的實時進度欄。對於用戶友好的成本跟踪至關重要。lorem_text :生成模擬API響應。 通過PIP安裝
pip install gpt-cost-estimator手動安裝
pip install tiktoken openai tqdm lorem_text克隆此存儲庫,並在您的腳本中導入CostEstimator 。
由tqdm提供動力的進度條為每個API調用提供即時反饋。無論您是嘲笑通話還是連接到真正的API,您都會看到當前請求的成本和到目前為止的總支出。它提供了一種視覺和用戶友好的方式來監視成本。
麻省理工學院許可證是允許的開源許可證。它允許使用最小限制的代碼重複使用,同時僅需要歸因和包含原始許可證。 ?