TokenCost 설치 — PyPI 패키지 정보

TokenCost 설치

TokenCost는 PyPI에서 간단히 설치할 수 있는 파이썬 패키지예요. 설치 후 calculate_prompt_cost·count_message_tokens 같은 함수로 비용·토큰을 바로 계산할 수 있습니다.

출처: https://pypi.org/project/tokencost/

설치

pip install tokencost

사용 예시

OpenAI 요청의 프롬프트·완성 비용을 계산해요.

from openai import OpenAI

client = OpenAI()
model = "gpt-3.5-turbo"
prompt = [{"role": "user", "content": "Say this is a test"}]
chat_completion = client.chat.completions.create(messages=prompt, model=model)
completion = chat_completion.choices[0].message.content

prompt_cost = calculate_prompt_cost(prompt, model)
completion_cost = calculate_completion_cost(completion, model)
print(f"{prompt_cost} + {completion_cost} = {prompt_cost + completion_cost}")

토큰 카운팅

from tokencost import count_message_tokens, count_string_tokens

message_prompt = [{"role": "user", "content": "Hello world"}]
print(count_message_tokens(message_prompt, model="gpt-3.5-turbo"))  # 9

print(count_string_tokens(prompt="Hello world", model="gpt-3.5-turbo"))  # 2

더 알아보기