Token
Token
The basic unit in which a large language model (LLM) processes text. Split into words, subwords, or characters, and a key concept that determines context window size and API usage cost.
Token
The basic unit in which a large language model (LLM) processes text. Split into words, subwords, or characters, and a key concept that determines context window size and API usage cost.
A token is the basic processing unit that a language model uses to understand and generate text. In English, 1 token corresponds to roughly 4 characters or 0.75 words. Because Korean is a morpheme-based language, it uses more tokens than English for the same content. "μλ νμΈμ" is split into 2-3 tokens in GPT-4.
There are several algorithms for tokenization. BPE (Byte Pair Encoding) is used in the GPT family and repeatedly merges the most frequent pairs of characters. WordPiece is used in BERT and is similar to BPE, but decides merges based on probability. SentencePiece provides language-independent tokenization and is used in LLaMA and others.
Tokens are a key cost factor in using LLMs. OpenAI GPT-4 Turbo charges $10 per 1M input tokens and $30 per 1M output tokens. Therefore, reducing the number of tokens through prompt optimization can significantly cut costs. In addition, the context window (e.g., 128K tokens for GPT-4) refers to the maximum number of tokens that can be processed at one time.
Token efficiency varies by model and language. English text is more token-efficient than Korean, and code uses more tokens than natural language. Special tokens (e.g., [CLS], [SEP], <|endoftext|>) are used by the model to understand sentence structure. To determine the token count accurately, you should use an official tokenizer such as tiktoken (OpenAI).
An example of checking the token count of a text with various tokenizers.
import tiktoken # OpenAI ν ν¬λμ΄μ
from transformers import AutoTokenizer # Hugging Face
# =============================================
# 1. OpenAI tiktoken (GPT-4, GPT-3.5 μ©)
# =============================================
# pip install tiktoken
# GPT-4 ν ν¬λμ΄μ λ‘λ
enc = tiktoken.encoding_for_model("gpt-4")
text_en = "Hello, how are you today?"
text_ko = "μλ
νμΈμ, μ€λ κΈ°λΆμ΄ μ΄λ μΈμ?"
code = "def hello(): return 'world'"
# ν ν°ν
tokens_en = enc.encode(text_en)
tokens_ko = enc.encode(text_ko)
tokens_code = enc.encode(code)
print(f"μμ΄ ν
μ€νΈ: {len(tokens_en)} ν ν°")
print(f"β ν ν° ID: {tokens_en}")
print(f"β ν ν°: {[enc.decode([t]) for t in tokens_en]}")
print()
print(f"νκ΅μ΄ ν
μ€νΈ: {len(tokens_ko)} ν ν°")
print(f"β ν ν°: {[enc.decode([t]) for t in tokens_ko]}")
print()
print(f"μ½λ: {len(tokens_code)} ν ν°")
# κ²°κ³Ό:
# μμ΄ ν
μ€νΈ: 7 ν ν°
# νκ΅μ΄ ν
μ€νΈ: 14 ν ν° (μμ΄λ³΄λ€ 2λ°° λ§μ)
# μ½λ: 9 ν ν°
# =============================================
# 2. Hugging Face Transformers
# =============================================
# pip install transformers
# LLaMA ν ν¬λμ΄μ (SentencePiece κΈ°λ°)
tokenizer_llama = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
# GPT-2 ν ν¬λμ΄μ (BPE κΈ°λ°)
tokenizer_gpt2 = AutoTokenizer.from_pretrained("gpt2")
# BERT ν ν¬λμ΄μ (WordPiece κΈ°λ°)
tokenizer_bert = AutoTokenizer.from_pretrained("bert-base-multilingual-cased")
text = "μΈκ³΅μ§λ₯μ΄ μΈμμ λ°κΎΈκ³ μμ΅λλ€."
for name, tokenizer in [
("LLaMA", tokenizer_llama),
("GPT-2", tokenizer_gpt2),
("BERT", tokenizer_bert)
]:
tokens = tokenizer.tokenize(text)
print(f"{name}: {len(tokens)} ν ν° β {tokens}")
# =============================================
# 3. ν ν° μ κΈ°λ° λΉμ© κ³μ°κΈ°
# =============================================
def estimate_cost(text: str, model: str = "gpt-4-turbo") -> dict:
"""OpenAI API λΉμ© μΆμ """
enc = tiktoken.encoding_for_model(model)
token_count = len(enc.encode(text))
# 2025λ
1μ κΈ°μ€ κ°κ²© ($ per 1M tokens)
prices = {
"gpt-4-turbo": {"input": 10.0, "output": 30.0},
"gpt-4o": {"input": 5.0, "output": 15.0},
"gpt-4o-mini": {"input": 0.15, "output": 0.60},
"gpt-3.5-turbo": {"input": 0.50, "output": 1.50}
}
price = prices.get(model, prices["gpt-4-turbo"])
input_cost = (token_count / 1_000_000) * price["input"]
return {
"model": model,
"tokens": token_count,
"input_cost_usd": round(input_cost, 6),
"per_1k_tokens": round(price["input"] / 1000, 6)
}
# μ¬μ© μμ
long_text = "λνλ―Όκ΅μ λμμμμ μμΉν κ΅κ°λ‘..." * 100
result = estimate_cost(long_text, "gpt-4o-mini")
print(f"ν ν° μ: {result['tokens']}, μμ λΉμ©: ${result['input_cost_usd']}")
"This prompt has over 8,000 tokens, so the context window is almost full"
β Explains that the prompt is close to the model's maximum token limit
"Korean has low token efficiency, so it costs about twice as much as English"
β Explains the cost increase caused by the tokenization characteristics of Korean
"Check the token count with tiktoken first, then send the request"
β Recommends checking the token count in advance before an API call
Estimating token count from word count
Token != word. Long or rare words are split into multiple tokens. The exact token count must be verified with a tokenizer.
Confusing input/output token prices
In most APIs, output tokens cost 2-3 times more than input tokens. Set max_tokens appropriately to manage costs.
Exceeding the context window
An error occurs if the sum of input + output tokens exceeds the context window. You must reserve space for the output in advance.
Special characters and emoji
Emoji and special characters can take up more tokens than expected. In cost-sensitive services, reduce the use of special characters.