A chat is a list of messages, from different speakers. But a model only reads one long string of tokens. So how does a conversation become one piece of text? With a chat template.
We write a conversation as a list of messages. Each message has a role, and some content. The system role sets the rules, like who the assistant is. The user role is the person asking. And the assistant role is the model's reply.
Here's a short conversation. A system message, and a user question. Apply chat template turns it into text. Tokenize equals false gives us text, not IDs, so we can read it. Add generation prompt adds the start of the assistant's turn. Run it. Each message is wrapped in i m start and i m end tokens, with its role. And it ends with the assistant's turn, open, ready for the model to write.
app.pypython
from transformers import AutoTokenizertok = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct")messages = [{"role": "system", "content": "You help customers of Riverside Books."}, {"role": "user", "content": "Is Dune in stock?"}]text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)print(text)
Output
<|im_start|>system
You help customers of Riverside Books.<|im_end|>
<|im_start|>user
Is Dune in stock?<|im_end|>
<|im_start|>assistant
Here's the key point. A model was trained with one exact template. If you use a different one, it gets confused. So when we fine-tune, we always format our examples with the model's own chat template. Luckily, the tokenizer does this for us.
Let's recap. A chat is a list of messages, with roles. The chat template turns them into one string, with special tokens. And we must always use the model's own template. Next, how much memory a model needs.