{%- if not messages %}
{{- raise_exception('No messages provided.') }}
{%- endif %}
{%- if tools and tools is iterable and tools is not mapping %}
{{- '<|im_start|>system
' }}
{{- "# Tools\n\nYou have access to the following functions:\n\n" }}
{%- for tool in tools %}
{{- "\n" }}
{{- tool | tojson }}
{%- endfor %}
{{- "\n" }}
{{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n\n\n\nvalue_1\n\n\n\n\n\nReminder:\n- Function calls MUST follow the specified format\n- Required parameters MUST be specified\n- If there is no function call available, answer normally\n' }}
{%- if messages[0].role == 'system' %}
{{- '\n\n' + messages[0].content | trim + '<|im_end|>\n' }}
{%- else %}
{{- '<|im_end|>\n' }}
{%- endif %}
{%- else %}
{%- if messages[0].role == 'system' %}
{{- '<|im_start|>system\n' + messages[0].content | trim + '<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- set ns = namespace(last_query_index=messages|length - 1) %}
{%- for message in messages %}
{%- if message.role == "user" %}
{{- '<|im_start|>user\n' + message.content | trim + '<|im_end|>\n' }}
{%- elif message.role == "assistant" %}
{%- set content = message.content | trim %}
{%- set reasoning = '' %}
{%- if '' in content %}
{%- set reasoning = content.split('')[0].split('')[-1].strip() %}
{%- set content = content.split('')[-1].strip() %}
{%- endif %}
{{- '<|im_start|>assistant\n' }}
{%- if reasoning %}
{{- '\n' + reasoning + '\n\n\n' }}
{%- endif %}
{{- content + '<|im_end|>\n' }}
{%- elif message.role == "tool" %}
{{- '\n' + message.content | trim + '\n\n' }}
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
{{- '<|im_start|>assistant\n\n' }}
{%- endif %}