Same topic, related formats. Practice these next.
Same topic, related formats. Practice these next.
Click any words you think contain an error. Click again to unmark.
The code slices by characters but promises a token limit. Tokens are not characters, so 100 chars can be 20 or 200 tokens. Fix: encode, slice IDs, decode.
Imagine a recipe says 'use the first 100 ingredients' but you instead grab the first 100 letters off the ingredient labels. Some ingredients have short names, some have long ones, so you end up with a wildly different number than 100 ingredients. That is this bug. A token is more like a whole ingredient than a single letter. The word 'hello' is five letters but one token, while a long rare word might be many tokens. So cutting at letter 100 gives you an unpredictable number of tokens. The fix is to first turn the text into a list of token numbers, then keep the first 100 numbers, then turn them back into text.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example. Click to expand.
Everything you need to truly understand this topic: intuition, mechanics, step by step explanation, code, formulas, and worked example.
Everything important, quickly.
2 min: char slice vs token limit + ratio varies by content + encode slice decode fix + Unicode boundary failure + RAG chunking context.
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("meta-llama/Meta-Llama-3-8B")
# Buggy: character slice does not respect a token limit
def truncate_wrong(text: str, limit: int = 100) -> str:
return text[:limit]
# Correct: encode, slice the ID array, decode
def truncate_to_token_limit(text: str, limit: int = 100) -> str:
ids = tok.encode(text, add_special_tokens=False)
return tok.decode(ids[:limit], skip_special_tokens=True)
for t in ["Hello world! " * 10, "def f(x):return x*2\n" * 6, "这是中文测试" * 5]:
ids = tok.encode(t, add_special_tokens=False)
print(len(t), len(ids), round(len(ids) / len(t), 2))Real products, models, and research that use this idea.
What an interviewer would ask next. Try answering before peeking at the approach.
Red flags and common mistakes that signal junior thinking. Click to expand.
Assuming roughly 4 characters per token as a safe universal rule. It holds for English prose but fails for code (often 2:1) and non-Latin scripts (can be far worse).
The night-before-the-interview bullets. Scan these on the way to the call.
Primary sources. Skim if you want the original framing.