{%- if tools %}
{{- '<|im_start|>system\n' }}
{%- if messages[0].role == 'system' %}
{{- messages[0].content + '\n\n' }}
{%- endif %}
{{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n\n" }}
{%- for tool in tools %}
{{- "\n" }}
{{- tool | tojson }}
{%- endfor %}
{{- "\n\n\nFor each function call, return a json object with function name and arguments within XML tags:\n\n\n{\"name\": , \"arguments\": }\n<|im_end|>\n" }}
{%- else %}
{%- if messages[0].role == 'system' %}
{{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- set ns = namespace(thinking_response_started=false, last_user_message_index=-1) %}
{%- for message in messages %}
{%- if message.role == 'user' %}
{%- set ns.last_user_message_index = loop.index0 %}
{%- endif %}
{%- endfor %}
{%- for message in messages %}
{%- if message.role in ['user', 'assistant', 'tool'] %}
{%- if message.role == 'user' %}
{%- if not tools and loop.index0 == 0 and messages[0].role != 'system' %}
{{- '<|im_start|>user\n' + message.content + '<|im_end|>\n' }}
{%- else %}
{{- '<|im_start|>user\n' + message.content + '<|im_end|>\n' }}
{%- endif %}
{%- elif message.role == 'assistant' %}
{%- set content = message.content %}
{%- set has_tool_calls = message.tool_calls is defined and message.tool_calls %}
{{- '<|im_start|>assistant\n' }}
{# Handle thinking mode: strip blocks from history except for the most recent user turn #}
{%- if loop.index0 > ns.last_user_message_index %}
{%- if content is string and content.startswith('') %}
{{- content }}
{%- elif content is string %}
{%- if enable_thinking is defined and enable_thinking == false %}
{{- '\n\n\n\n' }}
{%- endif %}
{{- content }}
{%- endif %}
{%- else %}
{# Older turns: strip think blocks to save context #}
{%- if content is string %}
{%- set stripped = content %}
{%- if '' in stripped %}
{%- set stripped = stripped.split('')[-1].lstrip('\n') %}
{%- endif %}
{{- stripped }}
{%- endif %}
{%- endif %}
{%- if has_tool_calls %}
{%- for tool_call in message.tool_calls %}
{{- '\n\n' }}
{{- '{"name": "' + tool_call.function.name + '", "arguments": ' }}
{%- if tool_call.function.arguments is string %}
{{- tool_call.function.arguments }}
{%- else %}
{{- tool_call.function.arguments | tojson }}
{%- endif %}
{{- '}\n' }}
{%- endfor %}
{%- endif %}
{{- '<|im_end|>\n' }}
{%- elif message.role == 'tool' %}
{{- '<|im_start|>user\n\n' + message.content + '\n<|im_end|>\n' }}
{%- endif %}
{%- endif %}
{%- endfor %}
{%- if add_generation_prompt %}
{{- '<|im_start|>assistant\n' }}
{%- if enable_thinking is defined and enable_thinking == false %}
{{- '\n\n\n\n' }}
{%- endif %}
{%- endif %}