Gemma 3 Chat Template

{# 
Block 1: System Message Handling and Loop Setup
(a) What this block is about: 
This block processes the initial system message if present, extracts its content (handling string or list formats), and sets up the loop messages by skipping the system if it exists. It prepares a prefix for the first user message and initializes variables for the conversation loop.
 
(b) What concretely each part is about:
- Check if first message is system: If yes, extracts content as prefix (string or first text item), sets loop_messages to start from second message.
- Else: Sets empty prefix, loop_messages to all messages.
#}
{{ bos_token }} {# Outputs the beginning-of-sequence token #}
{%- if messages[0]['role'] == 'system' -%} {# Checks if the first message is a system role #}
    {%- if messages[0]['content'] is string -%} {# If system content is a string #}
        {%- set first_user_prefix = messages[0]['content'] + '\n\n' -%} {# Sets prefix with content and newlines #}
    {%- else -%} {# If system content is not a string (e.g., list) #}
        {%- set first_user_prefix = messages[0]['content'][0]['text'] + '\n\n' -%} {# Extracts first text item as prefix #}
    {%- endif -%}
    {%- set loop_messages = messages[1:] -%} {# Skips system message for the loop #}
{%- else -%} {# No system message #}
    {%- set first_user_prefix = "" -%} {# Empty prefix #}
    {%- set loop_messages = messages -%} {# Uses all messages for the loop #}
{%- endif -%}
 
{# 
Block 2: Main Conversation Loop
(a) What this block is about: 
This block loops through the remaining messages, enforces alternating user/assistant roles, formats each message with <start_of_turn> and <end_of_turn> tokens, handles content types (string, iterable with text/image), and trims whitespace.
 
(b) What concretely each part is about:
- Role alternation check: Raises exception if roles don't alternate starting with user.
- Role mapping: Maps 'assistant' to 'model', keeps others.
- Output start: Adds <start_of_turn>role\n and prefix if first in loop.
- Content handling: If string, trims and outputs; if iterable, loops to handle 'text' (trim) or 'image' (<start_of_image>); else raises exception.
- End turn: Adds <end_of_turn>\n.
#}
{%- for message in loop_messages -%} {# Loops through prepared messages #}
    {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%} {# Ensures user/assistant alternation #}
        {{ raise_exception("Conversation roles must alternate user/assistant/user/assistant/...") }} {# Raises error on violation #}
    {%- endif -%}
    {%- if (message['role'] == 'assistant') -%} {# Maps assistant to model #}
        {%- set role = "model" -%}
    {%- else -%}
        {%- set role = message['role'] -%}
    {%- endif -%}
    {{ '<start_of_turn>' + role + '\n' + (first_user_prefix if loop.first else "") }} {# Starts turn with role and optional prefix #}
    {%- if message['content'] is string -%} {# If content is string #}
        {{ message['content'] | trim }} {# Trims and outputs #}
    {%- elif message['content'] is iterable -%} {# If content is iterable (multi-modal) #}
        {%- for item in message['content'] -%} {# Loops over items #}
            {%- if item['type'] == 'image' -%} {# Handles image type #}
                {{ '<start_of_image>' }} {# Outputs image marker #}
            {%- elif item['type'] == 'text' -%} {# Handles text type #}
                {{ item['text'] | trim }} {# Trims and outputs text #}
            {%- endif -%}
        {%- endfor -%}
    {%- else -%} {# Invalid content #}
        {{ raise_exception("Invalid content type") }} {# Raises error #}
    {%- endif -%}
    {{ '<end_of_turn>\n' }} {# Ends the turn #}
{%- endfor -%}
 
{# 
Block 3: Generation Prompt Addition
(a) What this block is about: 
This block conditionally adds a prompt to start the assistant's (model's) response if generation is requested.
 
(b) What concretely each part is about:
- Condition: If add_generation_prompt is true, outputs <start_of_turn>model\n to cue the next response.
#}
{%- if add_generation_prompt -%} {# Checks for generation prompt flag #}
    {{'<start_of_turn>model\n'}} {# Starts model (assistant) turn #}
{%- endif -%}

Llama 3.1 Chat Template

{# 
Block 1: Variable Initialization
(a) What this block is about: 
This block sets up default variables for tools, date, and other configurations if not provided, ensuring the template has fallback values for system prompts and tool handling.
 
(b) What concretely each part is about:
- Tools setup: Sets tools from custom_tools if defined.
- Tools in user message: Defaults to true if not defined.
- Date string: Defaults to "26 Jul 2024".
- Tools fallback: Sets to none if undefined.
#}
{{- bos_token }} {# Outputs beginning-of-sequence token #}
{%- if custom_tools is defined %} {# Checks for custom_tools #}
    {%- set tools = custom_tools %} {# Sets tools variable #}
{%- endif %}
{%- if not tools_in_user_message is defined %} {# Checks if tools_in_user_message defined #}
    {%- set tools_in_user_message = true %} {# Defaults to true #}
{%- endif %}
{%- if not date_string is defined %} {# Checks for date_string #}
    {%- set date_string = "26 Jul 2024" %} {# Defaults date #}
{%- endif %}
{%- if not tools is defined %} {# Checks for tools #}
    {%- set tools = none %} {# Defaults to none #}
{%- endif %}
 
{# 
Block 2: System Message Extraction
(a) What this block is about: 
This block extracts the system message if the first message is system-role, trims it, and adjusts the messages list accordingly; otherwise, sets an empty system message.
 
(b) What concretely each part is about:
- If first is system: Trims content, sets system_message, slices messages from second.
- Else: Empty system_message.
#}
{#- This block extracts the system message, so we can slot it into the right place. #}
{%- if messages[0]['role'] == 'system' %} {# Checks if first message is system #}
    {%- set system_message = messages[0]['content']|trim %} {# Trims and sets system_message #}
    {%- set messages = messages[1:] %} {# Skips system for further processing #}
{%- else %}
    {%- set system_message = "" %} {# Empty if no system #}
{%- endif %}
 
{# 
Block 3: System Prompt Construction
(a) What this block is about: 
This block builds the system header with environment info, builtin tools, knowledge cutoff date, current date, tool instructions (if not in user message), and the extracted system message.
 
(b) What concretely each part is about:
- Starts system header.
- If builtin_tools or tools: Adds ipython environment.
- If builtin_tools: Lists tools (excluding code_interpreter).
- Adds knowledge and date strings.
- If tools and not in user message: Adds function call instructions, outputs tools as JSON.
- Appends system_message and ends header.
#}
{#- System message + builtin tools #}
{{- "<|start_header_id|>system<|end_header_id|>\n\n" }} {# Starts system header #}
{%- if builtin_tools is defined or tools is not none %} {# Checks for tools presence #}
    {{- "Environment: ipython\n" }} {# Adds environment #}
{%- endif %}
{%- if builtin_tools is defined %} {# If builtin_tools defined #}
    {{- "Tools: " + builtin_tools | reject('equalto', 'code_interpreter') | join(", ") + "\n\n"}} {# Lists tools #}
{%- endif %}
{{- "Cutting Knowledge Date: December 2023\n" }} {# Knowledge cutoff #}
{{- "Today Date: " + date_string + "\n\n" }} {# Current date #}
{%- if tools is not none and not tools_in_user_message %} {# If tools and not in user #}
    {{- "You have access to the following functions. To call a function, please respond with JSON for a function call." }} {# Tool instructions #}
    {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }}
    {{- "Do not use variables.\n\n" }}
    {%- for t in tools %} {# Loops over tools #}
        {{- t | tojson(indent=4) }} {# Outputs as indented JSON #}
        {{- "\n\n" }}
    {%- endfor %}
{%- endif %}
{{- system_message }} {# Appends system content #}
{{- "<|eot_id|>" }} {# Ends system #}
 
{# 
Block 4: Custom Tools in User Message
(a) What this block is about: 
If tools are to be in the user message, this block injects them into the first user message with guidance on JSON function calls, extracting and trimming the first user content.
 
(b) What concretely each part is about:
- If tools_in_user_message and tools: Extracts first user content, adjusts messages.
- Outputs user header with tool instructions, outputs tools as JSON, appends first user message, ends header.
- Raises exception if no first user message.
#}
{#- Custom tools are passed in a user message with some extra guidance #}
{%- if tools_in_user_message and not tools is none %} {# Checks for tools in user #}
    {#- Extract the first user message so we can plug it in here #}
    {%- if messages | length != 0 %} {# Ensures messages exist #}
        {%- set first_user_message = messages[0]['content']|trim %} {# Trims first user #}
        {%- set messages = messages[1:] %} {# Skips it #}
    {%- else %}
        {{- raise_exception("Cannot put tools in the first user message when there's no first user message!") }} {# Error if none #}
    {%- endif %}
    {{- '<|start_header_id|>user<|end_header_id|>\n\n' -}} {# Starts user header #}
    {{- "Given the following functions, please respond with a JSON for a function call " }} {# Instructions #}
    {{- "with its proper arguments that best answers the given prompt.\n\n" }}
    {{- 'Respond in the format {"name": function name, "parameters": dictionary of argument name and its value}.' }}
    {{- "Do not use variables.\n\n" }}
    {%- for t in tools %} {# Loops over tools #}
        {{- t | tojson(indent=4) }} {# Outputs JSON #}
        {{- "\n\n" }}
    {%- endfor %}
    {{- first_user_message + "<|eot_id|>"}} {# Appends user content and ends #}
{%- endif %}
 
{# 
Block 5: Main Conversation Loop
(a) What this block is about: 
This block loops through remaining messages, formats non-tool messages with headers, handles tool calls (single only, builtin or JSON), and tool responses (as ipython).
 
(b) What concretely each part is about:
- Loop: For each message.
- If not tool/ipython or tool_calls: Outputs role header, trimmed content, eot.
- If tool_calls: Ensures single call, formats as assistant with python_tag for builtin or JSON, ends with eom/eot.
- If tool/ipython: Outputs ipython header, content as JSON or string, eot.
#}
{%- for message in messages %} {# Loops through messages #}
    {%- if not (message.role == 'ipython' or message.role == 'tool' or 'tool_calls' in message) %} {# Standard messages #}
        {{- '<|start_header_id|>' + message['role'] + '<|end_header_id|>\n\n'+ message['content'] | trim + '<|eot_id|>' }} {# Formats header/content/end #}
    {%- elif 'tool_calls' in message %} {# Tool calls #}
        {%- if not message.tool_calls|length == 1 %} {# Ensures single call #}
            {{- raise_exception("This model only supports single tool-calls at once!") }} {# Error if multiple #}
        {%- endif %}
        {%- set tool_call = message.tool_calls[0].function %} {# Gets function #}
        {%- if builtin_tools is defined and tool_call.name in builtin_tools %} {# If builtin #}
            {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' -}} {# Assistant header #}
            {{- "<|python_tag|>" + tool_call.name + ".call(" }} {# Python call format #}
            {%- for arg_name, arg_val in tool_call.arguments | items %} {# Args loop #}
                {{- arg_name + '="' + arg_val + '"' }} {# Arg pair #}
                {%- if not loop.last %}
                    {{- ", " }} {# Comma separator #}
                {%- endif %}
            {%- endfor %}
            {{- ")" }} {# Ends call #}
        {%- else %} {# Non-builtin #}
            {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' -}} {# Assistant header #}
            {{- '{"name": "' + tool_call.name + '", ' }} {# JSON name #}
            {{- '"parameters": ' }}
            {{- tool_call.arguments | tojson }} {# JSON parameters #}
            {{- "}" }} {# Ends JSON #}
        {%- endif %}
        {%- if builtin_tools is defined %} {# If builtin (ipython mode) #}
            {#- This means we're in ipython mode #}
            {{- "<|eom_id|>" }} {# End of message #}
        {%- else %}
            {{- "<|eot_id|>" }} {# End of turn #}
        {%- endif %}
    {%- elif message.role == "tool" or message.role == "ipython" %} {# Tool responses #}
        {{- "<|start_header_id|>ipython<|end_header_id|>\n\n" }} {# Ipython header #}
        {%- if message.content is mapping or message.content is iterable %} {# If mapping/iterable #}
            {{- message.content | tojson }} {# To JSON #}
        {%- else %}
            {{- message.content }} {# As string #}
        {%- endif %}
        {{- "<|eot_id|>" }} {# Ends #}
    {%- endif %}
{%- endfor %}
 
{# 
Block 6: Generation Prompt Addition
(a) What this block is about: 
This block conditionally adds the assistant header to prompt generation if requested.
 
(b) What concretely each part is about:
- If add_generation_prompt: Outputs assistant start header.
#}
{%- if add_generation_prompt %} {# Checks flag #}
    {{- '<|start_header_id|>assistant<|end_header_id|>\n\n' }} {# Starts assistant #}
{%- endif %}