A language model does not see "messages." It sees one long stream of tokens. A chat template is the recipe that converts your conversation into that stream, adding the special markers the model was trained to expect.
What it does
When you type a question into a chat app, the app has three kinds of text: a system prompt, your messages and the model's earlier replies. The chat template says how to stitch them together. It decides which marker opens a user turn, which closes it, where the system prompt goes, and how to signal "now the assistant speaks."
Think of it as a form letter layout. The words change every time, but the letterhead, greeting and signature sit in the same places. A model trained on one layout gets confused by another, so using the wrong template quietly makes answers worse.
Where it lives
Most open models ship the template inside their files. In the Hugging Face ecosystem it is a small program written in the Jinja templating language and stored with the tokenizer. Libraries call a function such as apply_chat_template to run it. Single-file formats like GGUF embed the template in the file's metadata, so runtimes such as llama.cpp and Ollama can pick it up automatically.
Because it is a program, not just a label, a template can contain logic: loops over messages, conditions for tool calls, even extra text inserted into every prompt.
Why it matters to you
First, correctness. A mismatched template is one of the most common reasons a freshly downloaded model seems "dumber" than advertised.
Second, trust. The template runs on every prompt before the model sees it, and you rarely read it. Anything it adds, such as hidden instructions, reaches the model as if you had typed it. That makes a template a place where a prompt injection can ride along inside a model file, which is why careful teams review the template of any model they did not build, or override it with a template they wrote.
A quick example
Given the messages "You are concise" (system) and "Hi" (user), one template might produce text like a system block, a user block and then an open assistant block waiting for the model to fill in. A different model family uses different markers for the same conversation.
A chat template shapes the input the way structured output shapes the output. Both are about making the model's text predictable. When you run models yourself through local inference, the template is part of the model you are trusting, along with the model weights.