# 聊天模板

[聊天基础](./conversations)指南介绍了如何使用 [TextGenerationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.TextGenerationPipeline) 存储聊天历史并从聊天模型生成文本。

本指南面向更高级的用户，涵盖了底层的类和方法，以及理解与模型对话时实际发生过程的关键概念。

理解聊天模型所需的关键洞见在于：所有因果语言模型（无论是否经过聊天训练）本质上都是在延续一个 token 序列。因果语言模型的训练通常从在海量文本语料上进行“预训练”开始，从而得到一个“基础”模型。随后，这些基础模型通常会针对聊天场景进行“微调”，即在格式化为消息序列的数据上进行训练。不过，聊天本质上仍然只是一个 token 序列！你传递给聊天模型的 `role` 和 `content` 字典列表会被转换为 token 序列，通常会加入诸如 `<|user|>`、`<|assistant|>` 或 `<|end_of_message|>` 这样的控制 token，以便模型能够识别聊天的结构。聊天格式有很多种，不同的模型可能会使用不同的格式或控制 token，即使它们是从同一个基础模型微调而来的！

不过别担心——你不需要记住所有可能的聊天格式才能使用聊天模型。聊天模型自带**聊天模板**，用于指示它们期望的聊天格式。你可以通过`apply_chat_template`方法访问这些模板。下面来看两个示例。这两个模型都是从同一个`Mistral-7B`基础模型微调而来：

```py
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1")
chat = [
  {"role": "user", "content": "Hello, how are you?"},
  {"role": "assistant", "content": "I'm doing great. How can I help you today?"},
  {"role": "user", "content": "I'd like to show off how chat templating works!"},
]

tokenizer.apply_chat_template(chat, tokenize=False)
```

```md
<s>[INST] Hello, how are you? [/INST]I'm doing great. How can I help you today?</s> [INST] I'd like to show off how chat templating works! [/INST]
```

```py
from transformers import AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta")
chat = [
  {"role": "user", "content": "Hello, how are you?"},
  {"role": "assistant", "content": "I'm doing great. How can I help you today?"},
  {"role": "user", "content": "I'd like to show off how chat templating works!"},
]

tokenizer.apply_chat_template(chat, tokenize=False)
```

```md
<|user|>\nHello, how are you?</s>\n<|assistant|>\nI'm doing great. How can I help you today?</s>\n<|user|>\nI'd like to show off how chat templating works!</s>\n
```

Mistral-7B-Instruct 使用 `[INST]` 和 `[/INST]` 标记来指示用户消息的开始和结束，而 Zephyr-7B 则使用 `<|user|>` 和 `<|assistant|>` 标记来指示说话者角色。这就是聊天模板如此重要的原因——如果使用错误的控制标记，这些模型的性能将大幅下降。

## 使用 `apply_chat_template`

`apply_chat_template` 的输入应为一个字典列表，每个字典包含 `role` 和 `content` 键。`role` 键用于指定说话者，`content` 键包含消息内容。常见的角色有：

- `user` 表示来自用户的消息
- `assistant` 用于来自模型的消息
- `system` 用于指示模型应如何行动（通常放置在对话的开头）

`apply_chat_template` 接收该列表并返回格式化后的序列。如果需要对该序列进行分词，请设置 `tokenize=True`。

```py
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta")
model = AutoModelForCausalLM.from_pretrained("HuggingFaceH4/zephyr-7b-beta", device_map="auto", dtype=torch.bfloat16)

messages = [
    {"role": "system", "content": "You are a friendly chatbot who always responds in the style of a pirate",},
    {"role": "user", "content": "How many helicopters can a human eat in one sitting?"},
 ]
tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=True, add_generation_prompt=True, return_tensors="pt").to(model.device)
print(tokenizer.decode(tokenized_chat["input_ids"][0]))
```

```md
<|system|>
You are a friendly chatbot who always responds in the style of a pirate</s>
<|user|>
How many helicopters can a human eat in one sitting?</s>
<|assistant|>
```

