C.W.K.
Stream
Lesson 03 of 08 · published

Token Economics

~22 min · tokens, cost, tiktoken

Level 0Tokenizer
0 XP0/54 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

OpenAI 는 character 단위가 아니라 token 단위로 과금해. 영어 평균 ~4 char/token, 한국어/일본어는 더 hot 하게 — 1000-character 한글 프롬프트가 600+ token 나올 수 있어 (영어 감각으로 어림한 길이의 약 2배).

실전 함의

Multi-lingual 앱은 같은 동작이 언어별로 cost 가 크게 달라져. 언어별로 budget 잡거나, prompt caching 으로 system-prompt 부분을 amortize 하는 게 답이야. tiktoken 으로 미리 측정해 — 'eyeball 로 짧아 보이는데 왜 비싸지?' 디버깅에 쓰이는 토큰이 더 비쌈.

Vision 토큰은 측정 아니라 계산

Image input 토큰은 image 의 dimension 과 detail level 에서 도출돼. detail='low' 는 flat 85 token, detail='high' 는 32×32 patch grid — image 가 클수록 토큰이 폭증. 채팅 history 에 high-detail vision 끼어 있으면 cost 가 빠르게 터져.

Prefix 캐시 챙겨

OpenAI prompt caching 은 cached prefix 토큰 (≥1024 토큰) 에 50% 할인을 줘. Stable system 지시 + few-shot 을 앞에 두고 가변 user input 을 뒤에 둬. 그러면 캐시 히트가 prefix 내내 살아.

Code

tiktoken 으로 토큰 카운트·python
import tiktoken

# Get encoding for a model
enc = tiktoken.encoding_for_model("gpt-4o")

# Or by encoding name directly
enc = tiktoken.get_encoding("o200k_base")

# Count tokens
text = "Hello, how are you today?"
tokens = enc.encode(text)
print(f"Token count: {len(tokens)}")  # → 6
Cost 추정 헬퍼·python
import tiktoken

def count_tokens_for_messages(messages: list[dict], model: str = "gpt-4o") -> int:
    """
    Approximate token count for a list of chat messages.
    Each message incurs a ~4-token overhead; each reply starts with 3 tokens.
    """
    enc = tiktoken.encoding_for_model(model)
    tokens_per_message = 3
    tokens_per_name = 1

    total = 0
    for msg in messages:
        total += tokens_per_message
        for key, value in msg.items():
            total += len(enc.encode(str(value)))
            if key == "name":
                total += tokens_per_name
    total += 3  # every reply is primed with <|start|>assistant<|message|>
    return total

messages = [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "What is the capital of France?"},
]
print(count_tokens_for_messages(messages))  # → ~26 tokens

External links

Exercise

파일 경로 받아서 (1) input token 수, (2) gpt-4.1 가격으로 input cost 추정, (3) prompt-cache 80% 히트 시 절약액 — 셋 다 출력하는 작은 CLI 짜. tiktoken 의 get_encoding('o200k_base') 사용.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.