> 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/jp/ji-ben/chat-templates.md).

# チャットテンプレート

GitHub には、Llama、Mistral、Phi-4 などを含む、Unsloth が使用するすべてのチャットテンプレートの一覧があります。書式設定や使用例について何か手がかりが必要なら、こちらで確認できます: [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 による

### 新しいトークンの追加

Unsloth には次の名前の関数があります `add_new_tokens` これを使うと、ファインチューニングに新しいトークンを追加できます。例えば、次を追加したい場合は `<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="/files/850bbe22af1e6e8304e5a34a7fcc08915e34f02d" alt=""><figcaption></figcaption></figure>

そこで私たちは `conversation_extension` パラメータを導入しました。これは本質的に、シングルターンのデータセットからランダムな行をいくつか選び、それらを1つの会話に結合するものです！たとえば 3 に設定すると、3行をランダムに選んで1つに結合します！長くしすぎると学習は遅くなりますが、チャットボットや最終的なファインチューニング結果がずっと良くなる可能性があります！

<figure><img src="/files/c7fae704073c784115a78c6a0a88d4d51544ec66" alt=""><figcaption></figcaption></figure>

次に `output_column_name` 予測 / 出力列に。Alpaca データセットでは、出力列になります。

その後、 `standardize_sharegpt` 関数を使って、ファインチューニングに正しい形式へデータセットを整えます！必ずこれを呼び出してください！

<figure><img src="/files/323f5402e3bc525f250606d1195dfb6003af0972" alt=""><figcaption></figcaption></figure>

## カスタマイズ可能なチャットテンプレート

これで、ファインチューニング自体のチャットテンプレートを指定できます。非常に有名な Alpaca 形式は以下です:

<figure><img src="/files/6f4e805ad43a082898ae0748207b9063cd25dc96" alt=""><figcaption></figcaption></figure>

ですが、ChatGPT 風のファインチューニングでは1つのプロンプトだけが必要なので、これは良くないアイデアだと言いましたよね？Unsloth を使ってすべてのデータセット列を1つに結合することに成功したので、基本的に以下のような、1つの入力列（instruction）と1つの出力を持つスタイルのチャットテンプレートを作成できます:

<figure><img src="/files/c5f14641763f9e63a90f419c72d192c69762f478" alt=""><figcaption></figcaption></figure>

必要なのは、 `{INPUT}` というフィールドを instruction 用に置き、さらに `{OUTPUT}` というフィールドをモデルの出力用に置くことだけです。実際には、オプションの `{SYSTEM}` フィールドも利用可能で、これは ChatGPT のようにシステムプロンプトをカスタマイズするのに便利です。たとえば、以下はチャットテンプレートをカスタマイズできるクールな例です:

<figure><img src="/files/687d676ea536236df884fa1b12c1428d31be8bee" alt=""><figcaption></figcaption></figure>

OpenAI モデルで使われる ChatML 形式の場合:

<figure><img src="/files/c9223bc2b837190a9cb35263c896600a002d9940" alt=""><figcaption></figcaption></figure>

あるいは、Llama-3 自体のテンプレートも使えます（これは Llama-3 の instruct 版を使う場合にのみ機能します）: 実際には、オプションの `{SYSTEM}` フィールドも利用可能で、これは ChatGPT のようにシステムプロンプトをカスタマイズするのに便利です。

<figure><img src="/files/9cfeed7201c3c9f176d70d003b115d79717f75f9" alt=""><figcaption></figcaption></figure>

または、CSV と Excel のアップロードを含むこの Colab ノートブックで、乗客が死亡したか生存したかを予測する必要がある Titanic 予測タスクでは: <https://colab.research.google.com/drive/1VYkncZMfGFkeCEgN2IzbZIKEDkyQuJAS?usp=sharing>

<figure><img src="/files/c9c464e78567cb68c6de823fb57599bd62d7c79e" alt=""><figcaption></figcaption></figure>

## Unsloth を使ったチャットテンプレートの適用

通常 ChatML 形式に従うデータセットでは、学習やファインチューニングのためにデータセットを準備する手順は、4 つの簡単なステップで構成されます:

* 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,)
  ```

  \
  データセットが ChatML の "role"/"content" 形式ではなく "from"/"value" キーを使う ShareGPT 形式である場合は、まず `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`、そして `mapping` を使って辞書の値を対応付けます `from`, `value` などを使います。 `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 }}"\
    "{{ 'You are a helpful assistant to the user\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'>"\
            "{{ '>>> User: ' + message['content'] + '\n' }}"\
        "<div data-gb-custom-block data-tag="elif" data-0='role' data-1='role' data-2='] == ' data-3='assistant'></div>"\
            "{{ '>>> Assistant: ' + message['content'] + eos_token + '\n' }}"\
        "</div>"\
    "</div>"\
    "<div data-gb-custom-block data-tag="if">"\
        "{{ '>>> Assistant: ' }}"\
    "</div>"
unsloth_eos_token = "eos_token"

tokenizer = get_chat_template(
    tokenizer,
    chat_template = (unsloth_template, unsloth_eos_token,), # テンプレートと EOS トークンの両方を指定する必要があります
    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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://unsloth.ai/docs/jp/ji-ben/chat-templates.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