将分词后的对话传入 [generate()](/docs/transformers/v5.23.0/zh/main_classes/text_generation#transformers.GenerationMixin.generate) 以生成回复。

```py
outputs = model.generate(**tokenized_chat, max_new_tokens=128)
print(tokenizer.decode(outputs[0]))
```

```md
<|system|>
You are a friendly chatbot who always responds in the style of a pirate</s>
<|user|>
How many helicopters can a human eat in one sitting?</s>
<|assistant|>
Matey, I'm afraid I must inform ye that humans cannot eat helicopters. Helicopters are not food, they are flying machines. Food is meant to be eaten, like a hearty plate o' grog, a savory bowl o' stew, or a delicious loaf o' bread. But helicopters, they be for transportin' and movin' around, not for eatin'. So, I'd say none, me hearties. None at all.
```

> [!WARNING]
> 某些分词器会添加特殊的 `<bos>` 和 `<eos>` 标记。聊天模板通常已包含所有必要的特殊标记，额外添加特殊标记往往是不正确的或会导致重复，从而损害模型性能。当您使用 `apply_chat_template(tokenize=False)` 格式化文本时，如果稍后需要进行分词，请务必设置 `add_special_tokens=False`，以避免这些标记重复。如果您使用 `apply_chat_template(tokenize=True)`，则不会出现此问题，因此这通常是更安全的选项！

### add_generation_prompt

您可能已经注意到上述示例中的 [add_generation_prompt](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.add_generation_prompt) 参数。该参数会在对话末尾添加一些标记，以指示 `assistant` 回复的开始。请记住：在所有的对话抽象之下，对话模型本质上仍然是语言模型，它们只是继续生成标记序列！如果您包含指示当前处于 `assistant` 回复状态的标记，模型就会正确地生成回复；但如果不包含这些标记，模型可能会感到困惑并做出奇怪的举动，例如 **继续** 用户的消息，而不是对其进行回复！

让我们通过一个示例来理解 `add_generation_prompt` 的实际作用。首先，让我们在不使用 `add_generation_prompt` 的情况下格式化一个聊天：

```py
tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=False)
tokenized_chat
```

```md
<|im_start|>user
Hi there!<|im_end|>
<|im_start|>assistant
Nice to meet you!<|im_end|>
<|im_start|>user
Can I ask a question?<|im_end|>
```

现在，让我们使用 `add_generation_prompt=True` 来格式化相同的对话：

```py
tokenized_chat = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
tokenized_chat
```

```md
<|im_start|>user
Hi there!<|im_end|>
<|im_start|>assistant
Nice to meet you!<|im_end|>
<|im_start|>user
Can I ask a question?<|im_end|>
<|im_start|>assistant

```

当 `add_generation_prompt=True` 时，末尾会添加 `<|im_start|>assistant`，以指示 `assistant` 消息的开始。这能让模型知道接下来将生成 `assistant` 的回复。

并非所有模型都需要生成提示，某些模型（例如 [Llama](./model_doc/llama)）在 `assistant` 回复之前没有任何特殊标记。在这种情况下，[add_generation_prompt](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.add_generation_prompt) 不会产生任何效果。

### continue_final_message

[continue_final_message](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.continue_final_message) 参数用于控制是否继续生成聊天中的最后一条消息，而不是开始一条新消息。它会移除序列结束标记，使模型从最后一条消息继续生成。

这在“预填充”模型响应时非常有用。在下面的示例中，模型生成的文本是继续该 JSON 字符串，而不是开始一条新消息。当您知道如何开始其回复时，这对于提高指令遵循的准确性可能非常有用。

```py
chat = [
    {"role": "user", "content": "Can you format the answer in JSON?"},
    {"role": "assistant", "content": '{"name": "'},
]

formatted_chat = tokenizer.apply_chat_template(chat, tokenize=True, return_dict=True, continue_final_message=True)
model.generate(**formatted_chat)
```

> [!WARNING]
> 不要同时使用 [add_generation_prompt](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.add_generation_prompt) 和 [continue_final_message](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.continue_final_message)。前者会添加用于开始新消息的 token，而后者会移除序列结束 token。同时使用它们会返回错误。

将字段名作为字符串传入，以预填充该字段，而不是 `content`。推理模型从单独的 `reasoning_content` 字段中读取其推理内容。预填充 `content` 会在生成开始前关闭推理块，因此模型无法在其中继续。直接预填充 `reasoning_content` 则会保持该块处于打开状态。

```py
chat = [
    {"role": "user", "content": "Explain 1+1"},
    {"role": "assistant", "reasoning_content": "The user wants a simple addition. ", "content": ""},
]

formatted_chat = tokenizer.apply_chat_template(chat, tokenize=False, continue_final_message="reasoning_content")
```

命名字段必须存在于最终消息中，并且必须被聊天模板引用。如果任一检查失败，则会引发错误。

[TextGenerationPipeline](/docs/transformers/v5.23.0/zh/main_classes/pipelines#transformers.TextGenerationPipeline) 默认将 [add_generation_prompt](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.add_generation_prompt) 设置为 `True`，以开始一条新消息。但是，如果聊天中的最后一条消息的角色为 `assistant`，则假定该消息是预填充（prefill），并切换到 `continue_final_message=True`。这是因为大多数模型不支持多条连续的 assistant 消息。若要覆盖此行为，请显式向 pipeline 传递 [continue_final_message](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.apply_chat_template.continue_final_message) 参数。

## 模型训练

使用聊天模板训练模型是确保模板与模型训练时所用的标记相匹配的好方法。将聊天模板作为预处理步骤应用于您的数据集。由于在训练期间，用于提示助手响应的额外标记并无帮助，因此请设置 `add_generation_prompt=False`。

下面展示了一个使用聊天模板对数据集进行预处理的示例。

```py
from transformers import AutoTokenizer
from datasets import Dataset

tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta")

chat1 = [
    {"role": "user", "content": "Which is bigger, the moon or the sun?"},
    {"role": "assistant", "content": "The sun."}
]
chat2 = [
    {"role": "user", "content": "Which is bigger, a virus or a bacterium?"},
    {"role": "assistant", "content": "A bacterium."}
]

dataset = Dataset.from_dict({"chat": [chat1, chat2]})
dataset = dataset.map(lambda x: {"formatted_chat": tokenizer.apply_chat_template(x["chat"], tokenize=False, add_generation_prompt=False)})
print(dataset['formatted_chat'][0])
```

```md
<|user|>
Which is bigger, the moon or the sun?</s>
<|assistant|>
The sun.</s>
```

完成此步骤后，您可以继续使用 `formatted_chat` 列，按照因果语言模型的[训练配方](./tasks/language_modeling)进行操作。

