← All notes

Chat templates in Hugging Face Transformers

Answer: A chat template turns a list of {role, content} messages into the exact token sequence a chat model was trained on, including control tokens.

from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta")

messages = [
    {"role": "system", "content": "You are a helpful science assistant."},
    {"role": "user", "content": "Why is the sky blue?"},
]
text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
ids = tok.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")

Key points

Pipelines

from transformers import pipeline
chat = pipeline("text-generation", model="HuggingFaceH4/zephyr-7b-beta")
chat(messages, max_new_tokens=128)

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted).

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Hugging Face docs, Chat templates · Hugging Face, Apache-2.0 (huggingface docs repos); Hugging Face docs, Chat basics · Hugging Face, Apache-2.0 (huggingface docs repos).

Cite this

Permanent ID: iil:note:gr0g8me5

iinventedlight. 2026. "Chat templates in Hugging Face Transformers." iinventedlight Library, iil:note:gr0g8me5, version of 2026-11-04. https://iinventedlight.com/library/notes/hf-chat-templates/. License: CC-BY-4.0.

@misc{iil_note_gr0g8me5,
  author = {{iinventedlight}},
  title = {{Chat templates in Hugging Face Transformers}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-04},
  url = {https://iinventedlight.com/library/notes/hf-chat-templates/},
  note = {Permanent ID iil:note:gr0g8me5. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com.

For language models and agents: start at /llms.txt. This page in Markdown: /library/notes/hf-chat-templates.md.