توفر فئة CostEstimator طريقة مريحة لتقدير تكلفة استخدام طرز GPT-3.5 و GPT-4 من Openai. يهدف إلى استخدامه في حلقة مع tqdm لتتبع وعرض تقدير التكلفة في الوقت الفعلي.
tqdm تعمل ويعرض تكلفة كل مكالمة API والتكلفة الإجمالية المتراكمة.تم تصميم فئة Costestimator لاستخدامها في دفاتر 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 )استدعاء واجهة برمجة التطبيقات من داخل حلقة :
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 الحقيقية ، سترى تكلفة الطلب الحالي وإجمالي الإنفاق حتى الآن. إنه يوفر طريقة مرئية وسهلة الاستخدام لمراقبة التكاليف.
ترخيص معهد ماساتشوستس للتكن يسمح بإعادة استخدام التعليمات البرمجية مع الحد الأدنى من القيود ، بينما تتطلب فقط الإسناد وإدراج الترخيص الأصلي. ؟