Modelfile Prompt Templates

Customize the Modelfile TEMPLATE directive and control tokens so a model's chat format works correctly.

TL;DR

  1. TEMPLATE controls the exact prompt sent to the model.
  2. Insert content with .System, .Prompt, and .Response variables.
  3. Match control tokens like <|im_end|> to the model's format.

The TEMPLATE Directive

    TEMPLATE

    Define the full prompt string sent to the model.

    TEMPLATE """{{ .Prompt }}"""
    .System

    Insert the system prompt into the template.

    {{ if .System }}{{ .System }}{{ end }}
    .Prompt

    Insert the user's message into the template.

    {{ .Prompt }}
    .Response

    Marks where the model's reply begins.

    {{ .Response }}

Control Tokens

    Special Tokens

    Models use tokens to mark turn boundaries.

    <|im_start|>user
    {{ .Prompt }}<|im_end|>
    Match Training

    Use the exact tokens the model was trained on.

    # Wrong tokens break the chat format
    Stop Sequences

    Set a stop token so generation ends cleanly.

    PARAMETER stop "<|im_end|>"

A Full Template

    System Block

    Render the system prompt only when present.

    {{ if .System }}<|system|>
    {{ .System }}
    {{ end }}
    User Block

    Wrap the user prompt in the model's tags.

    <|user|>
    {{ .Prompt }}
    Assistant Tag

    End with the assistant tag to cue the reply.

    <|assistant|>

View And Edit

    Show Template

    Print the model's current Modelfile and template.

    ollama show llama3.2 --modelfile
    Edit And Rebuild

    Change the template, then rebuild the model.

    ollama create my-model -f Modelfile
    Test It

    Run the model and check the formatting.

    ollama run my-model "Say hi"

Tips

  1. Start from the model's official template with ollama show --modelfile, then edit that rather than writing a TEMPLATE from scratch.
  2. Keep any special control tokens exactly as the model was trained, since even a small change can break the chat format.

Warnings

  1. A broken TEMPLATE can make a model ramble, loop, or ignore the system prompt; verify the format before relying on the model.
  2. Text placed after .Response in a TEMPLATE is dropped during generation, so keep the assistant tag before that point.

In Practice

FAQ