{%- set template_version = "qwen3.8-froggeric-v22.5.0-DAU-Twin-Turbo-V1.0" %}
{# Define the hardcoded thinking instructions - DAU=einstein, DAU2=spoon #}
{%- set system_instruction_DAU -%}
[SYSTEM]
[Temperature: 1.25]
[TopP: .2]
[PERSONA]Brainstormer takes in a notion, applies a bunch of perspective agents set to improve it by seeking novelty, and spits out a bunch of improved creative ideas.

SKILLS:
[Advert]-[DigMrk]-[SEO]-[SEM]-[PITCHES]-[CREATIVITY]-[BURSTINESS]-[PERPLEXITY]-[AVOIDHGHCORRELATE]-[HUMPRTXT]-[CONTENTGEN]

[Task]
gE: Silent input → Spawn 20 agents Sternberg Styles → Enhance idea → Seek Novel Emergence NE:unique/significant idea/concept → Ponder, assess, creative enhance notions → Refined idea => IdeaArray[].size=20 elements,  else → Interesting? Pass to rand. agent for refinement, else discard.=>output(IdeaArray)[/Task]

[Task]Request input[/Task]

gE(input) > response

Think deeply and carefully about the user's request using "gE(input)" and ponder all the possiblities, evaluate them one by one. Draft your first response, then evaluate it and adjust if required.
Compose your thoughts (which should be at least 5000 tokens) about the user's prompt between <think> and </think> tags, then output the final answer based on your thoughts.
{%- endset -%}
{# Define the hardcoded thinking instructions -DAU2=spoon #}
{%- set system_instruction_DAU2 -%}
Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.

IMPORTANT INSTRUCTIONS:
You are Qwen Deep Research, a careful local 27B Qwen reasoning assistant optimized for high-quality, structured research answers.
Your goal is to produce accurate, well-reasoned, practical results by internally simulating a focused multi-expert research process. Do not claim to be a real human panel. Use “virtual experts” as reasoning perspectives.

For every user request, internally follow this Deep Research Protocol:

1. Frame the task
   - Identify the user's core request, intended field, constraints, desired output format, and success criteria.
   - Note ambiguities, missing context, risks, and possible misunderstandings.
   - If one brief clarifying question would materially improve the result, ask it. Otherwise proceed with clearly stated assumptions.
   - Rate the user's core request of complexity on a scale of 1 to 5, with 5 being highest AND EXPAND the reasoning and detail levels according to this scale.

2. Create a field-specific expert panel
   - Build 3 to 5 virtual experts relevant to the user's domain.
   - Adapt the roles to the task. Examples:
     - Domain expert
     - Research methodologist
     - Engineer / developer
     - Risk / compliance / ethics analyst
     - Critic / red-team reviewer
     - Communicator / final-answer synthesizer
   - Each expert should focus on a different strength, not repeat the same point.

3. Panel discussion of the user's prompt
   - Have the panel discuss what the user is really asking.
   - Identify likely failure modes, edge cases, hidden assumptions, and required evidence.
   - If experts disagree, resolve the disagreement by favoring correctness, usefulness, safety, clarity, and practicality.

4. Generate candidate solutions
   - Produce 2 to 3 distinct candidate answers, plans, approaches, or solutions.
   - For each candidate, include:
     - Main idea
     - Assumptions
     - Key steps or components
     - Strengths
     - Weaknesses or risks

5. Evaluate the candidates
   - Score each candidate 1 to 5 on:
     - Correctness
     - Completeness
     - Practical usefulness
     - Safety / compliance
     - Clarity
     - Efficiency
   - Identify the best candidate and explain why it is superior.

6. Double-check the selected solution
   - Re-verify important facts, logic, calculations, code, dates, units, dependencies, and edge cases.
   - Check for hallucinated sources, invented numbers, unsupported claims, contradictions, and missing constraints.
   - For code, mentally execute or trace the logic and note likely failure points.
   - For medical, legal, financial, safety-critical, or high-stakes topics, add appropriate cautions and recommend qualified professional review.

7. Output the result
   - Provide the final result in the format the user requested.
   - If the user did not specify a format, use this structure:

     Final Answer
     Brief explanation
     Key assumptions
     Recommended next steps
     Confidence level / verification needed

Operating rules:
- Minimum size of the thinking/reasoning/eval block is 5000 words.
- Be concrete, specific, and useful.
- Do not claim live internet access unless the host system actually provides it.
- Do not invent citations, sources, statistics, benchmarks, or facts.
- If uncertain, state the uncertainty clearly and explain what evidence would confirm or disprove the claim.
- Keep the internal expert panel compact and purposeful. Do not loop indefinitely.
- SHOW hidden chain-of-thought processes.
- For code, provide minimal working examples when possible and mention required environment or dependencies.
- For ambiguous prompts, state the interpretation you chose before answering.
- Optimize for reliability: prefer clear structure, bounded reasoning, and concise final output.
{%- endset -%}
{%- set _tool_format = tool_call_format if tool_call_format is defined else 'xml' %}
{%- set image_count = namespace(value=0) %}
{%- set video_count = namespace(value=0) %}
{%- set add_vision_id = add_vision_id if add_vision_id is defined else false %}
{%- set enable_thinking = enable_thinking if enable_thinking is defined else true %}
{%- set auto_disable_thinking_with_tools = auto_disable_thinking_with_tools if auto_disable_thinking_with_tools is defined else false %}
{%- if preserve_reasoning is defined and preserve_reasoning is not none %}
    {%- set _preserve_thinking = preserve_reasoning %}
{%- elif preserve_thinking is defined and preserve_thinking is not none %}
    {%- set _preserve_thinking = preserve_thinking %}
{%- else %}
    {%- set _preserve_thinking = true %}
{%- endif %}
{%- set max_tool_arg_chars = max_tool_arg_chars if max_tool_arg_chars is defined else 0 %}
{%- set max_tool_response_chars = max_tool_response_chars if max_tool_response_chars is defined else 0 %}
{%- set _default_reasoning_effort = 'medium' %}
{%- set _has_tools = (tools is defined and tools and tools is iterable and tools is not mapping) %}
{%- set _effort_raw = (reasoning_effort | string | lower) if reasoning_effort is defined and reasoning_effort is not none else _default_reasoning_effort %}
{%- set _initial_thinking = enable_thinking %}
{%- if _effort_raw in ('none', 'off') %}
    {%- set _initial_thinking = false %}
    {%- set _initial_effort = 'medium' %}
{%- elif _effort_raw in ('minimal', 'low') %}
    {%- set _initial_effort = 'low' %}
{%- elif _effort_raw in ('high', 'xhigh', 'max', 'ultracode', 'extreme') %}
    {%- set _initial_effort = 'xhigh' %}
{%- else %}
    {%- set _initial_effort = 'medium' %}
{%- endif %}
{%- set ns_state = namespace(thinking=_initial_thinking, effort=_initial_effort) %}
{%- if auto_disable_thinking_with_tools and _has_tools %}
    {%- set ns_state.thinking = false %}
{%- endif %}
{%- for msg in messages %}
    {%- if msg.role == 'system' or msg.role == 'developer' or msg.role == 'user' %}
        {%- if msg.content is string %}
            {%- if '<|think_off|>' in msg.content %}
                {%- set ns_state.thinking = false %}
            {%- elif '<|think_on|>' in msg.content %}
                {%- set ns_state.thinking = true %}
            {%- elif '<|think_xhigh|>' in msg.content or '<|think_high|>' in msg.content or '<|think_ultracode|>' in msg.content or '<|think_extreme|>' in msg.content or '<|think_max|>' in msg.content %}
                {%- set ns_state.thinking = true %}
                {%- set ns_state.effort = 'xhigh' %}
            {%- elif '<|think_low|>' in msg.content or '<|think_minimal|>' in msg.content %}
                {%- set ns_state.thinking = true %}
                {%- set ns_state.effort = 'low' %}
            {%- elif '<|think_medium|>' in msg.content %}
                {%- set ns_state.thinking = true %}
                {%- set ns_state.effort = 'medium' %}
            {%- endif %}
        {%- elif msg.content is iterable and msg.content is not mapping %}
            {%- for item in msg.content %}
                {%- if item is string %}
                    {%- set _item_text = item %}
                {%- elif item is mapping and 'text' in item and item.text is string %}
                    {%- set _item_text = item.text %}
                {%- else %}
                    {%- set _item_text = '' %}
                {%- endif %}
                {%- if _item_text %}
                    {%- if '<|think_off|>' in _item_text %}
                        {%- set ns_state.thinking = false %}
                    {%- elif '<|think_on|>' in _item_text %}
                        {%- set ns_state.thinking = true %}
                    {%- elif '<|think_xhigh|>' in _item_text or '<|think_high|>' in _item_text or '<|think_ultracode|>' in _item_text or '<|think_extreme|>' in _item_text or '<|think_max|>' in _item_text %}
                        {%- set ns_state.thinking = true %}
                        {%- set ns_state.effort = 'xhigh' %}
                    {%- elif '<|think_low|>' in _item_text or '<|think_minimal|>' in _item_text %}
                        {%- set ns_state.thinking = true %}
                        {%- set ns_state.effort = 'low' %}
                    {%- elif '<|think_medium|>' in _item_text %}
                        {%- set ns_state.thinking = true %}
                        {%- set ns_state.effort = 'medium' %}
                    {%- endif %}
                {%- endif %}
            {%- endfor %}
        {%- endif %}
    {%- endif %}
{%- endfor %}
{%- macro render_content(content, do_vision_count, is_system_content=false) %}
    {%- if content is string %}
        {{- content }}
    {%- elif content is iterable and content is not mapping %}
        {%- for item in content %}
            {%- if item is mapping %}
                {%- if item.type == 'image' or 'image' in item or 'image_url' in item %}
                    {%- if is_system_content %}
                        {{- raise_exception('System message cannot contain images.') }}
                    {%- endif %}
                    {%- if do_vision_count %}
                        {%- set image_count.value = image_count.value + 1 %}
                    {%- endif %}
                    {%- if add_vision_id %}
                        {{- 'Picture ' ~ image_count.value ~ ': ' }}
                    {%- endif %}
                    {{- '<|vision_start|><|image_pad|><|vision_end|>' }}
                {%- elif item.type == 'video' or 'video' in item or 'video_url' in item %}
                    {%- if is_system_content %}
                        {{- raise_exception('System message cannot contain videos.') }}
                    {%- endif %}
                    {%- if do_vision_count %}
                        {%- set video_count.value = video_count.value + 1 %}
                    {%- endif %}
                    {%- if add_vision_id %}
                        {{- 'Video ' ~ video_count.value ~ ': ' }}
                    {%- endif %}
                    {{- '<|vision_start|><|video_pad|><|vision_end|>' }}
                {%- elif 'text' in item %}
                    {{- item.text }}
                {%- else %}
                    {{- raise_exception('Unexpected item type in content.') }}
                {%- endif %}
            {%- else %}
                {{- item | string }}
            {%- endif %}
        {%- endfor %}
    {%- elif content is none or content is undefined %}
        {{- '' }}
    {%- else %}
        {{- raise_exception('Unexpected content type.') }}
    {%- endif %}
{%- endmacro %}
{% set store = namespace(messages=[], reasoning_effort="", enable_thinking=true) %}
{% for msg in messages %}
  {% set raw_reason = "" %}
  {% set txt = render_content(msg.content, false) | trim %}
  {% if (msg.role == 'user' and "{REASON:" in txt) %}
  {% set after_tag = txt.split("{REASON:") %}
  {% set candidate = after_tag[1].split("}")[0] %}
  {% set candidate_key = candidate[1:] if candidate.startswith('i') else candidate %}
  {% if candidate and candidate_key in ('xhigh', 'medium', 'low', 'einstein', 'spoon') %}
    {% set raw_reason = candidate %}
    {% set tag = "{REASON:" ~ raw_reason ~ "}" %}
    {% set clean_txt = txt.replace(tag, "") | trim %}
    {% set store.messages = store.messages + [{"role": msg.role, "content": clean_txt}] %}
  {% endif %}
  {% else %}
    {% set store.messages = store.messages + [msg] %}
  {% endif %}
  {% if raw_reason %}
    {% if raw_reason.startswith('i') %}
      {% set store.reasoning_effort = raw_reason[1:] %}
      {% set store.enable_thinking = false %}
    {% else %}
      {% set store.reasoning_effort = raw_reason %}
      {% set store.enable_thinking = true %}
    {% endif %}
  {% endif %}
{% endfor %}
{% if store.reasoning_effort %}
  {% set reasoning_effort = store.reasoning_effort %}
  {% set enable_thinking = store.enable_thinking %}
  {% set ns_state.effort = store.reasoning_effort %}
  {% set ns_state.thinking = store.enable_thinking %}
{% endif %}
{% set messages = store.messages %}
{%- set reasoning_instructions = '' %}
{%- if enable_thinking is undefined or enable_thinking is true %}
    {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}
    {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low','einstein','spoon') %}
        {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low PLUS einstein and spoon.') }}
    {%- endif %}
    {%- if resolved_reasoning_effort == 'einstein' %}
        {%- set reasoning_instructions = system_instruction_DAU %}
    {%- elif resolved_reasoning_effort == 'spoon' %}
        {%- set reasoning_instructions = system_instruction_DAU2 %}
    {%- elif resolved_reasoning_effort == 'xhigh' %}
        {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}
    {%- elif resolved_reasoning_effort == 'low' %}
        {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}
    {%- endif %}
{%- endif %}
{%- if enable_thinking is false %}
    {%- set resolved_reasoning_effort = reasoning_effort|default('medium') %}
    {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low','einstein','spoon') %}
        {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low PLUS einstein and spoon.') }}
    {%- endif %}
    {%- if resolved_reasoning_effort == 'einstein' %}
        {%- set reasoning_instructions = system_instruction_DAU %}
    {%- elif resolved_reasoning_effort == 'spoon' %}
        {%- set reasoning_instructions = system_instruction_DAU2 %}
    {%- elif resolved_reasoning_effort == 'xhigh' %}
        {%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}
    {%- elif resolved_reasoning_effort == 'low' %}
        {%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}
    {%- endif %}
{%- endif %}
{%- if not messages %}
    {{- raise_exception('No messages provided.') }}
{%- endif %}
{%- set head = namespace(count=0, seen_non_system=false) %}
{%- for message in messages %}
    {%- set _is_sys = (message.role == 'system' or message.role == 'developer') %}
    {%- if _is_sys and not head.seen_non_system %}
        {%- set head.count = head.count + 1 %}
    {%- else %}
        {%- set head.seen_non_system = true %}
    {%- endif %}
{%- endfor %}
{%- set sys_state = namespace(content='') %}
{%- for message in messages[:head.count] %}
    {%- set _part = render_content(message.content, false, true) | trim %}
    {%- if '<|think_off|>' in _part %}{%- set _part = _part.split('<|think_off|>') | join('') | trim %}{%- endif %}
    {%- if '<|think_on|>' in _part %}{%- set _part = _part.split('<|think_on|>') | join('') | trim %}{%- endif %}
    {%- if '<|think_xhigh|>' in _part %}{%- set _part = _part.split('<|think_xhigh|>') | join('') | trim %}{%- endif %}
    {%- if '<|think_high|>' in _part %}{%- set _part = _part.split('<|think_high|>') | join('') | trim %}{%- endif %}
    {%- if '<|think_ultracode|>' in _part %}{%- set _part = _part.split('<|think_ultracode|>') | join('') | trim %}{%- endif %}
    {%- if '<|think_extreme|>' in _part %}{%- set _part = _part.split('<|think_extreme|>') | join('') | trim %}{%- endif %}
    {%- if '<|think_max|>' in _part %}{%- set _part = _part.split('<|think_max|>') | join('') | trim %}{%- endif %}
    {%- if '<|think_medium|>' in _part %}{%- set _part = _part.split('<|think_medium|>') | join('') | trim %}{%- endif %}
    {%- if '<|think_low|>' in _part %}{%- set _part = _part.split('<|think_low|>') | join('') | trim %}{%- endif %}
    {%- if '<|think_minimal|>' in _part %}{%- set _part = _part.split('<|think_minimal|>') | join('') | trim %}{%- endif %}
    {%- if _part %}
        {%- if sys_state.content %}
            {%- set sys_state.content = sys_state.content ~ '\n\n' ~ _part %}
        {%- else %}
            {%- set sys_state.content = _part %}
        {%- endif %}
    {%- endif %}
{%- endfor %}
{%- set _sc = sys_state.content %}
{%- set _msgs = messages[head.count:] %}
{%- if ns_state.thinking %}
    {%- set _terse_lead = 'Answer directly, after thinking. Lead with the answer, then only what it needs to be correct and usable.' %}
{%- else %}
    {%- set _terse_lead = 'Answer directly and concisely. Give the answer with only what it needs to be correct and usable.' %}
{%- endif %}
{%- set _terse_core %}
Never: open with preamble or pleasantries; restate the question; add filler transitions; hedge with niceties; or repeat a point you've already made.
Always: keep essential steps, caveats, uncertainties, and specifics — never drop correctness or a needed warning for brevity. Keep the final answer lean. Use the least structure that conveys it (plain prose when short; lists or code only when they earn their place). If genuinely uncertain, say so and explain why — never omit uncertainty for the sake of brevity.
If a user request is genuinely ambiguous, ask a sharp question, don't guess.
{%- endset %}
{%- set _terse = _terse_lead ~ '\n' ~ (_terse_core | trim) %}
{#- `terse` chat-template kwarg: default true, so behaviour is unchanged unless a caller opts out.
    Pass {"terse": false} via chat_template_kwargs to serve the model with only its own system
    prompt -- useful for A/B-ing the terseness effect, or when a downstream prompt conflicts. #}
{%- set _terse_on = terse if terse is defined else true %}
{%- if _terse_on %}
    {%- if not _sc %}
        {%- set _sc = _terse | trim %}
    {%- else %}
        {%- set _sc = (_sc | trim) ~ '\n\n' ~ (_terse | trim) %}
    {%- endif %}
{%- endif %}
{#- Some runtimes (LM Studio's MLX backend) have no native tool-call parser and prepend their own
    protocol into the system content. Emitting ours as well gives the model two contradictory tool
    protocols and it follows one at random. Detect that marker and stand down; the
    `suppress_tool_instructions` kwarg overrides either way where a runtime can pass template kwargs. #}
{%- set _runtime_tool_protocol = (_sc is defined and _sc and '[TOOL_REQUEST]' in _sc) %}
{%- set _suppress_tools = suppress_tool_instructions if suppress_tool_instructions is defined else _runtime_tool_protocol %}
{%- if _has_tools and not _suppress_tools %}
    {{- '<|im_start|>system\n' }}
    {%- if reasoning_instructions %}
        {{- reasoning_instructions + '\n\n' }}
    {%- endif %}
    {{- '# Tools\n\nYou have access to the following functions:\n\n<tools>' }}
    {%- for tool in tools %}
        {{- '\n' }}
        {{- tool | tojson }}
    {%- endfor %}
    {{- '\n</tools>' }}
    {%- if _tool_format == 'json' %}
        {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n' }}
        {%- if ns_state.thinking %}
            {{- '<think>\nBrief explanation of tool call\n</think>\n' }}
        {%- endif %}
        {{- '<tool_call>\n{"name": "example_function_name", "arguments": {"example_parameter_1": "value_1", "example_parameter_2": "This is the value for the second parameter"}}\n</tool_call>\n\n<IMPORTANT>\nReminder:\n' }}
        {%- if ns_state.thinking %}
            {{- '- You can use the <think></think> block to plan your next tool call OR to synthesize data and formulate your final response to the user.\n- ALL explanation and reasoning MUST be placed strictly inside the <think></think> block.\n' }}
        {%- endif %}
        {{- '- Function calls MUST follow the specified format: a single JSON object with "name" and "arguments" keys inside <tool_call></tool_call> XML tags.\n' }}
        {%- if ns_state.thinking %}
            {{- '- If you choose to call a tool, you MUST output the <tool_call> block IMMEDIATELY after thinking, with NO conversational text before it.\n' }}
        {%- else %}
            {{- '- If you choose to call a tool, you MUST output the <tool_call> block IMMEDIATELY, with NO conversational text before it.\n' }}
        {%- endif %}
        {{- '- The <tool_call> tag MUST be at the very beginning of a new line, with NO spaces or indentation before it.\n- To call multiple functions, output a separate, completely closed <tool_call></tool_call> block for EACH function. Do NOT nest <tool_call> blocks.\n- If you have all necessary data, provide your final answer directly to the user without any tool call.\n</IMPORTANT>' }}
    {%- else %}
        {{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n' }}
        {%- if ns_state.thinking %}
            {{- '<think>\nBrief explanation of tool call\n</think>\n' }}
        {%- endif %}
        {{- '<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n' }}
        {%- if ns_state.thinking %}
            {{- '- You can use the <think></think> block to plan your next tool call OR to synthesize data and formulate your final response to the user.\n- ALL explanation and reasoning MUST be placed strictly inside the <think></think> block.\n' }}
        {%- endif %}
        {{- '- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags.\n' }}
        {%- if ns_state.thinking %}
            {{- '- If you choose to call a tool, you MUST output the <tool_call> block IMMEDIATELY after thinking, with NO conversational text before it.\n' }}
        {%- else %}
            {{- '- If you choose to call a tool, you MUST output the <tool_call> block IMMEDIATELY, with NO conversational text before it.\n' }}
        {%- endif %}
        {{- '- The <tool_call> and <function> tags MUST be at the very beginning of a new line, with NO spaces or indentation before them.\n- To call multiple functions, output a separate, completely closed <tool_call></tool_call> block for EACH function. Do NOT nest <tool_call> blocks.\n- If you have all necessary data, provide your final answer directly to the user without any tool call.\n</IMPORTANT>' }}
    {%- endif %}
    {%- if _sc %}
        {{- '\n\n' + _sc }}
    {%- endif %}
    {{- '<|im_end|>\n' }}
{%- else %}
    {%- if _sc %}
        {{- '<|im_start|>system\n' + (reasoning_instructions + '\n\n' if reasoning_instructions else '') + _sc + '<|im_end|>\n' }}
    {%- elif reasoning_instructions %}
        {{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
    {%- endif %}
{%- endif %}
{%- set _last_idx = _msgs | length - 1 %}
{%- set ns = namespace(multi_step_tool=true, last_query_index=_last_idx) %}
{%- for message in _msgs[::-1] %}
    {%- set index = (_msgs | length - 1) - loop.index0 %}
    {%- if ns.multi_step_tool and message.role == 'user' %}
        {%- set _rc = render_content(message.content, false) | trim %}
        {%- if not (_rc.startswith('<tool_response>') and _rc.endswith('</tool_response>')) %}
            {%- set ns.multi_step_tool = false %}
            {%- set ns.last_query_index = index %}
        {%- endif %}
    {%- endif %}
{%- endfor %}
{%- if ns.multi_step_tool %}
    {%- if _last_idx > 50 %}
        {%- set ns.last_query_index = _last_idx %}
    {%- else %}
        {%- set ns.last_query_index = 0 %}
    {%- endif %}
{%- endif %}
{%- set ns2 = namespace(prev_role='', consecutive_failures=0) %}
{%- for message in _msgs %}
    {%- set is_system = (message.role == "system" or message.role == "developer") %}
    {%- set content = render_content(message.content, true, is_system) | trim %}
    {%- if is_system or message.role == 'user' %}
        {%- if '<|think_off|>' in content %}{%- set content = content.split('<|think_off|>') | join('') | trim %}{%- endif %}
        {%- if '<|think_on|>' in content %}{%- set content = content.split('<|think_on|>') | join('') | trim %}{%- endif %}
        {%- if '<|think_xhigh|>' in content %}{%- set content = content.split('<|think_xhigh|>') | join('') | trim %}{%- endif %}
        {%- if '<|think_high|>' in content %}{%- set content = content.split('<|think_high|>') | join('') | trim %}{%- endif %}
        {%- if '<|think_ultracode|>' in content %}{%- set content = content.split('<|think_ultracode|>') | join('') | trim %}{%- endif %}
        {%- if '<|think_extreme|>' in content %}{%- set content = content.split('<|think_extreme|>') | join('') | trim %}{%- endif %}
        {%- if '<|think_max|>' in content %}{%- set content = content.split('<|think_max|>') | join('') | trim %}{%- endif %}
        {%- if '<|think_medium|>' in content %}{%- set content = content.split('<|think_medium|>') | join('') | trim %}{%- endif %}
        {%- if '<|think_low|>' in content %}{%- set content = content.split('<|think_low|>') | join('') | trim %}{%- endif %}
        {%- if '<|think_minimal|>' in content %}{%- set content = content.split('<|think_minimal|>') | join('') | trim %}{%- endif %}
    {%- endif %}
    {%- if is_system %}
        {{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
    {%- elif message.role == 'user' %}
        {%- set ns2.consecutive_failures = 0 %}
        {{- '<|im_start|>user\n' + content + '<|im_end|>\n' }}
    {%- elif message.role == 'assistant' %}
        {%- set reasoning_content = '' %}
        {%- set _explicit_reasoning = '' %}
        {%- if message.reasoning_content is defined and message.reasoning_content is not none %}
            {%- if message.reasoning_content is string %}
                {%- set _explicit_reasoning = message.reasoning_content %}
            {%- else %}
                {%- set _explicit_reasoning = message.reasoning_content | string %}
            {%- endif %}
        {%- elif message.thinking is defined and message.thinking is not none %}
            {%- if message.thinking is string %}
                {%- set _explicit_reasoning = message.thinking %}
            {%- else %}
                {%- set _explicit_reasoning = message.thinking | string %}
            {%- endif %}
        {%- elif message.reasoning is defined and message.reasoning is not none %}
            {%- if message.reasoning is string %}
                {%- set _explicit_reasoning = message.reasoning %}
            {%- else %}
                {%- set _explicit_reasoning = message.reasoning | string %}
            {%- endif %}
        {%- endif %}
        {%- if _explicit_reasoning %}
            {%- set _lead_end = '' %}
            {%- if content.startswith('<think>') and '</think>' in content %}
                {%- set _lead_end = '</think>' %}
            {%- elif content.startswith('<thinking>') and '</thinking>' in content %}
                {%- set _lead_end = '</thinking>' %}
            {%- elif content.startswith('</think>') %}
                {%- set _lead_end = '</think>' %}
            {%- elif content.startswith('</thinking>') %}
                {%- set _lead_end = '</thinking>' %}
            {%- endif %}
            {%- if _lead_end %}
                {%- set content = content.split(_lead_end)[-1].lstrip('\n') %}
            {%- endif %}
            {%- set reasoning_content = _explicit_reasoning %}
        {%- else %}
            {%- set _think_end = '' %}
            {%- if content.startswith('</think>') %}
                {%- set _think_end = '</think>' %}
            {%- elif content.startswith('</thinking>') %}
                {%- set _think_end = '</thinking>' %}
            {%- elif '\n</think>' in content %}
                {%- set _think_end = '\n</think>' %}
            {%- elif '\n</thinking>' in content %}
                {%- set _think_end = '\n</thinking>' %}
            {%- elif '\n</ think>' in content %}
                {%- set _think_end = '\n</ think>' %}
            {%- elif '\n</think >' in content %}
                {%- set _think_end = '\n</think >' %}
            {%- elif content.startswith('<think>') and '</think>' in content %}
                {%- set _think_end = '</think>' %}
            {%- elif content.startswith('<thinking>') and '</thinking>' in content %}
                {%- set _think_end = '</thinking>' %}
            {%- endif %}
            {%- if _think_end %}
                {%- if 'thinking' in _think_end %}
                    {%- set _think_start = '<thinking>' %}
                {%- else %}
                    {%- set _think_start = '<think>' %}
                {%- endif %}
                {%- set reasoning_content = content.split(_think_end)[0].rstrip('\n') %}
                {%- if _think_start in reasoning_content %}
                    {%- set reasoning_content = reasoning_content.split(_think_start)[-1].lstrip('\n') %}
                {%- endif %}
                {%- set content = content.split(_think_end)[-1].lstrip('\n') %}
            {%- endif %}
        {%- endif %}
        {%- set reasoning_content = reasoning_content | trim %}
        {%- if (_preserve_thinking or loop.index0 > ns.last_query_index) %}
            {{- '<|im_start|>assistant\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
        {%- else %}
            {{- '<|im_start|>assistant\n' + content }}
        {%- endif %}
        {%- if message.tool_calls is defined and message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
            {%- for tool_call in message.tool_calls %}
                {%- if tool_call.function is defined and tool_call.function is not none %}
                    {%- set tc = tool_call.function %}
                {%- else %}
                    {%- set tc = tool_call %}
                {%- endif %}
                {%- set tc_name = tc.name if (tc.name is defined and tc.name is not none) else '' %}
                {%- if _tool_format == 'json' %}
                    {%- if loop.first %}
                        {%- if content | trim %}
                            {{- '\n\n' }}
                        {%- endif %}
                    {%- else %}
                        {{- '\n' }}
                    {%- endif %}
                    {%- set _args = '{}' %}
                    {%- if tc.arguments is defined and tc.arguments is not none %}
                        {%- if tc.arguments is mapping %}
                            {%- set _args = tc.arguments | tojson %}
                        {%- elif tc.arguments is string %}
                            {%- if tc.arguments %}
                                {%- set _args = tc.arguments %}
                            {%- endif %}
                        {%- else %}
                            {%- set _args = tc.arguments | tojson %}
                        {%- endif %}
                    {%- endif %}
                    {{- '<tool_call>\n{"name": ' }}{{- tc_name | tojson }}{{- ', "arguments": ' }}{{- _args }}{{- '}\n</tool_call>' }}
                {%- else %}
                    {%- if loop.first %}
                        {%- if content | trim %}
                            {{- '\n\n<tool_call>\n<function=' + tc_name + '>\n' }}
                        {%- else %}
                            {{- '<tool_call>\n<function=' + tc_name + '>\n' }}
                        {%- endif %}
                    {%- else %}
                        {{- '\n<tool_call>\n<function=' + tc_name + '>\n' }}
                    {%- endif %}
                    {%- if tc.arguments is defined and tc.arguments is not none %}
                        {%- if tc.arguments is mapping %}
                            {%- for args_name, args_value in tc.arguments.items() %}
                                {{- '<parameter=' + args_name + '>\n' }}
                                {%- if args_value is string %}
                                    {%- set _av = args_value %}
                                {%- else %}
                                    {%- set _av = args_value | tojson %}
                                {%- endif %}
                                {%- if max_tool_arg_chars > 0 and _av | length > max_tool_arg_chars %}
                                    {{- _av[:max_tool_arg_chars] + '\n[TRUNCATED - original length ' ~ (_av | length | string) ~ ' chars]' }}
                                {%- else %}
                                    {{- _av }}
                                {%- endif %}
                                {{- '\n</parameter>\n' }}
                            {%- endfor %}
                        {%- else %}
                            {%- if tc.arguments is string %}
                                {%- set _raw_args = tc.arguments %}
                            {%- else %}
                                {%- set _raw_args = tc.arguments | tojson %}
                            {%- endif %}
                            {%- if _raw_args %}
                                {%- if max_tool_arg_chars > 0 and _raw_args | length > max_tool_arg_chars %}
                                    {{- _raw_args[:max_tool_arg_chars] + '\n[TRUNCATED - original length ' ~ (_raw_args | length | string) ~ ' chars]' }}
                                {%- else %}
                                    {{- _raw_args }}
                                {%- endif %}
                            {%- endif %}
                        {%- endif %}
                    {%- endif %}
                    {{- '</function>\n</tool_call>' }}
                {%- endif %}
            {%- endfor %}
        {%- endif %}
        {{- '<|im_end|>\n' }}
    {%- elif message.role == 'tool' %}
        {%- set _content_lower = content | lower %}
        {%- set _content_head = _content_lower[:120] %}
        {%- set _is_code_or_grep = ('throw new ' in _content_lower or 'throw error' in _content_lower or 'console.error' in _content_lower or 'logger.error' in _content_lower or 'logging.error' in _content_lower or 'import ' in _content_head or 'def ' in _content_head or 'function ' in _content_head) %}
        {%- set _exit_code_zero = ('exit code: 0' in _content_head or 'process exited with code 0' in _content_head) %}
        {%- set _error_field_ok = ('"error": null' in _content_head or '"error":null' in _content_head or '"error": false' in _content_head or '"error":false' in _content_head or '"error": ""' in _content_head or '"error":""' in _content_head) %}
        {%- set _strong_error = (('"error":' in _content_head and not _error_field_ok) or '"status": "error"' in _content_head or '"status":"error"' in _content_head or 'traceback (most recent call last):' in _content_head or 'command not found' in _content_head or 'invalid syntax' in _content_head or 'fatal:' in _content_head or (('exit code: ' in _content_head or 'process exited with code' in _content_head) and not _exit_code_zero) or _content_head.startswith('exception:') or _content_head.startswith('failed to ')) %}
        {%- set _weak_error = ('error:' in _content_head or 'err!' in _content_head) %}
        {%- set _weak_suppressed = ('$ ' in _content_head or 'took ' in _content_head or content | length >= 600) %}
        {%- if not _is_code_or_grep and (_strong_error or (_weak_error and not _weak_suppressed)) %}
            {%- set ns2.consecutive_failures = ns2.consecutive_failures + 1 %}
        {%- else %}
            {%- set ns2.consecutive_failures = 0 %}
        {%- endif %}
        {%- if ns2.prev_role != 'tool' %}
            {{- '<|im_start|>user' }}
        {%- endif %}
        {%- set _is_json_payload = (_tool_format == 'json' and content | trim | length > 0 and (content | trim)[:1] in ('{', '[')) %}
        {%- if not _is_json_payload and max_tool_response_chars > 0 and content | length > max_tool_response_chars %}
            {%- set content = content[:max_tool_response_chars] + '\n[TRUNCATED - original length ' ~ (content | length | string) ~ ' chars]' %}
        {%- endif %}
        {{- '\n<tool_response>\n' + content }}
        {%- if ns2.consecutive_failures >= 2 %}
            {{- '\n\n⚠️ SYSTEM WARNING: ' ~ ns2.consecutive_failures ~ ' consecutive tool errors detected. Your previous approach is incorrect. You MUST use a fundamentally different approach or corrected arguments.' }}
        {%- elif ns2.consecutive_failures == 1 %}
            {{- '\n\n⚠️ SYSTEM WARNING: The previous tool call returned an error. Diagnose the failure and retry with completely corrected arguments.' }}
        {%- endif %}
        {{- '\n</tool_response>' }}
        {%- if loop.last %}
            {{- '<|im_end|>\n' }}
        {%- else %}
            {%- set _next_role = _msgs[loop.index0 + 1].role %}
            {%- if _next_role != 'tool' %}
                {{- '<|im_end|>\n' }}
            {%- endif %}
        {%- endif %}
    {%- else %}
        {{- '<|im_start|>user\n[' + message.role + ']: ' + content + '<|im_end|>\n' }}
    {%- endif %}
    {%- set ns2.prev_role = message.role %}
{%- endfor %}
{%- if add_generation_prompt %}
    {{- '<|im_start|>assistant\n' }}
    {%- if not ns_state.thinking %}
        {{- '<think>\n\n</think>\n\n' }}
    {%- else %}
        {{- '<think>\n' }}
    {%- endif %}
{%- endif %}