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,您都会看到当前请求的成本和到目前为止的总支出。它提供了一种视觉和用户友好的方式来监视成本。
麻省理工学院许可证是允许的开源许可证。它允许使用最小限制的代码重复使用,同时仅需要归因和包含原始许可证。 ?