{#- OLMo 3 Instruct SFT chat template (ChatML format).
Based on allenai/Olmo-3-7B-Instruct-SFT with {%- generation %} tags added
for completion_only_loss training support. -#}
{%- set has_system = messages | selectattr('role', 'equalto', 'system') | list | length > 0 -%}
{%- if not has_system -%}
{{- '<|im_start|>system\nYou are a helpful AI assistant.' -}}
{%- if tools is not none and (tools | length) > 0 -%}
{{- ' You are provided with function signatures within XML tags. You may call one or more functions to assist with the user query. Output any function calls within XML tags. Do not make assumptions about what values to plug into functions.' -}}
{{- '' + tools | tojson + '' -}}
{%- endif -%}
{{- '<|im_end|>\n' -}}
{%- endif -%}
{%- for message in messages -%}
{%- if message['role'] == 'system' -%}
{{- '<|im_start|>system\n' + message['content'] -}}
{%- if tools is not none -%}
{{- '' + tools | tojson + '' -}}
{%- elif message.get('functions', none) is not none -%}
{{- ' ' + message['functions'] + '' -}}
{%- endif -%}
{{- '<|im_end|>\n' -}}
{%- elif message['role'] == 'user' -%}
{{- '<|im_start|>user\n' + message['content'] + '<|im_end|>\n' -}}
{%- elif message['role'] == 'assistant' -%}
{{- '<|im_start|>assistant\n' -}}
{% generation %}
{%- if message.get('content', none) is not none -%}
{{- message['content'] -}}
{%- endif -%}
{%- if message.get('function_calls', none) is not none -%}
{{- '' + message['function_calls'] + '' -}}
{%- elif message.get('tool_calls', none) is not none -%}
{{- '' -}}
{%- for tool_call in message['tool_calls'] -%}
{%- if tool_call is mapping and tool_call.get('function', none) is not none -%}
{%- set args = tool_call['function']['arguments'] -%}
{%- set ns = namespace(arguments_list=[]) -%}
{%- for key, value in args.items() -%}
{%- set ns.arguments_list = ns.arguments_list + [key ~ '=' ~ (value | tojson)] -%}
{%- endfor -%}
{{- tool_call['function']['name'] + '(' + ns.arguments_list | join(', ') + ')' -}}
{%- else -%}
{{- tool_call -}}
{%- endif -%}
{%- if not loop.last -%}{{ '\n' }}{%- endif -%}
{%- endfor -%}
{{- '' -}}
{%- endif -%}
{%- if not loop.last -%}
{{- '<|im_end|>\n' -}}
{%- else -%}
{{- eos_token -}}
{%- endif -%}
{% endgeneration %}
{%- elif message['role'] == 'environment' or message['role'] == 'tool' -%}
{{- '<|im_start|>environment\n' + message['content'] + '<|im_end|>\n' -}}
{%- endif -%}
{%- if loop.last and add_generation_prompt -%}
{{- '<|im_start|>assistant\n' -}}
{%- endif -%}
{%- endfor -%}