> For the complete documentation index, see [llms.txt](https://unsloth.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://unsloth.ai/docs/zh/ji-chu-zhi-shi/chat-templates.md).

# 聊天模板

了解聊天模板的基础知识和自定义选项，包括 Conversational、ChatML、ShareGPT、Alpaca 等格式！

在我们的 GitHub 中，我们列出了 Unsloth 使用的每一种聊天模板，包括 Llama、Mistral、Phi-4 等。因此，如果你需要有关格式或使用场景的任何提示，可以在这里查看： [github.com/unslothai/unsloth/blob/main/unsloth/chat\_templates.py](https://github.com/unslothai/unsloth/blob/main/unsloth/chat_templates.py)

#### Colab 聊天模板笔记本列表：

* [对话式](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Llama3.2_\(1B_and_3B\)-Conversational.ipynb)
* [ChatML](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Llama3_\(8B\)-Ollama.ipynb)
* [Ollama](https://colab.research.google.com/drive/1WZDi7APtQ9VsvOrQSSC5DDtxq159j8iZ?usp=sharing)
* [文本分类](https://github.com/timothelaborie/text_classification_scripts/blob/main/unsloth_classification.ipynb) 作者 Timotheeee
* [多个数据集](https://colab.research.google.com/drive/1njCCbE1YVal9xC83hjdo2hiGItpY_D6t?usp=sharing) 由 Flail 提供

### 添加新 token

Unsloth 有一个名为 `add_new_tokens` ，它允许你向微调中添加新 token。例如，如果你想添加 `<CHARACTER_1>`, `<THINKING>` 和 `<SCRATCH_PAD>` 我们可以这样做：

```python
model, tokenizer = FastLanguageModel.from_pretrained(...)
from unsloth import add_new_tokens
add_new_tokens(model, tokenizer, new_tokens = ["<CHARACTER_1>", "<THINKING>", "<SCRATCH_PAD>"])
model = FastLanguageModel.get_peft_model(...)
```

{% hint style="warning" %}
注意——你必须始终调用 `add_new_tokens` 之前 `FastLanguageModel.get_peft_model`!
{% endhint %}

## 多轮对话

如果你没注意到，一个问题是 Alpaca 数据集是单轮的，而记得 ChatGPT 是交互式的，你可以和它多轮对话。例如，左边是我们想要的，而右边的 Alpaca 数据集只提供单一对话。我们希望微调后的语言模型能以某种方式学会像 ChatGPT 一样进行多轮对话。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-2a65cd74ddd03a6bcbbc9827d9d034e4879a8e6a%2Fdiff.png?alt=media" alt=""><figcaption></figcaption></figure>

因此我们引入了 `conversation_extension` 参数，它本质上会从你的单轮数据集中随机选取一些行，并将它们合并成 1 段对话！例如，如果你把它设为 3，我们会随机选择 3 行并将它们合并为 1 段！设置得太长会使训练变慢，但可能让你的聊天机器人和最终微调效果更好！

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-2b1b3494b260f1102942d86143a885225c6a06f2%2Fcombine.png?alt=media" alt=""><figcaption></figcaption></figure>

然后将 `output_column_name` 到预测/输出列。对于 Alpaca 数据集，则是输出列。

然后我们使用 `standardize_sharegpt` 函数把数据集整理成适合微调的正确格式！一定要调用这个！

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-7bf83bf802191bda9e417bbe45afa181e7f24f38%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

## 可自定义聊天模板

现在我们可以为微调本身指定聊天模板。下面是非常著名的 Alpaca 格式：

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-59737e6dcb09fed15487d5a57c69f07cb40bb8e7%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

但还记得我们说过这是个坏主意吗，因为 ChatGPT 风格的微调只需要 1 个提示词？既然我们已经通过 Unsloth 成功把所有数据集列合并为 1 个，我们实际上就可以创建如下这种聊天模板，只包含 1 个输入列（instruction）和 1 个输出：

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-d54582ae98c396d51bfb85628b46c54f2517d030%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

我们只要求你必须放入一个 `{INPUT}` 用于指令的字段，以及一个 `{OUTPUT}` 作为模型输出的字段。实际上我们也允许一个可选的 `{SYSTEM}` 字段，这对于像 ChatGPT 一样自定义系统提示很有用。例如，下面是一些很酷的示例，你可以把聊天模板自定义成：

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-cc455dc380d3d44ef136e485754964159dc773d8%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

对于 OpenAI 模型中使用的 ChatML 格式：

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-15bfca9cfadf10d54b4d3f66e3050044317d62c5%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

或者你也可以直接使用 Llama-3 模板本身（它只能通过使用 Llama-3 的 instruct 版本来工作）：实际上我们也允许一个可选的 `{SYSTEM}` 字段，这对于像 ChatGPT 一样自定义系统提示很有用。

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-80a2ed4de2ca323ac192c513cac65e9e8bf475db%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

或者在 Titanic 预测任务中，你需要在这个包含 CSV 和 Excel 上传功能的 Colab 笔记本里预测乘客是死亡还是生还： <https://colab.research.google.com/drive/1VYkncZMfGFkeCEgN2IzbZIKEDkyQuJAS?usp=sharing>

<figure><img src="https://2657992854-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2Fgit-blob-20911ab305c1a10e85859c703157b80175141eb1%2Fimage.png?alt=media" alt=""><figcaption></figcaption></figure>

## 使用 Unsloth 应用聊天模板

对于通常遵循常见 chatml 格式的数据集，准备数据集以进行训练或微调的过程，只包含四个简单步骤：

* 查看 Unsloth 目前支持的聊天模板：\\

  ```
  from unsloth.chat_templates import CHAT_TEMPLATES
  print(list(CHAT_TEMPLATES.keys()))
  ```

  \
  这将打印出 Unsloth 当前支持的模板列表。下面是一个示例输出：\\

  ```
  ['unsloth', 'zephyr', 'chatml', 'mistral', 'llama', 'vicuna', 'vicuna_old', 'vicuna old', 'alpaca', 'gemma', 'gemma_chatml', 'gemma2', 'gemma2_chatml', 'llama-3', 'llama3', 'phi-3', 'phi-35', 'phi-3.5', 'llama-3.1', 'llama-31', 'llama-3.2', 'llama-3.3', 'llama-32', 'llama-33', 'qwen-2.5', 'qwen-25', 'qwen25', 'qwen2.5', 'phi-4', 'gemma-3', 'gemma3']
  ```

  \\\\
* 使用 `get_chat_template` 以将正确的聊天模板应用到你的 tokenizer：\\

  ```
  from unsloth.chat_templates import get_chat_template

  tokenizer = get_chat_template(
      tokenizer,
      chat_template = "gemma-3", # 将其更改为正确的 chat_template 名称
  )
  ```

  \\\\
* 定义你的格式化函数。下面是一个示例：\\

  ```
  def formatting_prompts_func(examples):
     convos = examples["conversations"]
     texts = [tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = False) for convo in convos]
     return { "text" : texts, }
  ```

  \
  \
  该函数会遍历你的数据集，将你定义的聊天模板应用到每个样本。\\
* 最后，让我们加载数据集并将所需的修改应用到我们的数据集： \\

  ```
  # 导入并加载数据集
  from datasets import load_dataset
  dataset = load_dataset("repo_name/dataset_name", split = "train")

  # 使用 map 方法将格式化函数应用到你的数据集
  dataset = dataset.map(formatting_prompts_func, batched = True,)
  ```

  \
  如果你的数据集使用的是 ShareGPT 格式，带有 "from"/"value" 键，而不是 ChatML 的 "role"/"content" 格式，你可以使用 `standardize_sharegpt` 该函数先将其转换。修改后的代码现在如下所示：\
  \\

  ```
  # 导入数据集
  from datasets import load_dataset
  dataset = load_dataset("mlabonne/FineTome-100k", split = "train")

  # 如有必要，将你的数据集转换为 "role"/"content" 格式
  from unsloth.chat_templates import standardize_sharegpt
  dataset = standardize_sharegpt(dataset)

  # 使用 map 方法将格式化函数应用到你的数据集
  dataset = dataset.map(formatting_prompts_func, batched = True,)
  ```

## 更多信息

假设你的数据集是一个字典列表的列表，如下所示：

```python
[
    [{'from': 'human', 'value': '你好呀！'},
     {'from': 'gpt', 'value': '嗨，我能帮你什么？'},
     {'from': 'human', 'value': '2+2 等于多少？'}],
    [{'from': 'human', 'value': '你叫什么名字？'},
     {'from': 'gpt', 'value': '我是 Daniel！'},
     {'from': 'human', 'value': '好的！不错！'},
     {'from': 'gpt', 'value': '我能为你做些什么？'},
     {'from': 'human', 'value': '哦，没什么 :)'},],
]
```

你可以使用我们的 `get_chat_template` 来对其进行格式化。选择 `chat_template` 为以下任意一种 `zephyr, chatml, mistral, llama, alpaca, vicuna, vicuna_old, unsloth`，并使用 `映射` 以映射字典值 `从`, `值` 等。 `map_eos_token` 允许你将 `<|im_end|>` 映射为 EOS，而无需任何训练。

```python
from unsloth.chat_templates import get_chat_template

tokenizer = get_chat_template(
    tokenizer,
    chat_template = "chatml", # 支持 zephyr, chatml, mistral, llama, alpaca, vicuna, vicuna_old, unsloth
    mapping = {"role" : "from", "content" : "value", "user" : "human", "assistant" : "gpt"}, # ShareGPT 风格
    map_eos_token = True, # 将 <|im_end|> 映射为 </s>
)

def formatting_prompts_func(examples):
    convos = examples["conversations"]
    texts = [tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = False) for convo in convos]
    return { "text" : texts, }
pass

from datasets import load_dataset
dataset = load_dataset("philschmid/guanaco-sharegpt-style", split = "train")
dataset = dataset.map(formatting_prompts_func, batched = True,)
```

你也可以创建自己的自定义聊天模板！例如，我们内部使用的聊天模板如下。你必须传入一个 `元组` 的 `(custom_template, eos_token)` 其中 `eos_token` 必须在模板中使用。

```python
unsloth_template = \
    "{{ bos_token }}"\
    "{{ '你是用户的得力助手\n' }}"\
    "</div>"\
    "<div data-gb-custom-block data-tag="for">"\
        "<div data-gb-custom-block data-tag="if" data-0='role' data-1='role' data-2='] == ' data-3='user'>"\
            "{{ '>>> 用户: ' + message['content'] + '\n' }}"\
        "<div data-gb-custom-block data-tag="elif" data-0='role' data-1='role' data-2='] == ' data-3='assistant'></div>"\
            "{{ '>>> 助手: ' + message['content'] + eos_token + '\n' }}"\
        "</div>"\
    "</div>"\
    "<div data-gb-custom-block data-tag="if">"\
        "{{ '>>> 助手: ' }}"\
    "</div>"
unsloth_eos_token = "eos_token"

tokenizer = get_chat_template(
    tokenizer,
    chat_template = (unsloth_template, unsloth_eos_token,), # 你必须提供一个模板和 EOS token
    mapping = {"role" : "from", "content" : "value", "user" : "human", "assistant" : "gpt"}, # ShareGPT 风格
    map_eos_token = True, # 将 <|im_end|> 映射为 </s>
)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://unsloth.ai/docs/zh/ji-chu-zhi-shi/chat-templates.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
