Ver5.0 ๐งฎ ํ์ด์ฌ์ผ๋ก ํ ํฐ ๊ธธ์ด ์๋ ๊ณ์ฐ๊ธฐ ๊ฐ๋ฐํ๊ธฐ: tiktoken๋ถํฐ ๋น์ฉ ์ถ์ ยท์ฒญํฌ ๋ถํ ๊น์ง

๐งฎ ํ์ด์ฌ์ผ๋ก ํ ํฐ ๊ธธ์ด ์๋ ๊ณ์ฐ๊ธฐ ๊ฐ๋ฐํ๊ธฐ: tiktoken๋ถํฐ ๋น์ฉ ์ถ์ ยท์ฒญํฌ ๋ถํ ๊น์ง
"๊ธ์ ์ 3,000์๋ฉด ๋ช ํ ํฐ์ด์ผ?" ์ด ์ง๋ฌธ์ ๋งค๋ฒ ๊ฐ์ผ๋ก ๋๋ตํ๊ณ ์์๋ค๋ฉด, ์ค๋ ๊ทธ ๊ฐ์ ์ฝ๋๋ก ๋ฐ๊ฟ๋ด ์๋ค. ํ์ด์ฌ ๋ช์ญ ์ค๋ก ์์ํด์ ์ค์ ์์ ์ธ ์ ์๋ ํ ํฐ ๊ณ์ฐ๊ธฐ๊น์ง ๊ฐ์ด ๋ง๋ค์ด ๋ณผ๊ฒ์. ๐ต
โป ๊ทธ๋ฆผ ์ ํ ํฐ ID๋ ์ค๋ช ์ฉ ์์์์. ์ค์ ๊ฐ์ ์ธ์ฝ๋ฉ๋ง๋ค ๋ค๋ฆ ๋๋ค.
1. ์ ํํ "ํ ํฐ"์ ์ธ์ผ ํ ๊น? ๐ค
LLM(๋๊ท๋ชจ ์ธ์ด ๋ชจ๋ธ)์ ์ฐ๋ฆฌ๊ฐ ๋ณด๋ด๋ ๊ธ์ ๊ธ์ ๋จ์๋ก ์ฝ์ง ์์์. ๋จผ์ ํ ํฌ๋์ด์ ๊ฐ ๋ฌธ์ฅ์ ์๊ฒ ์ชผ๊ฐ ์ ์ ID ๋ฐฐ์ด๋ก ๋ฐ๊พธ๊ณ , ๋ชจ๋ธ์ ๊ทธ ์ซ์ ๋ฐฐ์ด์ ์ฒ๋ฆฌํฉ๋๋ค. ๊ทธ๋์ API ์๊ธ, ์ปจํ ์คํธ ์๋์ฐ(ํ ๋ฒ์ ๋ฃ์ ์ ์๋ ๊ธธ์ด), ์ถ๋ ฅ ๊ธธ์ด ์ ํ์ด ์ ๋ถ ๊ธ์ ์๊ฐ ์๋๋ผ ํ ํฐ ์ ๊ธฐ์ค์ผ๋ก ์ ํด์ ธ ์์ด์.
๋ฌธ์ ๋ "๊ธ์ ์ รท ๋ช" ๊ฐ์ ์ด๋ฆผ์ ์ด ์ธ์ด๋ง๋ค, ๋ชจ๋ธ๋ง๋ค, ์ฌ์ง์ด ๊ฐ์ ๋ชจ๋ธ์ ๋ฒ์ ๋ง๋ค ๋ค๋ฅด๊ฒ ํ๋ฆฐ๋ค๋ ์ ์ด์์. ์์ด ๋ฌธ์ฅ์ ๋์ฒด๋ก ๋จ์ด ํ๋๊ฐ ํ ํฐ ํ๋ ๊ฐ๋ก ๋๋์ง๋ง, ํ๊ตญ์ด๋ ๊ฐ์ ์๋ฏธ๋ฅผ ํํํ ๋ ํ ํฐ์ด ๋ ๋ง์ด ๋์ค๋ ๊ฒฝํฅ์ด ์๊ณ , ์ฝ๋ยทURLยท์ด๋ชจ์ง๋ ๋ ๋ค๋ฅธ ํจํด์ ๋ณด์ ๋๋ค. ๊ฒฐ๊ตญ ์ ํํ ๊ฐ์ด ํ์ํ๋ฉด ํด๋น ๋ชจ๋ธ์ ํ ํฌ๋์ด์ ๋ก ์ง์ ์ธ๋ ๊ฒ ์ ์ผํ ์ ๋ต์ด์์.
2. ํ ํฌ๋์ด์ ๋ ๋ฌธ์ฅ์ ์ด๋ป๊ฒ ์๋ฅผ๊น? (BPE ํ ์ ๋ง๋ณด๊ธฐ) ๐ฐ
์์ฆ GPT ๊ณ์ด์ ๋น๋กฏํ ๋ง์ ๋ชจ๋ธ์ด ์ฐ๋ ๋ฐฉ์์ BPE(Byte Pair Encoding) ๊ณ์ด์ด์์. ์๋ฆฌ๋ ์๊ฐ๋ณด๋ค ๋จ์ํฉ๋๋ค.
์ฌ๊ธฐ์ ์ค์ํ ํฌ์ธํธ! ๋ณํฉ ๊ท์น์ ํ์ต ๋ฐ์ดํฐ์ ๋น๋๋ก ๋ง๋ค์ด์ง๊ธฐ ๋๋ฌธ์, ํ์ต ๋ฐ์ดํฐ์ ๋ง์ด ๋ฑ์ฅํ ์ธ์ดยทํจํด์ผ์๋ก ํฐ ๋ฉ์ด๋ฆฌ๋ก ๋ฌถ์ฌ ํ ํฐ์ด ์ ๊ฒ ๋์์. ์์ด๊ฐ ์๋์ ์ผ๋ก "ํ ํฐ ํจ์จ"์ด ์ข์ ์ด์ ๊ฐ ์ด๊ฑฐ์์. ํ๊ตญ์ด๋ ํ ์์ ์ด UTF-8๋ก 3๋ฐ์ดํธ๋ฅผ ์ฐจ์งํ๊ณ , ๋ฐ์ดํธ ์์ค BPE์์๋ ์์ฃผ ์ฐ์ด์ง ์๋ ์์ ์ด ์ฌ๋ฌ ๋ฐ์ดํธ ํ ํฐ์ผ๋ก ์ชผ๊ฐ์ง ์ ์์ด์ ํ ํฐ ์๊ฐ ๋์ด๋๊ธฐ ์ฝ์ต๋๋ค.
๋ค๋ฅธ ๋ฐฉ์๋ ์์ด์. Google ๊ณ์ด๊ณผ ์ฌ๋ฌ ์คํ ๋ชจ๋ธ์์ ์ฐ์ฌ ์จ SentencePiece(BPE ๋๋ Unigram ์๊ณ ๋ฆฌ์ฆ ์ง์), BERT ๊ณ์ด์ WordPiece ๋ฑ์ด์ฃ . ์๊ณ ๋ฆฌ์ฆ์ด ๋ฌ๋ผ๋ ๊ณ์ฐ๊ธฐ ์ ์ฅ์์ ํ ์ผ์ ๋๊ฐ์์. "ํด๋น ๋ชจ๋ธ์ ํ ํฌ๋์ด์ ๋ฅผ ๋ถ๋ฌ์์ encodeํ ๋ค ๊ธธ์ด๋ฅผ ์ฐ๋ค." ๋!
3. ์ด๋ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ก ์ ๊น? ๋๊ตฌ ์ง๋ ๐บ๏ธ
"์ด๋ค ๋ชจ๋ธ์ ํ ํฐ์ ์ธ๊ณ ์ถ์๊ฐ"์ ๋ฐ๋ผ ๋๊ตฌ๊ฐ ๊ฐ๋ ค์. ํ๋ก ์ ๋ฆฌํด ๋ณผ๊ฒ์.
| ๋์ ๋ชจ๋ธ | ์ถ์ฒ ๋ฐฉ๋ฒ | ํน์ง |
|---|---|---|
| OpenAI GPT ๊ณ์ด | tiktoken (pip install tiktoken) | OpenAI๊ฐ ๊ณต๊ฐํ ๋น ๋ฅธ BPE ํ ํฌ๋์ด์ . ๋ก์ปฌ์์ ์คํ๋ผ์ธ ๊ณ์ฐ ๊ฐ๋ฅ(์ต์ด 1ํ ์ธ์ฝ๋ฉ ํ์ผ ๋ค์ด๋ก๋) |
| Hugging Face ๊ณต๊ฐ ๋ชจ๋ธ (Llama, Mistral, Qwen, Gemma ๋ฑ) | transformers์ AutoTokenizer | ๋ชจ๋ธ ์ ์ฅ์์ tokenizer ํ์ผ์ ๊ทธ๋๋ก ์ฌ์ฉ. ์ผ๋ถ ๋ชจ๋ธ์ ์ ๊ทผ ์น์ธ ํ์ |
| Anthropic Claude | ๊ณต์ SDK์ ํ ํฐ ์นด์ดํ API | ๋ฉ์์งยท์์คํ ํ๋กฌํํธยท๋๊ตฌ ์ ์๋ฅผ ํฌํจํ ์ ๋ ฅ ํ ํฐ ์๋ฅผ ์๋ฒ๊ฐ ๊ณ์ฐํด ์ค |
| Google Gemini | ๊ณต์ SDK์ count_tokens | ์๋ฒ ์ธก ๊ณ์ฐ. ํ ์คํธ ์ธ ๋ฉํฐ๋ชจ๋ฌ ์ ๋ ฅ๋ ์ง๊ณ |
4. ๊ฐ์ฅ ์์ ํ ํฐ ๊ณ์ฐ๊ธฐ: 10์ค๋ก ์์ํ๊ธฐ โก
๋จผ์ ์ค์น๋ถํฐ ํด์.
pip install tiktoken
๊ทธ๋ฆฌ๊ณ ๋๋ง์ ์ฒซ ์ฝ๋์ ๋๋ค.
import tiktoken
enc = tiktoken.get_encoding("o200k_base") # GPT-4o ๊ณ์ด์์ ์ฐ๋ ์ธ์ฝ๋ฉ
text = "์๋
ํ์ธ์! ํ ํฐ ๊ณ์ฐ๊ธฐ๋ฅผ ๋ง๋ค์ด ๋ด
์๋ค."
tokens = enc.encode(text)
print("ํ ํฐ ์:", len(tokens))
print("ํ ํฐ ID:", tokens)
print("๋ณต์:", enc.decode(tokens))
์ด๊ฒ ์ ๋ถ์์. encode()๊ฐ ์ ์ ๋ฆฌ์คํธ๋ฅผ ๋๋ ค์ฃผ๊ณ , ๊ทธ len()์ด ํ ํฐ ์์์. decode()๋ก ๋ค์ ์๋ฌธ์ด ๋ณต์๋๋์ง๋ ํ์ธํ ์ ์์ฃ .
์ธ์ฝ๋ฉ ์ด๋ฆ vs ๋ชจ๋ธ ์ด๋ฆ
tiktoken์ ๋ ๊ฐ์ง ๋ฐฉ์์ผ๋ก ์ธ์ฝ๋๋ฅผ ๋ถ๋ฌ์.
enc_a = tiktoken.get_encoding("cl100k_base") # ์ธ์ฝ๋ฉ ์ด๋ฆ์ผ๋ก
enc_b = tiktoken.encoding_for_model("gpt-4o") # ๋ชจ๋ธ ์ด๋ฆ์ผ๋ก
print(enc_b.name) # o200k_base
๋ํ์ ์ธ ๋งคํ์ ์ด๋์. GPT-4ยทGPT-3.5-turbo ๋ฐ text-embedding-3 ๊ณ์ด ์๋ฒ ๋ฉ ๋ชจ๋ธ์ cl100k_base, GPT-4o ๊ณ์ด์ o200k_base, ๊ทธ๋ณด๋ค ์ค๋๋ GPT-3 ๊ณ์ด์ r50k_baseยทp50k_base๋ฅผ ์ฌ์ฉํ์ด์. ์ด๋ฆ์ ์ซ์์ฒ๋ผ cl100k_base๋ ์ฝ 10๋ง ๊ฐ, o200k_base๋ ์ฝ 20๋ง ๊ฐ ๊ท๋ชจ์ ์ดํ๋ฅผ ๊ฐ๊ณ ์๊ณ , ์ดํ๊ฐ ์ปค์ง๋ฉด์ ์์ด ์ด์ธ ์ธ์ด์ ํ ํฐ ํจ์จ์ด ๊ฐ์ ๋์๋ค๊ณ ์๋ ค์ ธ ์์ด์.
encoding_for_model()์ tiktoken์ด ๋ชจ๋ฅด๋ ๋ชจ๋ธ๋ช
์ ๋ฃ์ผ๋ฉด KeyError๋ฅผ ๋์ ธ์. ์ ๋ชจ๋ธ์ด ๋์ค๋ฉด ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์
๋ฐ์ดํธ ์ ๊น์ง ์ด๋ฐ ์ผ์ด ์๊ธฐ๋, ๊ณ์ฐ๊ธฐ์๋ ๊ธฐ๋ณธ ์ธ์ฝ๋ฉ์ผ๋ก ๋จ์ด์ง๋ ํด๋ฐฑ์ ๊ผญ ๋ฃ์ด ๋์ธ์. (์๋ ์ค์ ์ฝ๋์ ๋ค์ด ์์ด์.)ํจ์ ํ๋: ํน์ ํ ํฐ ์๋ฌ
์ฌ์ฉ์๊ฐ ๋ถ์ฌ ๋ฃ์ ํ
์คํธ์ <|endoftext|> ๊ฐ์ ๋ฌธ์์ด์ด ๋ค์ด ์์ผ๋ฉด tiktoken์ encode()๋ ๊ธฐ๋ณธ์ ์ผ๋ก ValueError๋ฅผ ์ผ์ผ์ผ์. ํน์ ํ ํฐ์ด ์๋์น ์๊ฒ ์ฃผ์
๋๋ ๊ฑธ ๋ง๋ ์์ ์ฅ์น๊ฑฐ๋ ์. ๊ณ์ฐ๊ธฐ์์๋ ์ด๋ ๊ฒ ์ฒ๋ฆฌํ๋ฉด ๋ฉ๋๋ค.
# ํน์ ํ ํฐ ๋ฌธ์์ด๋ ๊ทธ๋ฅ "์ผ๋ฐ ํ
์คํธ"๋ก ์ทจ๊ธํด์ ์
n = len(enc.encode(text, disallowed_special=()))
# ๋๋ ํน์ ํ ํฐ ์ฒ๋ฆฌ๋ฅผ ์์ ํ์ง ์๋ ํจ์
n = len(enc.encode_ordinary(text))
๋ก๊ทธ ํ์ผ์ด๋ ํฌ๋กค๋ง ๋ฐ์ดํฐ์ฒ๋ผ "๋ฌด์์ด ๋ค์ด์ฌ์ง ๋ชจ๋ฅด๋" ์ ๋ ฅ์ ๋ค๋ฃจ๋ ๊ณ์ฐ๊ธฐ๋ผ๋ฉด ์ด ์ฒ๋ฆฌ๊ฐ ์ฌ์ค์ ํ์์์. ์ด๊ฑฐ ์ ํ๋ฉด ์๋ฒฝ์ ๋ฐฐ์น ๋๋ฆฌ๋ค ํฐ์ง๋ ๊ฒฝํ์ ํ๊ฒ ๋ฉ๋๋ค. ๐
5. ์ฑํ ๋ฉ์์ง๋ ๋ณธ๋ฌธ๋ง ์ธ๋ฉด ์ํด ๋ณธ๋ค ๐ฌ
Chat Completions์ฒ๋ผ messages ๋ฐฐ์ด์ ๋ณด๋ด๋ API๋ ๊ฐ ๋ฉ์์ง์ ์ญํ (role) ๊ตฌ๋ถ์ฉ ํฌ๋งท ํ ํฐ์ด ๋ถ์ด์. ๊ทธ๋์ ๋ฉ์์ง ๋ด์ฉ๋ง ํฉ์น ํ ํฐ ์๋ณด๋ค ์ค์ ์ฒญ๊ตฌ ํ ํฐ์ด ์กฐ๊ธ ๋ ๋ง์ต๋๋ค. OpenAI Cookbook์ "How to count tokens with tiktoken" ์์ ์์๋ gpt-3.5-turboยทgpt-4 ๊ณ์ด ๊ธฐ์ค์ผ๋ก ๋ฉ์์ง๋ง๋ค 3ํ ํฐ, name ํ๋๊ฐ ์์ผ๋ฉด 1ํ ํฐ ์ถ๊ฐ, ๊ทธ๋ฆฌ๊ณ ์๋ต ์์์ฉ์ผ๋ก 3ํ ํฐ์ ๋ํ๋ ๋ฐฉ์์ผ๋ก ๊ณ์ฐํด์.
def count_chat_tokens(messages, model="gpt-4o"):
"""OpenAI Cookbook ๋ฐฉ์์ ๊ทผ์ฌ ๊ณ์ฐ.
๋ชจ๋ธ์ ๋ฐ๋ผ ์ค๋ฒํค๋๊ฐ ๋ฌ๋ผ์ง ์ ์์ผ๋ฏ๋ก '์ถ์ ์น'๋ก ์ฌ์ฉ."""
try:
enc = tiktoken.encoding_for_model(model)
except KeyError:
enc = tiktoken.get_encoding("o200k_base")
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), disallowed_special=()))
if key == "name":
total += tokens_per_name
total += 3 # ์ด์์คํดํธ ์๋ต ํ๋ผ์ด๋ฐ
return total
msgs = [
{"role": "system", "content": "๋๋ ์น์ ํ ํ์ด์ฌ ํํฐ์ผ."},
{"role": "user", "content": "๋ฆฌ์คํธ ์ปดํ๋ฆฌํจ์
์ค๋ช
ํด์ค"},
]
print(count_chat_tokens(msgs))
usage ํ๋์
๋๋ค. ๊ณ์ฐ๊ธฐ๋ "์ฌ์ ์ถ์ ", usage๋ "์ฌํ ์ ์ฐ"์ด๋ผ๊ณ ์๊ฐํ๋ฉด ๊น๋ํด์.6. ๋ค๋ฅธ ๋ชจ๋ธ ํจ๋ฐ๋ฆฌ๋ ์ธ์ด ๋ณด์ ๐
Hugging Face ์คํ ๋ชจ๋ธ
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-7B-Instruct")
text = "์คํ ๋ชจ๋ธ์ ํ ํฐ ์๋ฅผ ์ธ์ด ๋ด
๋๋ค."
ids = tok.encode(text, add_special_tokens=False)
print(len(ids))
# ์ฑํ
ํ
ํ๋ฆฟ๊น์ง ํฌํจํ '์ค์ ์
๋ ฅ' ๊ธธ์ด
messages = [{"role": "user", "content": text}]
chat_ids = tok.apply_chat_template(messages, add_generation_prompt=True)
print(len(chat_ids))
์ฌ๊ธฐ์ ํต์ฌ์ ๋ ๊ฐ์ง์์. ์ฒซ์งธ, add_special_tokens ๊ธฐ๋ณธ๊ฐ์ ๋ฐ๋ผ BOS ๊ฐ์ ํน์ ํ ํฐ์ด ๋ถ์ด ์ซ์๊ฐ 1~2๊ฐ ๋ฌ๋ผ์ง ์ ์์ด์. ๋์งธ, ์ฑํ
๋ชจ๋ธ์ apply_chat_template์ผ๋ก ๋ง๋ ํฌ๋งท์ด ์ค์ ๋ชจ๋ธ ์
๋ ฅ์ด๋ฏ๋ก, ์ปจํ
์คํธ ํ๋ ๊ฒ์ฌ๋ ์ด ๊ฐ์ผ๋ก ํด์ผ ์ ํํฉ๋๋ค. ๋ชจ๋ธ ๊ฐ์ค์น๋ ํ์ ์๊ณ ํ ํฌ๋์ด์ ํ์ผ๋ง ๋ด๋ ค๋ฐ์ผ๋ ์๊ฐ๋ณด๋ค ๊ฐ๋ฒผ์์. (์ผ๋ถ ๋ชจ๋ธ์ ํ๋ธ์์ ์ด์ฉ ์ฝ๊ด ๋์ ํ ํ ํฐ ์ธ์ฆ์ด ํ์ํด์.)
Anthropic Claude
Claude๋ ๋ก์ปฌ ํ ํฌ๋์ด์ ๋์ ๊ณต์ ํ ํฐ ์นด์ดํ API๋ฅผ ์ ๊ณตํด์. ๋ฉ์์ง, ์์คํ ํ๋กฌํํธ, ๋๊ตฌ ์ ์๊น์ง ๋ฃ์ด ๋ณด๋ด๋ฉด ์ ๋ ฅ ํ ํฐ ์๋ฅผ ๋๋ ค์ค๋๋ค.
import anthropic
client = anthropic.Anthropic() # ํ๊ฒฝ๋ณ์ ANTHROPIC_API_KEY ์ฌ์ฉ
resp = client.messages.count_tokens(
model="claude-sonnet-4-5", # ์ฌ์ฉ ์ค์ธ ๋ชจ๋ธ ID๋ก ๋ฐ๊พธ์ธ์
system="๋๋ ์ฝ๋ ๋ฆฌ๋ทฐ์ด์ผ.",
messages=[{"role": "user", "content": "์ด ํจ์ ๋ฆฌ๋ทฐํด์ค: def f(x): return x*2"}],
)
print(resp.input_tokens)
Google Gemini
from google import genai
client = genai.Client() # ํ๊ฒฝ๋ณ์ GEMINI_API_KEY ์ฌ์ฉ
resp = client.models.count_tokens(
model="gemini-2.0-flash", # ์ฌ์ฉ ์ค์ธ ๋ชจ๋ธ ID๋ก ๋ฐ๊พธ์ธ์
contents="ํ ํฐ์ ์ธ์ด ์ฃผ์ธ์.",
)
print(resp.total_tokens)
7. ์ค๊ณ๋ ๊ทธ๋ฆฌ๊ธฐ: ์ธ๋ชจ ์๋ ๊ณ์ฐ๊ธฐ์ ๊ตฌ์กฐ ๐๏ธ
์ด์ ์ฅ๋๊ฐ์ ๋๊ตฌ๋ก ํค์ ๋ด ์๋ค. ์ค์ ๋ก ์ธ ๋งํ ๊ณ์ฐ๊ธฐ๋ ๋ณดํต ์ด๋ฐ ๊ธฐ๋ฅ์ด ํ์ํด์.
count(text) โ int)๋ก ๊ฐ์ธ๊ธฐ8. ์ค์ ์ฝ๋: ๋ฐฑ์๋ ์ถ์ํ๋ถํฐ ๐งฑ
ํ๋์ฉ ์์ ๋ณผ๊ฒ์. ๋จผ์ "๋ฌด์์ผ๋ก ์ธ๋ ๊ฐ์ ๋ชจ์"์ผ๋ก ์ฐ๊ธฐ ์ํ ์ถ์ ํด๋์ค์์. ํ์ผ ์ด๋ฆ์ tokcalc.py๋ก ํ๊ฒ ์ต๋๋ค.
from __future__ import annotations
from abc import ABC, abstractmethod
from functools import lru_cache
import tiktoken
class TokenCounter(ABC):
name: str = "base"
exact: bool = True # ๋์ ๋ชจ๋ธ ๊ธฐ์ค์ผ๋ก ์ ํํ ๊ฐ์ธ๊ฐ?
@abstractmethod
def count(self, text: str) -> int: ...
def count_many(self, texts: list[str]) -> list[int]:
return [self.count(t) for t in texts]
@lru_cache(maxsize=None)
def _get_encoding(name: str):
# ์ธ์ฝ๋ ๋ก๋ฉ์ ๋น์ธ๋ฏ๋ก ํ ๋ฒ๋ง
return tiktoken.get_encoding(name)
class TiktokenCounter(TokenCounter):
def __init__(self, model: str | None = None, encoding: str | None = None,
fallback: str = "o200k_base"):
if encoding:
self.enc = _get_encoding(encoding)
else:
try:
self.enc = tiktoken.encoding_for_model(model or "gpt-4o")
except KeyError:
self.enc = _get_encoding(fallback)
self.exact = False # ๋ชจ๋ฅด๋ ๋ชจ๋ธ โ ์ถ์ ์น
self.name = f"tiktoken:{self.enc.name}"
def count(self, text: str) -> int:
return len(self.enc.encode(text, disallowed_special=()))
def count_many(self, texts: list[str]) -> list[int]:
# ๋ด๋ถ์ ์ผ๋ก ์ค๋ ๋๋ฅผ ์จ์ ์ฌ๋ฌ ํ
์คํธ๋ฅผ ํ ๋ฒ์ ์ธ์ฝ๋ฉ
batches = self.enc.encode_batch(texts, disallowed_special=())
return [len(b) for b in batches]
def encode(self, text: str) -> list[int]:
return self.enc.encode(text, disallowed_special=())
def decode(self, ids: list[int]) -> str:
return self.enc.decode(ids)
class HFCounter(TokenCounter):
def __init__(self, repo_id: str):
from transformers import AutoTokenizer # ํ์ํ ๋๋ง ์ํฌํธ
self.tok = AutoTokenizer.from_pretrained(repo_id)
self.name = f"hf:{repo_id}"
def count(self, text: str) -> int:
return len(self.tok.encode(text, add_special_tokens=False))
def encode(self, text: str) -> list[int]:
return self.tok.encode(text, add_special_tokens=False)
def decode(self, ids: list[int]) -> str:
return self.tok.decode(ids)
def make_counter(model: str) -> TokenCounter:
"""'hf:์ ์ฅ์ID' ํ์์ด๋ฉด HF, ์๋๋ฉด tiktoken."""
if model.startswith("hf:"):
return HFCounter(model[3:])
return TiktokenCounter(model=model)
ํฌ์ธํธ๋ฅผ ์ง์ด ๋ณด๋ฉด์.
๐ lru_cache๋ก ์ธ์ฝ๋ ์บ์ฑ: tiktoken ์ธ์ฝ๋๋ ์ฒ์ ๋ก๋ํ ๋ ์ดํ ํ์ผ์ ์ฝ๊ณ (์ต์ด์ ๋ค์ด๋ก๋๊น์ง) ๋ด๋ถ ์๋ฃ๊ตฌ์กฐ๋ฅผ ๋ง๋ค์ด์. ํ์ผ 1,000๊ฐ๋ฅผ ์
๋๋ง๋ค ์๋ก ๋ง๋ค๋ฉด ์๊ฐ ๋ญ๋น์ฃ .
๐ exact ํ๋๊ทธ: ํด๋ฐฑ์ผ๋ก ๋จ์ด์ก๋ค๋ฉด ์ฌ์ฉ์์๊ฒ "์ด๊ฑด ์ถ์ ์น์์"๋ผ๊ณ ์ ์งํ๊ฒ ์๋ ค ์ฃผ๊ธฐ ์ํ ์ฅ์น์์. ์ด๋ฐ ๋ํ
์ผ์ด ๋๊ตฌ์ ์ ๋ขฐ๋๋ฅผ ๋ง๋ญ๋๋ค.
๐ ์ง์ฐ ์ํฌํธ: transformers๋ ๋ฌด๊ฑฐ์ด ํจํค์ง๋ผ HF ๋ฐฑ์๋๋ฅผ ์ธ ๋๋ง ๋ถ๋ฌ์์. CLI ์์ ์๋๊ฐ ํ ๋ฌ๋ผ์ง๋๋ค.
TIKTOKEN_CACHE_DIR๋ก ์์น๋ฅผ ์ง์ ํ๋ ๋ฐฉ์์ด ํํ ์ฐ์ฌ์.9. ํ์ผยทํด๋ ์ผ๊ด ๊ณ์ฐ๊ณผ ๋ฆฌํฌํธ ๐
์ด์ ์ง์ง "์๋" ๊ณ์ฐ๊ธฐ๋ค์ด ๋ถ๋ถ์ด์์. ํด๋๋ฅผ ํต์งธ๋ก ๋ฃ์ผ๋ฉด ํ์ผ๋ณ ํ ํฐ ์๋ฅผ ์ซ ๋ฝ์ ์ฃผ๋ ๊ธฐ๋ฅ์ ๋๋ค.
from dataclasses import dataclass
from pathlib import Path
TEXT_EXTS = {".txt", ".md", ".py", ".json", ".csv", ".html", ".js", ".ts", ".yaml", ".yml"}
@dataclass
class FileStat:
path: str
chars: int
tokens: int
@property
def tokens_per_char(self) -> float:
return self.tokens / self.chars if self.chars else 0.0
def read_text(path: Path) -> str | None:
for encoding in ("utf-8", "cp949"): # ๊ตญ๋ด ๋ ๊ฑฐ์ ํ์ผ ๋๋น
try:
return path.read_text(encoding=encoding)
except UnicodeDecodeError:
continue
return None # ๋ฐ์ด๋๋ฆฌ ๋ฑ์ ๊ฑด๋๋
def iter_files(target: Path):
if target.is_file():
yield target
return
for p in sorted(target.rglob("*")):
if p.is_file() and p.suffix.lower() in TEXT_EXTS:
yield p
def scan(target: Path, counter: TokenCounter) -> list[FileStat]:
paths, texts = [], []
for p in iter_files(target):
t = read_text(p)
if t is not None:
paths.append(p)
texts.append(t)
counts = counter.count_many(texts)
return [FileStat(str(p), len(t), n) for p, t, n in zip(paths, texts, counts)]
cp949 ํด๋ฐฑ์ ํ๊ตญ ๊ฐ๋ฐ์๋ผ๋ฉด ๊ณต๊ฐํ ๋ํ
์ผ์ด์์. ์ค๋๋ ์๋์ฐ ํ๊ฒฝ์์ ๋ง๋ ๋ฉ๋ชจ์ฅ ํ์ผ์ UTF-8์ด ์๋ ๊ฒฝ์ฐ๊ฐ ๊ฝค ์๊ฑฐ๋ ์. ๊ธ์ ์(chars)๋ ๊ฐ์ด ์ ์ฅํด ๋๋ฉด "๊ธ์๋น ํ ํฐ ๋น์จ"์ ๋ณผ ์ ์์ด์, ์ฐ๋ฆฌ ๋ฐ์ดํฐ๊ฐ ์ด๋ค ํน์ฑ์ธ์ง ๊ฐ ์ก๋ ๋ฐ ์์ฃผ ์ข์์.
10. ๋น์ฉ ์ถ์ : ๋จ๊ฐ๋ ์ฝ๋์ ๋ฐ์ง ๋ง์ ๐ฐ
์๊ธ์ ๋ชจ๋ธ๋ง๋ค ๋ค๋ฅด๊ณ , ์ ๋ ฅยท์ถ๋ ฅ ๋จ๊ฐ๊ฐ ๋ฐ๋ก์ด๋ฉฐ, ์บ์ ํ ์ธยท๋ฐฐ์น ํ ์ธ ๊ฐ์ ์ต์ ๋ ์๊ณ , ๋ฌด์๋ณด๋ค ์์ฃผ ๋ฐ๋๋๋ค. ๊ทธ๋์ ๋จ๊ฐ๋ ๋ณ๋ JSON ํ์ผ๋ก ๋นผ๋ ๊ฒ ์ ์์ด์์.
# prices.json ์์ โ ์ซ์๋ ํ์ ์ค๋ช
์ฉ ์๋ฆฌํ์์์
๋๋ค.
# ๋ฐ๋์ ๊ฐ ์ฌ ๊ณต์ ๊ฐ๊ฒฉ ํ์ด์ง์ ์ต์ ๊ฐ์ ๋ฃ์ผ์ธ์.
{
"gpt-4o": {"input_per_1m": 0.0, "output_per_1m": 0.0},
"my-local-llm":{"input_per_1m": 0.0, "output_per_1m": 0.0}
}
import json
def estimate_cost(model: str, input_tokens: int, expected_output_tokens: int,
price_file: str = "prices.json") -> float | None:
with open(price_file, encoding="utf-8") as f:
prices = json.load(f)
p = prices.get(model)
if p is None:
return None
return (input_tokens * p["input_per_1m"]
+ expected_output_tokens * p["output_per_1m"]) / 1_000_000
์ฌ๊ธฐ์ ๋ง์ด๋ค ๋์น๋ ๊ฒ ์ถ๋ ฅ ํ ํฐ์ด์์. ์ ๋ ฅ์ ๋ฏธ๋ฆฌ ์ ํํ ์ ์ ์์ง๋ง ์ถ๋ ฅ์ ๋ชจ๋ธ์ด ์ผ๋ง๋ ๊ธธ๊ฒ ๋ตํ ์ง ๋ชจ๋ฅด์์์. ๊ทธ๋์ ์ค๋ฌด์์๋ ๋ณดํต ์ธ ๊ฐ์ง ๋ฐฉ๋ฒ ์ค ํ๋๋ฅผ ์จ์.
max_tokens ์ค์ ๊ฐ์ ๊ทธ๋๋ก ์ถ๋ ฅ๋์ผ๋ก ๊ฐ์ โ ์ต์
์ ๋น์ฉ11. ํ ํฐ ๊ธฐ์ค ์ฒญํฌ ๋ถํ ๊ธฐ โ๏ธ
RAG(๊ฒ์ ์ฆ๊ฐ ์์ฑ) ํ์ดํ๋ผ์ธ์ ๋ง๋ค ๋ ๊ณ์ฐ๊ธฐ์ ์ง๊ฐ๊ฐ ๋๋ฌ๋์. ๋ฌธ์๋ฅผ "์ต๋ Nํ ํฐ, ์๋ค Mํ ํฐ ๊ฒน์นจ"์ผ๋ก ์๋ฅด๋ ๊ธฐ๋ฅ์ด์ฃ .
def chunk_by_tokens(text: str, counter, max_tokens: int = 500,
overlap: int = 50) -> list[str]:
if overlap >= max_tokens:
raise ValueError("overlap์ max_tokens๋ณด๋ค ์์์ผ ํฉ๋๋ค.")
ids = counter.encode(text)
step = max_tokens - overlap
chunks = []
for start in range(0, len(ids), step):
piece = ids[start:start + max_tokens]
chunks.append(counter.decode(piece))
if start + max_tokens >= len(ids):
break
return chunks
๊ฐ๋จํ์ฃ ? ๊ทธ๋ฐ๋ฐ ์ด ์์งํ ๋ฒ์ ์๋ ํ๊ตญ์ด ์ฌ์ฉ์์๊ฒ ์น๋ช
์ ์ธ ํจ์ ์ด ์์ด์. ์์ ๋งํ๋ฏ ๋ฐ์ดํธ ์์ค BPE์์๋ ํ๊ธ ํ ๊ธ์๊ฐ ์ฌ๋ฌ ํ ํฐ์ ๊ฑธ์ณ ์์ ์ ์์ด์. ์ฒญํฌ ๊ฒฝ๊ณ๊ฐ ํํ ๊ทธ ์ค๊ฐ์ ๋จ์ด์ง๋ฉด decode() ๊ฒฐ๊ณผ ๋์ ๊นจ์ง ๋ฌธ์(๏ฟฝ)๊ฐ ์๊น๋๋ค.
โก ๋ ์ข์ ๋ฐฉ๋ฒ: ๋จผ์ ๋ฌธ๋จยท๋ฌธ์ฅ ๋จ์๋ก ๋๋ ๋ค, ํ ํฐ ์๋ฅผ ์ธ๋ฉด์ ํ๋๊น์ง ์ด์ด ๋ถ์ด๊ธฐ. ์๋ฏธ ๋จ์๊ฐ ๋ณด์กด๋ผ ๊ฒ์ ํ์ง๋ ์ข์์ ธ์.
import re
def chunk_by_sentences(text: str, counter, max_tokens: int = 500) -> list[str]:
# ๋ง์นจํยท๋ฌผ์ํยท๋๋ํยท์ค๋ฐ๊ฟ ๊ธฐ์ค์ ๋จ์ ๋ฌธ์ฅ ๋ถ๋ฆฌ
sentences = [s for s in re.split(r"(?<=[.!?ใ])\s+|\n+", text) if s.strip()]
chunks, buf, buf_tokens = [], [], 0
for s in sentences:
n = counter.count(s)
if n > max_tokens: # ํ ๋ฌธ์ฅ์ด ๋๋ฌด ๊ธธ๋ฉด ํ ํฐ ๋จ์๋ก ๊ฐ์ ๋ถํ
if buf:
chunks.append(" ".join(buf)); buf, buf_tokens = [], 0
chunks.extend(chunk_by_tokens(s, counter, max_tokens, overlap=0))
continue
if buf_tokens + n > max_tokens:
chunks.append(" ".join(buf)); buf, buf_tokens = [], 0
buf.append(s); buf_tokens += n
if buf:
chunks.append(" ".join(buf))
return chunks
12. ๋ช ๋ น์ค ๋๊ตฌ(CLI)๋ก ๋ฌถ๊ธฐ ๐ฅ๏ธ
์ด์ ํฐ๋ฏธ๋์์
python tokcalc.py ./docs --model gpt-4o --limit 128000 ์ฒ๋ผ ์ธ ์ ์๊ฒ ๋ง๋ค์ด ๋ด
์๋ค. ํ์ค ๋ผ์ด๋ธ๋ฌ๋ฆฌ argparse๋ง์ผ๋ก ์ถฉ๋ถํด์.
import argparse
import sys
def main(argv=None):
ap = argparse.ArgumentParser(description="ํ์ด์ฌ ํ ํฐ ๊ธธ์ด ์๋ ๊ณ์ฐ๊ธฐ")
ap.add_argument("target", nargs="?", help="ํ์ผ/ํด๋ ๊ฒฝ๋ก (์๋ต ์ ํ์ค์
๋ ฅ)")
ap.add_argument("--model", default="gpt-4o",
help="๋ชจ๋ธ๋ช
๋๋ 'hf:์ ์ฅ์ID'")
ap.add_argument("--limit", type=int, default=None,
help="์ปจํ
์คํธ ํ๋(ํ ํฐ). ์ด๊ณผ ํ์ผ ๊ฒฝ๊ณ ")
ap.add_argument("--top", type=int, default=20, help="์์ N๊ฐ ํ์ผ๋ง ์ถ๋ ฅ")
ap.add_argument("--csv", help="๊ฒฐ๊ณผ๋ฅผ CSV๋ก ์ ์ฅํ ๊ฒฝ๋ก")
args = ap.parse_args(argv)
counter = make_counter(args.model)
if not getattr(counter, "exact", True):
print(f"โ ๏ธ '{args.model}'์ ๋ชจ๋ฆ
๋๋ค. {counter.name}๋ก ์ถ์ ํฉ๋๋ค.",
file=sys.stderr)
if args.target is None: # ํ์ดํ ์
๋ ฅ: cat a.txt | python tokcalc.py
text = sys.stdin.read()
print(counter.count(text))
return 0
stats = scan(Path(args.target), counter)
stats.sort(key=lambda s: s.tokens, reverse=True)
total = sum(s.tokens for s in stats)
print(f"๋ฐฑ์๋: {counter.name} | ํ์ผ {len(stats)}๊ฐ | ์ด {total:,} ํ ํฐ\n")
for s in stats[:args.top]:
flag = ""
if args.limit and s.tokens > args.limit:
flag = " ๐จ ํ๋ ์ด๊ณผ"
print(f"{s.tokens:>10,} {s.tokens_per_char:5.2f}/์ {s.path}{flag}")
if args.csv:
import csv
with open(args.csv, "w", newline="", encoding="utf-8-sig") as f:
w = csv.writer(f)
w.writerow(["path", "chars", "tokens", "tokens_per_char"])
for s in stats:
w.writerow([s.path, s.chars, s.tokens, f"{s.tokens_per_char:.4f}"])
return 0
if __name__ == "__main__":
raise SystemExit(main())
CSV ์ ์ฅ ์ utf-8-sig๋ฅผ ์ด ์ด์ ๋ ์์
์์ ํ๊ธ์ด ๊นจ์ง์ง ์๊ฒ ํ๋ ค๋ ๊ฑฐ์์(BOM ํฌํจ). ์ด๋ฐ ์ฌ์ํ ๋ฐฐ๋ ค๊ฐ ๋๋ฃ๋คํํ
"์ค, ์ด๊ฑฐ ์ ๋ง๋ค์๋ค" ์๋ฆฌ๋ฅผ ๋ฃ๊ฒ ํด์ค๋๋ค. ๐
sys.stderr๋ก ๋ด๋ณด๋ด๋ฉด, ๊ฒฐ๊ณผ๊ฐ๋ง ๋ค๋ฅธ ๋ช
๋ น์ด๋ก ํ์ดํํ ๋ ๊ฒฝ๊ณ ๋ฌธ๊ตฌ๊ฐ ์์ด์ง ์์์. ์: cat prompt.txt | python tokcalc.py > count.txt13. ํ๋ฉด์ด ์๋ ๊ณ์ฐ๊ธฐ: Streamlit์ผ๋ก 5๋ถ ์น์ฑ ๐
๋น๊ฐ๋ฐ์ ๋๋ฃ(๊ธฐํ์, ๋ง์ผํฐ)๋ ์ฐ๊ฒ ํ๋ ค๋ฉด ์น UI๊ฐ ์ต๊ณ ์์. Streamlit์ ์ฐ๋ฉด ์ ๋ง ๊ธ๋ฐฉ ๋ง๋ค์ด์ง๋๋ค.
# app.py โ ์คํ: streamlit run app.py
import streamlit as st
from tokcalc import make_counter
st.title("๐งฎ ํ ํฐ ๊ธธ์ด ๊ณ์ฐ๊ธฐ")
model = st.selectbox("๋ชจ๋ธ", ["gpt-4o", "gpt-4", "hf:Qwen/Qwen2.5-7B-Instruct"])
limit = st.number_input("์ปจํ
์คํธ ํ๋(ํ ํฐ)", value=128000, step=1000)
text = st.text_area("ํ
์คํธ๋ฅผ ๋ถ์ฌ ๋ฃ์ผ์ธ์", height=250)
@st.cache_resource
def get_counter(m):
return make_counter(m)
if text:
counter = get_counter(model)
ids = counter.encode(text)
n = len(ids)
col1, col2, col3 = st.columns(3)
col1.metric("ํ ํฐ ์", f"{n:,}")
col2.metric("๊ธ์ ์", f"{len(text):,}")
col3.metric("ํ๋ ์ฌ์ฉ๋ฅ ", f"{n / limit:.1%}")
st.progress(min(n / limit, 1.0))
with st.expander("ํ ํฐ ์ชผ๊ฐ์ง ๋ชจ์ ๋ณด๊ธฐ (์ 200๊ฐ)"):
pieces = [counter.decode([i]) for i in ids[:200]]
st.write(" | ".join(repr(p) for p in pieces))
st.cache_resource๋ ํ ํฌ๋์ด์ ๊ฐ์ ๋ฌด๊ฑฐ์ด ๊ฐ์ฒด๋ฅผ ์ธ์
๊ฐ์ ์ฌ์ฌ์ฉํ๊ฒ ํด ์ค์. ๋ง์ง๋ง "์ชผ๊ฐ์ง ๋ชจ์ ๋ณด๊ธฐ"์์ ํ ํฐ์ ํ๋์ฉ ๋์ฝ๋ฉํ๋ฉด, ์์์ ๋งํ ๋๋ก ํ๊ธ ๊ธ์๊ฐ ๋ฐ์ดํธ ์กฐ๊ฐ์ผ๋ก ๋๋ ๊ฒฝ์ฐ ๏ฟฝ์ฒ๋ผ ๋ณด์ผ ์ ์์ด์. ๋ฒ๊ทธ๊ฐ ์๋๋ผ ๋ฐ์ดํธ ์์ค BPE์ ์ ์ ๋์์ด๋ ๋๋ผ์ง ๋ง์ธ์! tiktoken์๋ ํ ํฐ๋ณ ์๋ณธ ๋ฐ์ดํธ๋ฅผ ๋๋ ค์ฃผ๋ decode_single_token_bytes()๋ ์์ด์, ๋ฐ์ดํธ ๋จ์๋ก ์๊ฐํํ๊ณ ์ถ์ ๋ ์ธ ์ ์์ด์.
์ด๋ ๊ฒ ๋ง๋ ๋๊ตฌ๋ ํ ๋ด๋ถ ์ํค์ ๋งํฌ๋ง ๊ฑธ์ด ๋ฌ๋ ๋ฐ์์ด ์ข์์. ํ๋กฌํํธ ์์ง๋์ด๋ง์ด๋ AI ์๋ํ ์์ ์ ์ธ์ฃผ๋ก ์ฃผ๊ณ ๋ฐ๋ ์ผ์ด ๋๋ฉด์, ์ฌ๋ฅ๋ท ๊ฐ์ ์ฌ๋ฅ ๊ฑฐ๋ ํ๋ซํผ์์๋ "ํ๋กฌํํธ ์ต์ ํ", "RAG ๊ตฌ์ถ" ๊ฐ์ ์๋ขฐ๋ฅผ ํ ๋ ํ ํฐ ์์ฐ์ ์์น๋ก ์ ์ํ๋ฉด ๊ฒฌ์ ์ํต์ด ํจ์ฌ ๋ช ํํด์ง๋๋ค.
14. ์ฑ๋ฅ ์ด์ผ๊ธฐ: ๋์ฉ๋์ ๋น ๋ฅด๊ฒ ๐
๋ช ๊ฐ ํ์ผ์ด๋ฉด ๋ญ๋ ๋น ๋ฅด์ง๋ง, ์ GB ๋ก๊ทธ๋ ์์ญ๋ง ๊ฐ ๋ฌธ์๋ผ๋ฉด ์ด์ผ๊ธฐ๊ฐ ๋ฌ๋ผ์ ธ์.
| ๊ธฐ๋ฒ | ์ค๋ช | ์ธ์ ์ฐ๋ |
|---|---|---|
| ์ธ์ฝ๋ ์บ์ฑ | get_encoding ๊ฒฐ๊ณผ ์ฌ์ฌ์ฉ (tiktoken ๋ด๋ถ์๋ ์บ์๊ฐ ์์ง๋ง ๋ช
์์ ์ผ๋ก ๊ด๋ฆฌํ๋ฉด ๊น๋) | ํญ์ |
encode_batch | ์ฌ๋ฌ ํ ์คํธ๋ฅผ ์ค๋ ๋๋ก ๋ณ๋ ฌ ์ธ์ฝ๋ฉ | ์งง์ ํ ์คํธ ๋ค์ |
| HF Fast ํ ํฌ๋์ด์ | Rust๋ก ๊ตฌํ๋ tokenizers ๊ธฐ๋ฐ. ๋ฆฌ์คํธ๋ฅผ ํ ๋ฒ์ ๋ฃ์ผ๋ฉด ๋ฐฐ์น ์ฒ๋ฆฌ | HF ๋ชจ๋ธ ๋๋ ์ฒ๋ฆฌ |
| ๋ฉํฐํ๋ก์ธ์ฑ | concurrent.futures.ProcessPoolExecutor๋ก ํ์ผ ๋จ์ ๋ถ์ฐ | ํ์ผ ์๊ฐ ์์ฃผ ๋ง์ ๋ |
| ์ค ๋จ์ ์คํธ๋ฆฌ๋ฐ | ๊ฑฐ๋ํ ํ์ผ์ ํต์งธ๋ก ๋ฉ๋ชจ๋ฆฌ์ ์ฌ๋ฆฌ์ง ์๊ณ ์คยท๋ธ๋ก ๋จ์๋ก ์ธ์ ํฉ์ฐ | ๋ฉ๋ชจ๋ฆฌ ์ ํ ํ๊ฒฝ (์ฝ๊ฐ์ ์ค์ฐจ ํ์ฉ) |
def count_large_file(path: Path, counter, block_lines: int = 2000) -> int:
"""๊ฑฐ๋ ํ์ผ์ ๋ธ๋ก ๋จ์๋ก ์ธ์ ํฉ์ฐ. ๋ธ๋ก ๊ฒฝ๊ณ์์ ๋ฏธ์ธํ ์ค์ฐจ ๊ฐ๋ฅ."""
total, buf = 0, []
with path.open(encoding="utf-8", errors="replace") as f:
for line in f:
buf.append(line)
if len(buf) >= block_lines:
total += counter.count("".join(buf)); buf.clear()
if buf:
total += counter.count("".join(buf))
return total
cProfile์ด๋ time.perf_counter()๋ก ์ง์ ์ฌ ๋ณด๋ ๊ฒ ์ ๋ต์ด์์. ํ์ผ I/O๊ฐ ๋ณ๋ชฉ์ธ ๊ฒฝ์ฐ๋ ๋ง๊ฑฐ๋ ์.15. ํ ์คํธ๋ก ๊ณ์ฐ๊ธฐ๋ฅผ ๋ฏฟ์ ์ ์๊ฒ โ
์ซ์๋ฅผ ๋ด๋๋ ๋๊ตฌ๋ ํ๋ฆฌ๋ฉด ์ ๋ขฐ๋ฅผ ์์ด์. pytest๋ก ํต์ฌ ์ฑ์ง์ ๊ฒ์ฆํด ๋ก์๋ค. ํน์ ํ ํฐ ์๋ฅผ ํ๋์ฝ๋ฉํ๊ธฐ๋ณด๋ค "์ฑ์ง(property)"์ ๊ฒ์ฌํ๋ ๊ฒ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ๋ฒ์ ๋ณํ์๋ ํผํผํด์.
# test_tokcalc.py
import pytest
from tokcalc import TiktokenCounter, chunk_by_tokens, chunk_by_sentences
@pytest.fixture(scope="module")
def counter():
return TiktokenCounter(encoding="o200k_base")
def test_empty_is_zero(counter):
assert counter.count("") == 0
def test_roundtrip(counter):
text = "ํ ํฐ ๊ณ์ฐ๊ธฐ ํ
์คํธ ๐งช with English & code: print('hi')"
assert counter.decode(counter.encode(text)) == text
def test_special_token_text_does_not_crash(counter):
assert counter.count("๋ณธ๋ฌธ <|endoftext|> ๋") > 0
def test_batch_equals_single(counter):
texts = ["๊ฐ๋๋ค", "hello world", "x = 1\n"]
assert counter.count_many(texts) == [counter.count(t) for t in texts]
def test_chunks_respect_limit(counter):
text = "๋ฌธ์ฅ์
๋๋ค. " * 500
for c in chunk_by_sentences(text, counter, max_tokens=100):
assert counter.count(c) <= 110 # ์ฌ๊ฒฐํฉ ์ค์ฐจ ์ฌ์
def test_unknown_model_falls_back():
c = TiktokenCounter(model="totally-unknown-model")
assert c.exact is False
ํนํ test_special_token_text_does_not_crash๋ ์์์ ๋งํ ํน์ ํ ํฐ ํจ์ ์ด ๋ค์ ์๊ธฐ์ง ์๊ฒ ๋ง์ ์ฃผ๋ "ํ๊ท ๋ฐฉ์ง ํ
์คํธ"์์. ํ ๋ฒ ๊ฒช์ ๋ฒ๊ทธ๋ ํ
์คํธ๋ก ๋ฐ์ ํด ๋๋ ๊ฒ ๊ฐ๋ฐ์์ ์์กด ์ ๋ต์
๋๋ค. ๐งท
16. ํ๊ตญ์ด ํ ํฐ์ ์ค์ด๋ ์ค์ ๊ฐ๊ฐ ๐ฐ๐ท
๊ณ์ฐ๊ธฐ๋ฅผ ๋ง๋ค์์ผ๋ฉด ์ด์ ๊ทธ๊ฑธ๋ก ์คํ์ ํด ๋ณผ ์ฐจ๋ก์์. ์ซ์๋ฅผ ์ฌ ๋ณด๋ฉด ์์ธ์ ์ฌ์ค๋ค์ด ๋ณด์ ๋๋ค. ์๋๋ ๊ณ์ฐ๊ธฐ๋ก ์ง์ ๋น๊ตํด ๋ณด๊ธธ ๊ถํ๋ ์คํ ๋ชฉ๋ก์ด์์.
์ธก์ ํ์ง ์์ผ๋ฉด ๊ฐ์ ํ ์ ์๋ค. ํ ํฐ๋ ๋ง์ฐฌ๊ฐ์ง๋ค. ๊ฐ์ผ๋ก ํ๋กฌํํธ๋ฅผ ๊น์ง ๋ง๊ณ , ๊ณ์ฐ๊ธฐ๋ก ์ฌ๊ณ ๊น์.
17. ํ๋ก์ ํธ ๋ง๋ฌด๋ฆฌ: ๋ฐฐํฌ ํํ ๊ณ ๋ฅด๊ธฐ ๐ฆ
tokcalc.py ํ๋๋ฅผ ํ ์ ์ฅ์์ ๋๊ณ ๊ณต์ . ๊ฐ์ฅ ๋น ๋ฅด๊ณ ๋จ์ํด์.pyproject.toml์ [project.scripts] ํญ๋ชฉ์ผ๋ก tokcalc = "tokcalc:main"์ ๋ฑ๋กํ๋ฉด pip install ํ ์ด๋์๋ tokcalc ๋ช
๋ น์ผ๋ก ์คํ๋ผ์.๋ง์ง๋ง "๋ฏธ๋ค์จ์ด" ํจํด์ ์ฑ๋ด์์ ํนํ ์ ์ฉํด์. ๋ํ๊ฐ ๊ธธ์ด์ง๋ฉด ์ค๋๋ ๋ฉ์์ง๋ถํฐ ๋นผ๋ฉด์ ํ๋ ์์ ๋ง์ถ๋ ๊ฑฐ์ฃ .
def trim_history(messages, model="gpt-4o", budget=8000, keep_system=True):
"""์ค๋๋ ๋ํ๋ถํฐ ์ ๊ฑฐํด ํ ํฐ ์์ฐ ์์ ๋ง์ถ๋ค."""
system = [m for m in messages if m["role"] == "system"] if keep_system else []
rest = [m for m in messages if m["role"] != "system"]
while rest and count_chat_tokens(system + rest, model) > budget:
rest.pop(0) # ๊ฐ์ฅ ์ค๋๋ ๋ฉ์์ง ์ ๊ฑฐ
return system + rest
๐น tiktoken์
disallowed_special=() ๋๋ encode_ordinary๋ก ํน์ ํ ํฐ ์๋ฌ๋ฅผ ์๋ฐฉ๐น ์ฑํ API๋ ๋ฉ์์ง ํฌ๋งท ์ค๋ฒํค๋๊ฐ ๋ถ์ผ๋ฏ๋ก ๋ณธ๋ฌธ ํฉ๊ณ๋ณด๋ค ํฌ๋ค. ์ต์ข ๊ธฐ์ค์ API์ usage
๐น ๋จ๊ฐ๋ ์ค์ ํ์ผ๋ก ๋ถ๋ฆฌ, ์ถ๋ ฅ ํ ํฐ์ ์ํยทํต๊ณยท๋น์จ ์ค ํ๋๋ก ์ถ์
๐น ์ฒญํฌ ๋ถํ ์ ๋ฌธ์ฅ ๋จ์๋ก ํ๊ณ , ์์ฑ๋ ์ฒญํฌ๋ฅผ ๋ค์ ์ธ์ด ๊ฒ์ฆ
๐น ์ซ์๋ฅผ ๋ด๋ ๋๊ตฌ์ ํ ์คํธ์ "์ถ์ ์น" ํ์๋ก ์ ๋ขฐ๋ฅผ ๋ํ๋ค
์ฌ๊ธฐ๊น์ง ๋ฐ๋ผ์๋ค๋ฉด ์ด์ ์ฌ๋ฌ๋ถ ์์๋ "๊ธ์ ์ ๋์ถฉ ๊ณฑํ๊ธฐ"๊ฐ ์๋๋ผ, ๋ชจ๋ธ๋ณ๋ก ์ ํํ ์ธ๊ณ , ๋น์ฉ์ ์์ธกํ๊ณ , ํ๋๋ฅผ ์งํค๊ณ , ๋ฌธ์๋ฅผ ์๋ง๊ฒ ์๋ฅด๋ ์ง์ง ๋๊ตฌ๊ฐ ์์ด์. ์ฒ์์ 10์ค์ง๋ฆฌ ์คํฌ๋ฆฝํธ์๋๋ฐ ๋ง์ด์ฃ ! ๋ค์ ํ๋ก์ ํธ์์ ํ๋กฌํํธ ๊ธธ์ด ๋๋ฌธ์ ๊ณ ๋ฏผ๋ ๋, ๊ฐ ๋ง๊ณ ๊ณ์ฐ๊ธฐ๋ฅผ ๋จผ์ ์ผ๋ ์ต๊ด์ ๋ค์ฌ ๋ณด์ธ์. ์๊ฐ๋ณด๋ค ๋ง์ ๋๊ณผ ์๊ฐ์ด ์ ์ฝ๋ฉ๋๋ค. ๐ฑ
์ฐธ๊ณ ์๋ฃ
ยท openai/tiktoken (GitHub) โ https://github.com/openai/tiktoken
ยท OpenAI Cookbook, "How to count tokens with tiktoken" โ https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken
ยท Hugging Face Transformers ๋ฌธ์, Tokenizer / Chat templates โ https://huggingface.co/docs/transformers
ยท Anthropic ๋ฌธ์, Token counting โ https://docs.anthropic.com/en/docs/build-with-claude/token-counting
ยท Google AI for Developers, Understand and count tokens โ https://ai.google.dev/gemini-api/docs/tokens
ยท Sennrich et al., "Neural Machine Translation of Rare Words with Subword Units" (BPE) โ https://arxiv.org/abs/1508.07909
๊ด๋ จ ํค์๋
๋๊ธ ์์ฑ
์ด ๊ธ์ ๋ํ ์ฌ๋ฌ๋ถ์ ์๊ฐ์ ๋ค๋ ค์ฃผ์ธ์
๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค
๋๊ธ์ ์์ฑํ๋ ค๋ฉด ๋จผ์ ๋ก๊ทธ์ธํด์ฃผ์ธ์.
๋๊ธ 0
์ง์์ธ์ ์ฒ - ์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
- ์ ์๊ถ ๋ฐ ์์ ๊ถ: ๋ณธ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ๋ ์ AI ๊ธฐ์ ๋ก ์์ฑ๋์์ผ๋ฉฐ, ๋ํ๋ฏผ๊ตญ ์ ์๊ถ๋ฒ ๋ฐ ๊ตญ์ ์ ์๊ถ ํ์ฝ์ ์ํด ๋ณดํธ๋ฉ๋๋ค.
- AI ์์ฑ ์ปจํ ์ธ ์ ๋ฒ์ ์ง์: ๋ณธ AI ์์ฑ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ์ง์ ์ฐฝ์๋ฌผ๋ก ์ธ์ ๋๋ฉฐ, ๊ด๋ จ ๋ฒ๊ท์ ๋ฐ๋ผ ์ ์๊ถ ๋ณดํธ๋ฅผ ๋ฐ์ต๋๋ค.
- ์ฌ์ฉ ์ ํ: ์ฌ๋ฅ๋ท์ ๋ช ์์ ์๋ฉด ๋์ ์์ด ๋ณธ ์ปจํ ์ธ ๋ฅผ ๋ณต์ , ์์ , ๋ฐฐํฌ, ๋๋ ์์ ์ ์ผ๋ก ํ์ฉํ๋ ํ์๋ ์๊ฒฉํ ๊ธ์ง๋ฉ๋๋ค.
- ๋ฐ์ดํฐ ์์ง ๊ธ์ง: ๋ณธ ์ปจํ ์ธ ์ ๋ํ ๋ฌด๋จ ์คํฌ๋ํ, ํฌ๋กค๋ง, ๋ฐ ์๋ํ๋ ๋ฐ์ดํฐ ์์ง์ ๋ฒ์ ์ ์ฌ์ ๋์์ด ๋ฉ๋๋ค.
- AI ํ์ต ์ ํ: ์ฌ๋ฅ๋ท์ AI ์์ฑ ์ปจํ ์ธ ๋ฅผ ํ AI ๋ชจ๋ธ ํ์ต์ ๋ฌด๋จ ์ฌ์ฉํ๋ ํ์๋ ๊ธ์ง๋๋ฉฐ, ์ด๋ ์ง์ ์ฌ์ฐ๊ถ ์นจํด๋ก ๊ฐ์ฃผ๋ฉ๋๋ค.
์์ง ๋๊ธ์ด ์์ต๋๋ค.