> 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-chu/chat-templates.md).

# チャットテンプレート

Conversational、ChatML、ShareGPT、Alpaca 形式などを含む、チャットテンプレートの基本とカスタマイズ方法を学びます！

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データセットは1ターンのみです。一方で、ChatGPTを使うと対話形式で複数ターン会話ができました。たとえば、左側が私たちの求めるものですが、右側のAlpacaデータセットは単発の会話しか提供しません。ファインチューニングした言語モデルには、ChatGPTのように複数ターン会話をどうやって行うかを何とか学んでほしいのです。

<figure><img src="https://735611837-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://735611837-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 データセットでは、これは output 列になります。

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

<figure><img src="https://735611837-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://735611837-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://735611837-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://735611837-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://735611837-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://735611837-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>

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

<figure><img src="https://735611837-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 形式に従うデータセットでは、トレーニングまたはファインチューニングのためにデータセットを準備する手順は、次の 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` トークナイザに正しいチャットテンプレートを適用するには:\\

  ```
  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': '人間', 'value': 'やあ！'},
     {'from': 'GPT', 'value': 'やあ、どうお手伝いできますか？'},
     {'from': '人間', 'value': '2+2 はいくつですか？'}],
    [{'from': '人間', 'value': 'あなたの名前は何ですか？'},
     {'from': 'GPT', 'value': '私は Daniel です！'},
     {'from': '人間', 'value': 'いいね！'},
     {'from': 'GPT', 'value': '何をお手伝いできますか？'},
     {'from': '人間', '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 }}"\
    "{{ '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'>"\
            "{{ '>>> ユーザー: ' + 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 トークンの両方を指定する必要があります
    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/jp/ji-chu/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.
