{# --- MACROS --- #}
{%- macro render_vision_element(item, type, count_obj, add_id) -%}
{%- set count_obj.value = count_obj.value + 1 -%}
{%- if add_id -%}
{{ type|capitalize ~ ' ' ~ count_obj.value ~ ': ' }}
{%- endif -%}
{{- '<|vision_start|><|' ~ type ~ '_pad|><|vision_end|>' -%}
{%- endmacro -%}
{%- macro render_tool_call(tool_call) -%}
{%- if tool_call.arguments is defined -%}
{%- for args_name, args_value in tool_call.arguments|items %}
{{ args_value | tojson | safe if args_value is mapping or (args_value is sequence and args_value is not string) else args_value }}
{%- endfor -%}
{%- endif %}
{%- endmacro -%}
{# --- CORE LOGIC --- #}
{%- if tools -%}
<|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- Reasoning should come BEFORE the function call\n' }}
{%- if messages[0].role == 'system' -%}
{%- set sys_content = render_content(messages[0].content, false, true)|trim -%}
{{- '\n\n' + sys_content if sys_content }}
{%- endif %}
<|im_end|>
{%- elif messages[0].role == 'system' -%}
<|im_start|>system
{{- render_content(messages[0].content, false, true)|trim -}}
<|im_end|>
{%- endif %}
{%- for message in messages %}
{%- if message.role == "user" %}
<|im_start|>user
{{- render_content(message.content, true)|trim -}}
<|im_end|>
{%- elif message.role == "assistant" %}
<|im_start|>assistant
{%- if loop.index0 > ns.last_query_index %}
{{ message.reasoning_content | trim if message.reasoning_content else "" }}
{%- endif %}
{{- render_content(message.content, true)|trim -}}
{%- if message.tool_calls %}
{%- for tool_call in message.tool_calls %}
{{- render_tool_call(tool_call.function if tool_call.function is defined else tool_call) }}
{%- endfor %}
{%- endif %}
<|im_end|>
{%- elif message.role == "tool" %}
{%- if loop.previtem and loop.previtem.role != "tool" %}<|im_start|>user{% endif %}
{{- render_content(message.content, true)|trim -}}
{%- if loop.last or loop.nextitem.role != "tool" %}<|im_end|>{% endif %}
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
<|im_start|>assistant
{%- if not (enable_thinking == false) %}
{% endif %}
{%- endif %}