คลาส 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 )เรียก 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 : ใช้เพื่อกำหนดจำนวนโทเค็นในสตริงโดยไม่ต้องโทร APIopenai : ไคลเอนต์ Openai Python อย่างเป็นทางการtqdm : จัดเตรียมแถบความคืบหน้าแบบเรียลไทม์ที่แสดงรายละเอียดต้นทุน จำเป็นสำหรับการติดตามต้นทุนที่ใช้งานง่ายlorem_text : สร้างการตอบสนอง Mock API ติดตั้งผ่าน PIP
pip install gpt-cost-estimatorการติดตั้งด้วยตนเอง
pip install tiktoken openai tqdm lorem_text โคลนที่เก็บนี้และนำเข้า CostEstimator ในสคริปต์ของคุณ
แถบความคืบหน้าขับเคลื่อนโดย tqdm ให้ข้อเสนอแนะทันทีสำหรับการโทร API ทุกครั้ง ไม่ว่าคุณจะเยาะเย้ยการโทรหรือเชื่อมต่อกับ API จริงคุณจะเห็นค่าใช้จ่ายของคำขอปัจจุบันและค่าใช้จ่ายทั้งหมด มันมีวิธีที่มองเห็นและใช้งานง่ายในการตรวจสอบค่าใช้จ่าย
ใบอนุญาต MIT เป็นใบอนุญาตโอเพนซอร์ซที่อนุญาต ช่วยให้สามารถนำรหัสกลับมาใช้ใหม่ได้โดยมีข้อ จำกัด น้อยที่สุดในขณะที่ต้องการเพียงการระบุแหล่งที่มาและการรวมใบอนุญาตเดิม -