Instructions to use froggeric/Qwen-Fixed-Chat-Templates with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use froggeric/Qwen-Fixed-Chat-Templates with MLX:
# Download the model from the Hub pip install huggingface_hub[hf_xet] huggingface-cli download --local-dir Qwen-Fixed-Chat-Templates froggeric/Qwen-Fixed-Chat-Templates
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Atomic Chat
feat: Upgrade to v20 (The Architect Patch) with C++ AST optimization and deep agent loop fallbacks
Browse files- README.md +11 -3
- archive/v19_chat_template.jinja +265 -0
- archive/v19_chat_template_oneline.txt +1 -0
- chat_template.jinja +178 -156
- chat_template_oneline.txt +1 -1
- scripts/test_v18.py +0 -404
- scripts/test_v20.py +173 -0
README.md
CHANGED
|
@@ -14,9 +14,16 @@ tags:
|
|
| 14 |
- thinking
|
| 15 |
---
|
| 16 |
|
| 17 |
-
# Fixed jinja chat templates for Qwen 3.5 & 3.6 (
|
| 18 |
|
| 19 |
<details open>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
<summary><b>Update History & Changelog (v19)</b></summary>
|
| 21 |
|
| 22 |
> **2026-05-18 Update (v19): The Agentic Loop Cure.** (1) **Abolished "Empty Think" Poisoning:** Rewrote the AST history rendering to completely remove the injection of empty `<think>\n</think>` blocks. This cures a severe in-context learning bias where the model assumed tools could only be called if it didn't think first, which was causing 80%+ of premature `<|im_end|>` turn aborts. (2) **System Prompt Logic Trap Removed:** Softened the absolute tool mandate in the `<IMPORTANT>` block and restored Universal Synthesis instructions. The model is now explicitly permitted to transition from `</think>` to a conversational answer without panicking. (3) **True 100% KV Cache & Amnesia Fix:** `preserve_thinking` now defaults to `true`. Past thoughts are retained chronologically, permanently curing "amnesia stalls" during multi-step tool loops while mathematically guaranteeing 100% KV Cache prefix matching out-of-the-box.
|
|
@@ -211,10 +218,10 @@ Python-only Jinja2 features crash on `minijinja` (the C++ runtime used by llama.
|
|
| 211 |
## Running the test suite
|
| 212 |
|
| 213 |
```bash
|
| 214 |
-
python3 scripts/
|
| 215 |
```
|
| 216 |
|
| 217 |
-
Tests cover:
|
| 218 |
|
| 219 |
---
|
| 220 |
|
|
@@ -224,6 +231,7 @@ Tests cover: XML tool format, tool instructions, thinking bypass, `<|think_off|>
|
|
| 224 |
|------|--------|
|
| 225 |
| Original models | Alibaba Cloud (Qwen team) |
|
| 226 |
| Template fixes | [froggeric](https://huggingface.co/froggeric) |
|
|
|
|
| 227 |
|
| 228 |
## License
|
| 229 |
|
|
|
|
| 14 |
- thinking
|
| 15 |
---
|
| 16 |
|
| 17 |
+
# Fixed jinja chat templates for Qwen 3.5 & 3.6 (v20)
|
| 18 |
|
| 19 |
<details open>
|
| 20 |
+
<summary><b>Update History & Changelog (v20)</b></summary>
|
| 21 |
+
|
| 22 |
+
> **2026-06-05 Update (v20): The Architect Patch.** A monumental structural overhaul targeting deep agentic loops and C++ inference engine compatibility. (1) **Minja AST Flattening:** Dramatically optimized Jinja nesting depths to resolve severe parsing bottlenecks that were dropping inference throughput by 80% on `llama.cpp`. (2) **Auto-disable Thinking:** Introduced `auto_disable_thinking_with_tools` kwarg (default `false`) that allows users to instantly shut off reasoning blocks during tool use to completely prevent `<tool_call>` hallucinations inside `<think>` tags. (3) **Deep Agent Fallbacks:** Resolved exceptions triggered by mid-conversation system prompts or loops lacking human `user` messages. (4) **Payload Truncation:** Implemented `max_tool_arg_chars` and `max_tool_response_chars` configurations to definitively stop context-window explosions from massive data returns. *(Huge thanks to `barubary` / `spiritbuun` for their contributions to these C++ architecture optimizations!)*
|
| 23 |
+
|
| 24 |
+
</details>
|
| 25 |
+
|
| 26 |
+
<details>
|
| 27 |
<summary><b>Update History & Changelog (v19)</b></summary>
|
| 28 |
|
| 29 |
> **2026-05-18 Update (v19): The Agentic Loop Cure.** (1) **Abolished "Empty Think" Poisoning:** Rewrote the AST history rendering to completely remove the injection of empty `<think>\n</think>` blocks. This cures a severe in-context learning bias where the model assumed tools could only be called if it didn't think first, which was causing 80%+ of premature `<|im_end|>` turn aborts. (2) **System Prompt Logic Trap Removed:** Softened the absolute tool mandate in the `<IMPORTANT>` block and restored Universal Synthesis instructions. The model is now explicitly permitted to transition from `</think>` to a conversational answer without panicking. (3) **True 100% KV Cache & Amnesia Fix:** `preserve_thinking` now defaults to `true`. Past thoughts are retained chronologically, permanently curing "amnesia stalls" during multi-step tool loops while mathematically guaranteeing 100% KV Cache prefix matching out-of-the-box.
|
|
|
|
| 218 |
## Running the test suite
|
| 219 |
|
| 220 |
```bash
|
| 221 |
+
python3 scripts/test_v20.py
|
| 222 |
```
|
| 223 |
|
| 224 |
+
Tests cover: `auto_disable_thinking_with_tools`, payload truncation logic, parallel tool spacing, mid-conversation system rendering, deep agent loop fallback, XML tool format, `<|think_off|>` / `<|think_on|>` inline overrides, and all legacy v19 regression tests.
|
| 225 |
|
| 226 |
---
|
| 227 |
|
|
|
|
| 231 |
|------|--------|
|
| 232 |
| Original models | Alibaba Cloud (Qwen team) |
|
| 233 |
| Template fixes | [froggeric](https://huggingface.co/froggeric) |
|
| 234 |
+
| C++ AST optimizations | [barubary](https://github.com/spiritbuun/buun-llama-cpp) / `spiritbuun` |
|
| 235 |
|
| 236 |
## License
|
| 237 |
|
archive/v19_chat_template.jinja
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{%- set image_count = namespace(value=0) %}
|
| 2 |
+
{%- set video_count = namespace(value=0) %}
|
| 3 |
+
{%- macro render_content(content, do_vision_count, is_system_content=false) %}
|
| 4 |
+
{%- if content is string %}
|
| 5 |
+
{{- content }}
|
| 6 |
+
{%- elif content is iterable and content is not mapping %}
|
| 7 |
+
{%- for item in content %}
|
| 8 |
+
{%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
|
| 9 |
+
{%- if is_system_content %}
|
| 10 |
+
{{- raise_exception('System message cannot contain images.') }}
|
| 11 |
+
{%- endif %}
|
| 12 |
+
{%- if do_vision_count %}
|
| 13 |
+
{%- set image_count.value = image_count.value + 1 %}
|
| 14 |
+
{%- endif %}
|
| 15 |
+
{%- if add_vision_id is defined and add_vision_id %}
|
| 16 |
+
{{- 'Picture ' ~ image_count.value ~ ': ' }}
|
| 17 |
+
{%- endif %}
|
| 18 |
+
{{- '<|vision_start|><|image_pad|><|vision_end|>' }}
|
| 19 |
+
{%- elif 'video' in item or item.type == 'video' %}
|
| 20 |
+
{%- if is_system_content %}
|
| 21 |
+
{{- raise_exception('System message cannot contain videos.') }}
|
| 22 |
+
{%- endif %}
|
| 23 |
+
{%- if do_vision_count %}
|
| 24 |
+
{%- set video_count.value = video_count.value + 1 %}
|
| 25 |
+
{%- endif %}
|
| 26 |
+
{%- if add_vision_id is defined and add_vision_id %}
|
| 27 |
+
{{- 'Video ' ~ video_count.value ~ ': ' }}
|
| 28 |
+
{%- endif %}
|
| 29 |
+
{{- '<|vision_start|><|video_pad|><|vision_end|>' }}
|
| 30 |
+
{%- elif 'text' in item %}
|
| 31 |
+
{{- item.text }}
|
| 32 |
+
{%- else %}
|
| 33 |
+
{{- raise_exception('Unexpected item type in content.') }}
|
| 34 |
+
{%- endif %}
|
| 35 |
+
{%- endfor %}
|
| 36 |
+
{%- elif content is none or content is undefined %}
|
| 37 |
+
{{- '' }}
|
| 38 |
+
{%- else %}
|
| 39 |
+
{{- raise_exception('Unexpected content type.') }}
|
| 40 |
+
{%- endif %}
|
| 41 |
+
{%- endmacro %}
|
| 42 |
+
{%- set ns_flags = namespace(enable_thinking=true, has_tools=false, last_tool_failed=false, consecutive_failures=0) %}
|
| 43 |
+
{%- if enable_thinking is defined %}
|
| 44 |
+
{%- set ns_flags.enable_thinking = enable_thinking %}
|
| 45 |
+
{%- endif %}
|
| 46 |
+
{%- if not messages %}
|
| 47 |
+
{{- raise_exception('No messages provided.') }}
|
| 48 |
+
{%- endif %}
|
| 49 |
+
{%- set system_content = '' %}
|
| 50 |
+
{%- set has_system = false %}
|
| 51 |
+
{%- if messages[0].role == 'system' or messages[0].role == 'developer' %}
|
| 52 |
+
{%- set has_system = true %}
|
| 53 |
+
{%- set system_content = render_content(messages[0].content, false, true)|trim %}
|
| 54 |
+
{%- if '<|think_off|>' in system_content %}
|
| 55 |
+
{%- set ns_flags.enable_thinking = false %}
|
| 56 |
+
{%- set system_content = system_content | replace('<|think_off|>', '') %}
|
| 57 |
+
{%- endif %}
|
| 58 |
+
{%- if '<|think_on|>' in system_content %}
|
| 59 |
+
{%- set ns_flags.enable_thinking = true %}
|
| 60 |
+
{%- set system_content = system_content | replace('<|think_on|>', '') %}
|
| 61 |
+
{%- endif %}
|
| 62 |
+
{%- set system_content = system_content | trim %}
|
| 63 |
+
{%- endif %}
|
| 64 |
+
{%- if tools and tools is iterable and tools is not mapping %}
|
| 65 |
+
{%- set ns_flags.has_tools = true %}
|
| 66 |
+
{{- '<|im_start|>system\n' }}
|
| 67 |
+
{{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
|
| 68 |
+
{%- for tool in tools %}
|
| 69 |
+
{{- '\n' }}
|
| 70 |
+
{%- set fn = tool.function if tool.function is defined else tool %}
|
| 71 |
+
{{- fn | tojson }}
|
| 72 |
+
{%- endfor %}
|
| 73 |
+
{{- "\n</tools>" }}
|
| 74 |
+
{%- set tool_instructions %}
|
| 75 |
+
If you choose to call a function ONLY reply in the following format with NO suffix:
|
| 76 |
+
|
| 77 |
+
<think>
|
| 78 |
+
Brief explanation of tool call
|
| 79 |
+
</think>
|
| 80 |
+
<tool_call>
|
| 81 |
+
<function=example_function_name>
|
| 82 |
+
<parameter=example_parameter_1>
|
| 83 |
+
value_1
|
| 84 |
+
</parameter>
|
| 85 |
+
<parameter=example_parameter_2>
|
| 86 |
+
This is the value for the second parameter
|
| 87 |
+
that can span
|
| 88 |
+
multiple lines
|
| 89 |
+
</parameter>
|
| 90 |
+
</function>
|
| 91 |
+
</tool_call>
|
| 92 |
+
|
| 93 |
+
<IMPORTANT>
|
| 94 |
+
Reminder:
|
| 95 |
+
- 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.
|
| 96 |
+
- ALL explanation and reasoning MUST be placed strictly inside the <think></think> block.
|
| 97 |
+
- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags.
|
| 98 |
+
- If you choose to call a tool, you MUST output the <tool_call> block IMMEDIATELY after closing </think>. Do NOT output any conversational text before the tool call.
|
| 99 |
+
- The <tool_call> and <function> tags MUST be at the very beginning of a new line, with NO spaces or indentation before them.
|
| 100 |
+
- To call multiple functions, output a separate, completely closed <tool_call></tool_call> block for EACH function. Do NOT nest <tool_call> blocks.
|
| 101 |
+
- If you have gathered all necessary data and do not need to call a tool, answer the question like normal and provide your final response to the user IMMEDIATELY after closing </think>.
|
| 102 |
+
</IMPORTANT>
|
| 103 |
+
{%- endset %}
|
| 104 |
+
{{- '\n\n' ~ tool_instructions | trim }}
|
| 105 |
+
{%- if has_system and system_content %}
|
| 106 |
+
{{- '\n\n' + system_content }}
|
| 107 |
+
{%- endif %}
|
| 108 |
+
{{- '<|im_end|>\n' }}
|
| 109 |
+
{%- elif has_system and system_content %}
|
| 110 |
+
{{- '<|im_start|>system\n' + system_content + '<|im_end|>\n' }}
|
| 111 |
+
{%- endif %}
|
| 112 |
+
{%- for message in messages %}
|
| 113 |
+
{%- set is_system = (message.role == "system" or message.role == "developer") %}
|
| 114 |
+
{%- set content = render_content(message.content, true, is_system)|trim %}
|
| 115 |
+
{%- if '<|think_off|>' in content %}
|
| 116 |
+
{%- set ns_flags.enable_thinking = false %}
|
| 117 |
+
{%- set content = content | replace('<|think_off|>', '') | trim %}
|
| 118 |
+
{%- elif '<|think_on|>' in content %}
|
| 119 |
+
{%- set ns_flags.enable_thinking = true %}
|
| 120 |
+
{%- set content = content | replace('<|think_on|>', '') | trim %}
|
| 121 |
+
{%- endif %}
|
| 122 |
+
{%- if is_system %}
|
| 123 |
+
{%- if not loop.first and content %}
|
| 124 |
+
{{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
|
| 125 |
+
{%- endif %}
|
| 126 |
+
{%- elif message.role == "user" %}
|
| 127 |
+
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>\n' }}
|
| 128 |
+
{%- set ns_flags.last_tool_failed = false %}
|
| 129 |
+
{%- set ns_flags.consecutive_failures = 0 %}
|
| 130 |
+
{%- elif message.role == "assistant" %}
|
| 131 |
+
{%- set ns_flags.last_tool_failed = false %}
|
| 132 |
+
{%- set reasoning_content = '' %}
|
| 133 |
+
{%- if message.reasoning_content is string %}
|
| 134 |
+
{%- set reasoning_content = message.reasoning_content %}
|
| 135 |
+
{%- else %}
|
| 136 |
+
{%- set think_end_token = '' %}
|
| 137 |
+
{%- if '</think>' in content %}
|
| 138 |
+
{%- set think_end_token = '</think>' %}
|
| 139 |
+
{%- elif '</thinking>' in content %}
|
| 140 |
+
{%- set think_end_token = '</thinking>' %}
|
| 141 |
+
{%- elif '</ think>' in content %}
|
| 142 |
+
{%- set think_end_token = '</ think>' %}
|
| 143 |
+
{%- elif '</think >' in content %}
|
| 144 |
+
{%- set think_end_token = '</think >' %}
|
| 145 |
+
{%- endif %}
|
| 146 |
+
{%- if think_end_token %}
|
| 147 |
+
{%- set reasoning_parts = content.split(think_end_token) %}
|
| 148 |
+
{%- set reasoning_content = reasoning_parts[0] %}
|
| 149 |
+
{%- set content = reasoning_parts[1:] | join(think_end_token) %}
|
| 150 |
+
{%- if '<think>' in reasoning_content %}
|
| 151 |
+
{%- set r_prefix = reasoning_content.split('<think>')[0] | trim %}
|
| 152 |
+
{%- set reasoning_content = reasoning_content.split('<think>')[1:] | join('<think>') | trim %}
|
| 153 |
+
{%- set content = (r_prefix ~ '\n' ~ content) | trim %}
|
| 154 |
+
{%- endif %}
|
| 155 |
+
{%- elif '<think>' in content %}
|
| 156 |
+
{%- set prefix = content.split('<think>')[0] %}
|
| 157 |
+
{%- set think_part = content.split('<think>')[1:] | join('<think>') %}
|
| 158 |
+
{%- if '<tool_call>' in think_part %}
|
| 159 |
+
{%- set reasoning_content = think_part.split('<tool_call>')[0] %}
|
| 160 |
+
{%- set content = prefix ~ '\n<tool_call>' ~ think_part.split('<tool_call>')[1:] | join('<tool_call>') %}
|
| 161 |
+
{%- else %}
|
| 162 |
+
{%- set reasoning_content = think_part %}
|
| 163 |
+
{%- set content = prefix %}
|
| 164 |
+
{%- endif %}
|
| 165 |
+
{%- endif %}
|
| 166 |
+
{%- endif %}
|
| 167 |
+
{%- set reasoning_content = reasoning_content | trim %}
|
| 168 |
+
{%- set content = content | trim %}
|
| 169 |
+
{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
|
| 170 |
+
{%- if '<tool_call>' in content %}
|
| 171 |
+
{%- set content = content.split('<tool_call>')[0] | trim %}
|
| 172 |
+
{%- endif %}
|
| 173 |
+
{%- endif %}
|
| 174 |
+
{%- set show_think = true %}
|
| 175 |
+
{%- if preserve_thinking is defined and preserve_thinking == false %}
|
| 176 |
+
{%- set show_think = false %}
|
| 177 |
+
{%- endif %}
|
| 178 |
+
{%- if not reasoning_content %}
|
| 179 |
+
{%- set show_think = false %}
|
| 180 |
+
{%- endif %}
|
| 181 |
+
|
| 182 |
+
{%- if show_think and ns_flags.enable_thinking is not false %}
|
| 183 |
+
{%- if content %}
|
| 184 |
+
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n' + content }}
|
| 185 |
+
{%- else %}
|
| 186 |
+
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>' }}
|
| 187 |
+
{%- endif %}
|
| 188 |
+
{%- else %}
|
| 189 |
+
{%- if content %}
|
| 190 |
+
{{- '<|im_start|>' + message.role + '\n' + content }}
|
| 191 |
+
{%- else %}
|
| 192 |
+
{{- '<|im_start|>' + message.role }}
|
| 193 |
+
{%- endif %}
|
| 194 |
+
{%- endif %}
|
| 195 |
+
{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
|
| 196 |
+
{%- for tool_call in message.tool_calls %}
|
| 197 |
+
{%- if tool_call.function is defined %}
|
| 198 |
+
{%- set tool_call = tool_call.function %}
|
| 199 |
+
{%- endif %}
|
| 200 |
+
{{- '\n<tool_call>\n' }}
|
| 201 |
+
{{- '<function=' ~ tool_call.name ~ '>\n' }}
|
| 202 |
+
{%- if tool_call.arguments is defined and tool_call.arguments is mapping %}
|
| 203 |
+
{%- if tool_call.arguments | length > 0 %}
|
| 204 |
+
{%- for args_name in tool_call.arguments %}
|
| 205 |
+
{%- set args_value = tool_call.arguments[args_name] %}
|
| 206 |
+
{{- '<parameter=' ~ args_name ~ '>\n' }}
|
| 207 |
+
{%- set args_value = args_value | tojson if args_value is mapping or (args_value is iterable and args_value is not string) else args_value | string %}
|
| 208 |
+
{{- args_value }}
|
| 209 |
+
{{- '\n</parameter>\n' }}
|
| 210 |
+
{%- endfor %}
|
| 211 |
+
{%- endif %}
|
| 212 |
+
{%- elif tool_call.arguments is defined and tool_call.arguments is string %}
|
| 213 |
+
{%- if tool_call.arguments | trim | length > 0 %}
|
| 214 |
+
{{- tool_call.arguments }}
|
| 215 |
+
{{- '\n' }}
|
| 216 |
+
{%- endif %}
|
| 217 |
+
{%- endif %}
|
| 218 |
+
{{- '</function>\n</tool_call>' }}
|
| 219 |
+
{%- endfor %}
|
| 220 |
+
{%- endif %}
|
| 221 |
+
{{- '<|im_end|>\n' }}
|
| 222 |
+
{%- elif message.role == "tool" %}
|
| 223 |
+
{%- set content_lower = content | lower %}
|
| 224 |
+
{%- if content | length < 500
|
| 225 |
+
and '$ ' not in content
|
| 226 |
+
and 'took ' not in content_lower
|
| 227 |
+
and ('"error":' in content_lower or 'error:' in content_lower or 'exception:' in content_lower or 'traceback' in content_lower or 'command not found' in content_lower or 'invalid syntax' in content_lower or 'failed to' in content_lower) %}
|
| 228 |
+
{%- set ns_flags.last_tool_failed = true %}
|
| 229 |
+
{%- set ns_flags.consecutive_failures = ns_flags.consecutive_failures + 1 %}
|
| 230 |
+
{%- else %}
|
| 231 |
+
{%- set ns_flags.last_tool_failed = false %}
|
| 232 |
+
{%- set ns_flags.consecutive_failures = 0 %}
|
| 233 |
+
{%- endif %}
|
| 234 |
+
{%- if loop.index0 > 0 and messages[loop.index0 - 1].role != "tool" %}
|
| 235 |
+
{{- '<|im_start|>user' }}
|
| 236 |
+
{%- endif %}
|
| 237 |
+
{{- '\n<tool_response>\n' }}
|
| 238 |
+
{{- content }}
|
| 239 |
+
{%- if ns_flags.last_tool_failed %}
|
| 240 |
+
{%- if ns_flags.consecutive_failures >= 2 %}
|
| 241 |
+
{{- '\n\n⚠️ SYSTEM WARNING: ' ~ ns_flags.consecutive_failures ~ ' consecutive tool errors detected. Your previous approach is incorrect. You MUST use a fundamentally different approach or corrected arguments.' }}
|
| 242 |
+
{%- else %}
|
| 243 |
+
{{- '\n\n⚠️ SYSTEM WARNING: The previous tool call returned an error. Diagnose the failure and retry with completely corrected arguments.' }}
|
| 244 |
+
{%- endif %}
|
| 245 |
+
{%- endif %}
|
| 246 |
+
{{- '\n</tool_response>' }}
|
| 247 |
+
{%- if not loop.last and messages[loop.index0 + 1].role != "tool" %}
|
| 248 |
+
{{- '<|im_end|>\n' }}
|
| 249 |
+
{%- elif loop.last %}
|
| 250 |
+
{{- '<|im_end|>\n' }}
|
| 251 |
+
{%- endif %}
|
| 252 |
+
{%- else %}
|
| 253 |
+
{{- raise_exception('Unexpected message role.') }}
|
| 254 |
+
{%- endif %}
|
| 255 |
+
{%- endfor %}
|
| 256 |
+
{%- if add_generation_prompt %}
|
| 257 |
+
{{- '<|im_start|>assistant\n' }}
|
| 258 |
+
{%- if ns_flags.enable_thinking is false %}
|
| 259 |
+
{{- '<think>\n</think>\n' }}
|
| 260 |
+
{%- elif ns_flags.last_tool_failed and ns_flags.consecutive_failures >= 2 %}
|
| 261 |
+
{{- '<think>\n</think>\n' }}
|
| 262 |
+
{%- else %}
|
| 263 |
+
{{- '<think>\n' }}
|
| 264 |
+
{%- endif %}
|
| 265 |
+
{%- endif %}
|
archive/v19_chat_template_oneline.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{%- set image_count = namespace(value=0) %}{%- set video_count = namespace(value=0) %}{%- 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 'image' in item or 'image_url' in item or item.type == 'image' %}{%- 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 is defined and add_vision_id %}{{- 'Picture ' ~ image_count.value ~ ': ' }}{%- endif %}{{- '<|vision_start|><|image_pad|><|vision_end|>' }}{%- elif 'video' in item or item.type == 'video' %}{%- 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 is defined and 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 %}{%- endfor %}{%- elif content is none or content is undefined %}{{- '' }}{%- else %}{{- raise_exception('Unexpected content type.') }}{%- endif %}{%- endmacro %}{%- set ns_flags = namespace(enable_thinking=true, has_tools=false, last_tool_failed=false, consecutive_failures=0) %}{%- if enable_thinking is defined %}{%- set ns_flags.enable_thinking = enable_thinking %}{%- endif %}{%- if not messages %}{{- raise_exception('No messages provided.') }}{%- endif %}{%- set system_content = '' %}{%- set has_system = false %}{%- if messages[0].role == 'system' or messages[0].role == 'developer' %}{%- set has_system = true %}{%- set system_content = render_content(messages[0].content, false, true)|trim %}{%- if '<|think_off|>' in system_content %}{%- set ns_flags.enable_thinking = false %}{%- set system_content = system_content | replace('<|think_off|>', '') %}{%- endif %}{%- if '<|think_on|>' in system_content %}{%- set ns_flags.enable_thinking = true %}{%- set system_content = system_content | replace('<|think_on|>', '') %}{%- endif %}{%- set system_content = system_content | trim %}{%- endif %}{%- if tools and tools is iterable and tools is not mapping %}{%- set ns_flags.has_tools = true %}{{- '<|im_start|>system\n' }}{{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}{%- for tool in tools %}{{- '\n' }}{%- set fn = tool.function if tool.function is defined else tool %}{{- fn | tojson }}{%- endfor %}{{- "\n</tools>" }}{%- set tool_instructions %} If you choose to call a function ONLY reply in the following format with NO suffix: <think> Brief explanation of tool call </think> <tool_call> <function=example_function_name> <parameter=example_parameter_1> value_1 </parameter> <parameter=example_parameter_2> This is the value for the second parameter that can span multiple lines </parameter> </function> </tool_call> <IMPORTANT> Reminder: - 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. - ALL explanation and reasoning MUST be placed strictly inside the <think></think> block. - Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags. - If you choose to call a tool, you MUST output the <tool_call> block IMMEDIATELY after closing </think>. Do NOT output any conversational text before the tool call. - The <tool_call> and <function> tags MUST be at the very beginning of a new line, with NO spaces or indentation before them. - To call multiple functions, output a separate, completely closed <tool_call></tool_call> block for EACH function. Do NOT nest <tool_call> blocks. - If you have gathered all necessary data and do not need to call a tool, answer the question like normal and provide your final response to the user IMMEDIATELY after closing </think>. </IMPORTANT> {%- endset %}{{- '\n\n' ~ tool_instructions | trim }}{%- if has_system and system_content %}{{- '\n\n' + system_content }}{%- endif %}{{- '<|im_end|>\n' }}{%- elif has_system and system_content %}{{- '<|im_start|>system\n' + system_content + '<|im_end|>\n' }}{%- endif %}{%- for message in messages %}{%- set is_system = (message.role == "system" or message.role == "developer") %}{%- set content = render_content(message.content, true, is_system)|trim %}{%- if '<|think_off|>' in content %}{%- set ns_flags.enable_thinking = false %}{%- set content = content | replace('<|think_off|>', '') | trim %}{%- elif '<|think_on|>' in content %}{%- set ns_flags.enable_thinking = true %}{%- set content = content | replace('<|think_on|>', '') | trim %}{%- endif %}{%- if is_system %}{%- if not loop.first and content %}{{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}{%- endif %}{%- elif message.role == "user" %}{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>\n' }}{%- set ns_flags.last_tool_failed = false %}{%- set ns_flags.consecutive_failures = 0 %}{%- elif message.role == "assistant" %}{%- set ns_flags.last_tool_failed = false %}{%- set reasoning_content = '' %}{%- if message.reasoning_content is string %}{%- set reasoning_content = message.reasoning_content %}{%- else %}{%- set think_end_token = '' %}{%- if '</think>' in content %}{%- set think_end_token = '</think>' %}{%- elif '</thinking>' in content %}{%- set think_end_token = '</thinking>' %}{%- elif '</ think>' in content %}{%- set think_end_token = '</ think>' %}{%- elif '</think >' in content %}{%- set think_end_token = '</think >' %}{%- endif %}{%- if think_end_token %}{%- set reasoning_parts = content.split(think_end_token) %}{%- set reasoning_content = reasoning_parts[0] %}{%- set content = reasoning_parts[1:] | join(think_end_token) %}{%- if '<think>' in reasoning_content %}{%- set r_prefix = reasoning_content.split('<think>')[0] | trim %}{%- set reasoning_content = reasoning_content.split('<think>')[1:] | join('<think>') | trim %}{%- set content = (r_prefix ~ '\n' ~ content) | trim %}{%- endif %}{%- elif '<think>' in content %}{%- set prefix = content.split('<think>')[0] %}{%- set think_part = content.split('<think>')[1:] | join('<think>') %}{%- if '<tool_call>' in think_part %}{%- set reasoning_content = think_part.split('<tool_call>')[0] %}{%- set content = prefix ~ '\n<tool_call>' ~ think_part.split('<tool_call>')[1:] | join('<tool_call>') %}{%- else %}{%- set reasoning_content = think_part %}{%- set content = prefix %}{%- endif %}{%- endif %}{%- endif %}{%- set reasoning_content = reasoning_content | trim %}{%- set content = content | trim %}{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}{%- if '<tool_call>' in content %}{%- set content = content.split('<tool_call>')[0] | trim %}{%- endif %}{%- endif %}{%- set show_think = true %}{%- if preserve_thinking is defined and preserve_thinking == false %}{%- set show_think = false %}{%- endif %}{%- if not reasoning_content %}{%- set show_think = false %}{%- endif %}{%- if show_think and ns_flags.enable_thinking is not false %}{%- if content %}{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n' + content }}{%- else %}{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>' }}{%- endif %}{%- else %}{%- if content %}{{- '<|im_start|>' + message.role + '\n' + content }}{%- else %}{{- '<|im_start|>' + message.role }}{%- endif %}{%- endif %}{%- if 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 %}{%- set tool_call = tool_call.function %}{%- endif %}{{- '\n<tool_call>\n' }}{{- '<function=' ~ tool_call.name ~ '>\n' }}{%- if tool_call.arguments is defined and tool_call.arguments is mapping %}{%- if tool_call.arguments | length > 0 %}{%- for args_name in tool_call.arguments %}{%- set args_value = tool_call.arguments[args_name] %}{{- '<parameter=' ~ args_name ~ '>\n' }}{%- set args_value = args_value | tojson if args_value is mapping or (args_value is iterable and args_value is not string) else args_value | string %}{{- args_value }}{{- '\n</parameter>\n' }}{%- endfor %}{%- endif %}{%- elif tool_call.arguments is defined and tool_call.arguments is string %}{%- if tool_call.arguments | trim | length > 0 %}{{- tool_call.arguments }}{{- '\n' }}{%- endif %}{%- endif %}{{- '</function>\n</tool_call>' }}{%- endfor %}{%- endif %}{{- '<|im_end|>\n' }}{%- elif message.role == "tool" %}{%- set content_lower = content | lower %}{%- if content | length < 500 and '$ ' not in content and 'took ' not in content_lower and ('"error":' in content_lower or 'error:' in content_lower or 'exception:' in content_lower or 'traceback' in content_lower or 'command not found' in content_lower or 'invalid syntax' in content_lower or 'failed to' in content_lower) %}{%- set ns_flags.last_tool_failed = true %}{%- set ns_flags.consecutive_failures = ns_flags.consecutive_failures + 1 %}{%- else %}{%- set ns_flags.last_tool_failed = false %}{%- set ns_flags.consecutive_failures = 0 %}{%- endif %}{%- if loop.index0 > 0 and messages[loop.index0 - 1].role != "tool" %}{{- '<|im_start|>user' }}{%- endif %}{{- '\n<tool_response>\n' }}{{- content }}{%- if ns_flags.last_tool_failed %}{%- if ns_flags.consecutive_failures >= 2 %}{{- '\n\n⚠️ SYSTEM WARNING: ' ~ ns_flags.consecutive_failures ~ ' consecutive tool errors detected. Your previous approach is incorrect. You MUST use a fundamentally different approach or corrected arguments.' }}{%- else %}{{- '\n\n⚠️ SYSTEM WARNING: The previous tool call returned an error. Diagnose the failure and retry with completely corrected arguments.' }}{%- endif %}{%- endif %}{{- '\n</tool_response>' }}{%- if not loop.last and messages[loop.index0 + 1].role != "tool" %}{{- '<|im_end|>\n' }}{%- elif loop.last %}{{- '<|im_end|>\n' }}{%- endif %}{%- else %}{{- raise_exception('Unexpected message role.') }}{%- endif %}{%- endfor %}{%- if add_generation_prompt %}{{- '<|im_start|>assistant\n' }}{%- if ns_flags.enable_thinking is false %}{{- '<think>\n</think>\n' }}{%- elif ns_flags.last_tool_failed and ns_flags.consecutive_failures >= 2 %}{{- '<think>\n</think>\n' }}{%- else %}{{- '<think>\n' }}{%- endif %}{%- endif %}
|
chat_template.jinja
CHANGED
|
@@ -1,36 +1,52 @@
|
|
|
|
|
| 1 |
{%- set image_count = namespace(value=0) %}
|
| 2 |
{%- set video_count = namespace(value=0) %}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
{%- macro render_content(content, do_vision_count, is_system_content=false) %}
|
| 4 |
{%- if content is string %}
|
| 5 |
{{- content }}
|
| 6 |
{%- elif content is iterable and content is not mapping %}
|
| 7 |
{%- for item in content %}
|
| 8 |
-
{%- if
|
| 9 |
-
{%- if
|
| 10 |
-
{
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
{%-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
{
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
{%-
|
| 21 |
-
{
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
{%-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
{%- endif %}
|
| 29 |
-
{{- '<|vision_start|><|video_pad|><|vision_end|>' }}
|
| 30 |
-
{%- elif 'text' in item %}
|
| 31 |
-
{{- item.text }}
|
| 32 |
{%- else %}
|
| 33 |
-
{{-
|
| 34 |
{%- endif %}
|
| 35 |
{%- endfor %}
|
| 36 |
{%- elif content is none or content is undefined %}
|
|
@@ -39,38 +55,36 @@
|
|
| 39 |
{{- raise_exception('Unexpected content type.') }}
|
| 40 |
{%- endif %}
|
| 41 |
{%- endmacro %}
|
| 42 |
-
{%- set ns_flags = namespace(enable_thinking=true, has_tools=false, last_tool_failed=false, consecutive_failures=0) %}
|
| 43 |
-
{%- if enable_thinking is defined %}
|
| 44 |
-
{%- set ns_flags.enable_thinking = enable_thinking %}
|
| 45 |
-
{%- endif %}
|
| 46 |
{%- if not messages %}
|
| 47 |
{{- raise_exception('No messages provided.') }}
|
| 48 |
{%- endif %}
|
| 49 |
-
{%- set
|
| 50 |
-
{%-
|
| 51 |
-
{%-
|
| 52 |
-
{%- set
|
| 53 |
-
|
| 54 |
-
{%-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
{%- endif %}
|
| 62 |
-
{%- set system_content = system_content | trim %}
|
| 63 |
{%- endif %}
|
| 64 |
-
{%- if
|
| 65 |
-
{%- set ns_flags.has_tools = true %}
|
| 66 |
{{- '<|im_start|>system\n' }}
|
| 67 |
-
{{-
|
| 68 |
{%- for tool in tools %}
|
| 69 |
{{- '\n' }}
|
| 70 |
-
{
|
| 71 |
-
{{- fn | tojson }}
|
| 72 |
{%- endfor %}
|
| 73 |
-
{{-
|
| 74 |
{%- set tool_instructions %}
|
| 75 |
If you choose to call a function ONLY reply in the following format with NO suffix:
|
| 76 |
|
|
@@ -102,162 +116,170 @@ Reminder:
|
|
| 102 |
</IMPORTANT>
|
| 103 |
{%- endset %}
|
| 104 |
{{- '\n\n' ~ tool_instructions | trim }}
|
| 105 |
-
{%- if
|
| 106 |
-
{{- '\n\n' +
|
| 107 |
{%- endif %}
|
| 108 |
{{- '<|im_end|>\n' }}
|
| 109 |
-
{%-
|
| 110 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
{%- endif %}
|
| 112 |
-
{%-
|
|
|
|
| 113 |
{%- set is_system = (message.role == "system" or message.role == "developer") %}
|
| 114 |
-
{%- set content = render_content(message.content, true, is_system)|trim %}
|
| 115 |
{%- if '<|think_off|>' in content %}
|
| 116 |
-
{%- set
|
| 117 |
{%- set content = content | replace('<|think_off|>', '') | trim %}
|
| 118 |
{%- elif '<|think_on|>' in content %}
|
| 119 |
-
{%- set
|
| 120 |
{%- set content = content | replace('<|think_on|>', '') | trim %}
|
| 121 |
{%- endif %}
|
| 122 |
{%- if is_system %}
|
| 123 |
-
{
|
| 124 |
-
|
| 125 |
-
{%-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
{%- set ns_flags.last_tool_failed = false %}
|
| 129 |
-
{%- set ns_flags.consecutive_failures = 0 %}
|
| 130 |
-
{%- elif message.role == "assistant" %}
|
| 131 |
-
{%- set ns_flags.last_tool_failed = false %}
|
| 132 |
{%- set reasoning_content = '' %}
|
| 133 |
-
{%- if message.reasoning_content is
|
| 134 |
-
{%-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
{%- else %}
|
| 136 |
-
{%- set
|
| 137 |
{%- if '</think>' in content %}
|
| 138 |
-
{%- set
|
| 139 |
{%- elif '</thinking>' in content %}
|
| 140 |
-
{%- set
|
| 141 |
{%- elif '</ think>' in content %}
|
| 142 |
-
{%- set
|
| 143 |
{%- elif '</think >' in content %}
|
| 144 |
-
{%- set
|
| 145 |
{%- endif %}
|
| 146 |
-
{%- if
|
| 147 |
-
{%-
|
| 148 |
-
|
| 149 |
-
{%- set content = reasoning_parts[1:] | join(think_end_token) %}
|
| 150 |
-
{%- if '<think>' in reasoning_content %}
|
| 151 |
-
{%- set r_prefix = reasoning_content.split('<think>')[0] | trim %}
|
| 152 |
-
{%- set reasoning_content = reasoning_content.split('<think>')[1:] | join('<think>') | trim %}
|
| 153 |
-
{%- set content = (r_prefix ~ '\n' ~ content) | trim %}
|
| 154 |
-
{%- endif %}
|
| 155 |
-
{%- elif '<think>' in content %}
|
| 156 |
-
{%- set prefix = content.split('<think>')[0] %}
|
| 157 |
-
{%- set think_part = content.split('<think>')[1:] | join('<think>') %}
|
| 158 |
-
{%- if '<tool_call>' in think_part %}
|
| 159 |
-
{%- set reasoning_content = think_part.split('<tool_call>')[0] %}
|
| 160 |
-
{%- set content = prefix ~ '\n<tool_call>' ~ think_part.split('<tool_call>')[1:] | join('<tool_call>') %}
|
| 161 |
{%- else %}
|
| 162 |
-
{%- set
|
| 163 |
-
{%- set content = prefix %}
|
| 164 |
{%- endif %}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
{%- endif %}
|
| 166 |
{%- endif %}
|
| 167 |
{%- set reasoning_content = reasoning_content | trim %}
|
| 168 |
-
{%-
|
| 169 |
-
|
| 170 |
-
{%- if '<tool_call>' in content %}
|
| 171 |
-
{%- set content = content.split('<tool_call>')[0] | trim %}
|
| 172 |
-
{%- endif %}
|
| 173 |
-
{%- endif %}
|
| 174 |
-
{%- set show_think = true %}
|
| 175 |
-
{%- if preserve_thinking is defined and preserve_thinking == false %}
|
| 176 |
-
{%- set show_think = false %}
|
| 177 |
-
{%- endif %}
|
| 178 |
-
{%- if not reasoning_content %}
|
| 179 |
-
{%- set show_think = false %}
|
| 180 |
-
{%- endif %}
|
| 181 |
-
|
| 182 |
-
{%- if show_think and ns_flags.enable_thinking is not false %}
|
| 183 |
-
{%- if content %}
|
| 184 |
-
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n' + content }}
|
| 185 |
-
{%- else %}
|
| 186 |
-
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>' }}
|
| 187 |
-
{%- endif %}
|
| 188 |
{%- else %}
|
| 189 |
-
{
|
| 190 |
-
{{- '<|im_start|>' + message.role + '\n' + content }}
|
| 191 |
-
{%- else %}
|
| 192 |
-
{{- '<|im_start|>' + message.role }}
|
| 193 |
-
{%- endif %}
|
| 194 |
{%- endif %}
|
| 195 |
-
{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
|
| 196 |
{%- for tool_call in message.tool_calls %}
|
| 197 |
-
{%- if tool_call.function is defined %}
|
| 198 |
-
{%- set
|
|
|
|
|
|
|
| 199 |
{%- endif %}
|
| 200 |
-
{
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
{%-
|
| 204 |
-
{
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
{{- '\n</parameter>\n' }}
|
| 210 |
{%- endfor %}
|
| 211 |
-
{%-
|
| 212 |
-
|
| 213 |
-
{%- if tool_call.arguments | trim | length > 0 %}
|
| 214 |
-
{{- tool_call.arguments }}
|
| 215 |
-
{{- '\n' }}
|
| 216 |
{%- endif %}
|
| 217 |
{%- endif %}
|
| 218 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
{%- endfor %}
|
| 220 |
{%- endif %}
|
| 221 |
{{- '<|im_end|>\n' }}
|
| 222 |
-
{%- elif message.role ==
|
| 223 |
-
{%- set
|
| 224 |
-
{%- if content | length < 500
|
| 225 |
-
|
| 226 |
-
and 'took ' not in content_lower
|
| 227 |
-
and ('"error":' in content_lower or 'error:' in content_lower or 'exception:' in content_lower or 'traceback' in content_lower or 'command not found' in content_lower or 'invalid syntax' in content_lower or 'failed to' in content_lower) %}
|
| 228 |
-
{%- set ns_flags.last_tool_failed = true %}
|
| 229 |
-
{%- set ns_flags.consecutive_failures = ns_flags.consecutive_failures + 1 %}
|
| 230 |
{%- else %}
|
| 231 |
-
{%- set
|
| 232 |
-
{%- set ns_flags.consecutive_failures = 0 %}
|
| 233 |
{%- endif %}
|
| 234 |
-
{%- if
|
| 235 |
{{- '<|im_start|>user' }}
|
| 236 |
{%- endif %}
|
| 237 |
-
{
|
| 238 |
-
|
| 239 |
-
{%-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
{
|
| 243 |
-
|
| 244 |
-
{
|
| 245 |
{%- endif %}
|
| 246 |
{{- '\n</tool_response>' }}
|
| 247 |
-
{%- if
|
| 248 |
-
{{- '<|im_end|>\n' }}
|
| 249 |
-
{%- elif loop.last %}
|
| 250 |
{{- '<|im_end|>\n' }}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
{%- endif %}
|
| 252 |
{%- else %}
|
| 253 |
-
{{-
|
| 254 |
{%- endif %}
|
|
|
|
| 255 |
{%- endfor %}
|
| 256 |
{%- if add_generation_prompt %}
|
| 257 |
{{- '<|im_start|>assistant\n' }}
|
| 258 |
-
{%- if
|
| 259 |
{{- '<think>\n</think>\n' }}
|
| 260 |
-
{%- elif
|
| 261 |
{{- '<think>\n</think>\n' }}
|
| 262 |
{%- else %}
|
| 263 |
{{- '<think>\n' }}
|
|
|
|
| 1 |
+
{%- set template_version = "qwen3.6-froggeric-v20" %}
|
| 2 |
{%- set image_count = namespace(value=0) %}
|
| 3 |
{%- set video_count = namespace(value=0) %}
|
| 4 |
+
{%- set add_vision_id = add_vision_id if add_vision_id is defined else false %}
|
| 5 |
+
{%- set enable_thinking = enable_thinking if enable_thinking is defined else true %}
|
| 6 |
+
{%- set auto_disable_thinking_with_tools = auto_disable_thinking_with_tools if auto_disable_thinking_with_tools is defined else false %}
|
| 7 |
+
{%- set _preserve_thinking = preserve_thinking if preserve_thinking is defined else false %}
|
| 8 |
+
{%- set max_tool_arg_chars = max_tool_arg_chars if max_tool_arg_chars is defined else 0 %}
|
| 9 |
+
{%- set max_tool_response_chars = max_tool_response_chars if max_tool_response_chars is defined else 0 %}
|
| 10 |
+
{%- set _has_tools = (tools is defined and tools and tools is iterable and tools is not mapping) %}
|
| 11 |
+
{%- set ns_state = namespace(thinking=enable_thinking) %}
|
| 12 |
+
{%- if auto_disable_thinking_with_tools and _has_tools %}
|
| 13 |
+
{%- set ns_state.thinking = false %}
|
| 14 |
+
{%- endif %}
|
| 15 |
{%- macro render_content(content, do_vision_count, is_system_content=false) %}
|
| 16 |
{%- if content is string %}
|
| 17 |
{{- content }}
|
| 18 |
{%- elif content is iterable and content is not mapping %}
|
| 19 |
{%- for item in content %}
|
| 20 |
+
{%- if item is mapping %}
|
| 21 |
+
{%- if item.type == 'image' or 'image' in item or 'image_url' in item %}
|
| 22 |
+
{%- if is_system_content %}
|
| 23 |
+
{{- raise_exception('System message cannot contain images.') }}
|
| 24 |
+
{%- endif %}
|
| 25 |
+
{%- if do_vision_count %}
|
| 26 |
+
{%- set image_count.value = image_count.value + 1 %}
|
| 27 |
+
{%- endif %}
|
| 28 |
+
{%- if add_vision_id %}
|
| 29 |
+
{{- 'Picture ' ~ image_count.value ~ ': ' }}
|
| 30 |
+
{%- endif %}
|
| 31 |
+
{{- '<|vision_start|><|image_pad|><|vision_end|>' }}
|
| 32 |
+
{%- elif item.type == 'video' or 'video' in item %}
|
| 33 |
+
{%- if is_system_content %}
|
| 34 |
+
{{- raise_exception('System message cannot contain videos.') }}
|
| 35 |
+
{%- endif %}
|
| 36 |
+
{%- if do_vision_count %}
|
| 37 |
+
{%- set video_count.value = video_count.value + 1 %}
|
| 38 |
+
{%- endif %}
|
| 39 |
+
{%- if add_vision_id %}
|
| 40 |
+
{{- 'Video ' ~ video_count.value ~ ': ' }}
|
| 41 |
+
{%- endif %}
|
| 42 |
+
{{- '<|vision_start|><|video_pad|><|vision_end|>' }}
|
| 43 |
+
{%- elif 'text' in item %}
|
| 44 |
+
{{- item.text }}
|
| 45 |
+
{%- else %}
|
| 46 |
+
{{- raise_exception('Unexpected item type in content.') }}
|
| 47 |
{%- endif %}
|
|
|
|
|
|
|
|
|
|
| 48 |
{%- else %}
|
| 49 |
+
{{- item | string }}
|
| 50 |
{%- endif %}
|
| 51 |
{%- endfor %}
|
| 52 |
{%- elif content is none or content is undefined %}
|
|
|
|
| 55 |
{{- raise_exception('Unexpected content type.') }}
|
| 56 |
{%- endif %}
|
| 57 |
{%- endmacro %}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
{%- if not messages %}
|
| 59 |
{{- raise_exception('No messages provided.') }}
|
| 60 |
{%- endif %}
|
| 61 |
+
{%- set _first_role = messages[0].role %}
|
| 62 |
+
{%- if _first_role == 'system' or _first_role == 'developer' %}
|
| 63 |
+
{%- set _sys_msg = messages[0] %}
|
| 64 |
+
{%- set _msgs = messages[1:] %}
|
| 65 |
+
{%- else %}
|
| 66 |
+
{%- set _sys_msg = none %}
|
| 67 |
+
{%- set _msgs = messages %}
|
| 68 |
+
{%- endif %}
|
| 69 |
+
{%- set _sc = '' %}
|
| 70 |
+
{%- if _sys_msg is not none %}
|
| 71 |
+
{%- set _sc = render_content(_sys_msg.content, false, true) | trim %}
|
| 72 |
+
{%- if '<|think_off|>' in _sc %}
|
| 73 |
+
{%- set ns_state.thinking = false %}
|
| 74 |
+
{%- set _sc = _sc | replace('<|think_off|>', '') | trim %}
|
| 75 |
+
{%- elif '<|think_on|>' in _sc %}
|
| 76 |
+
{%- set ns_state.thinking = true %}
|
| 77 |
+
{%- set _sc = _sc | replace('<|think_on|>', '') | trim %}
|
| 78 |
{%- endif %}
|
|
|
|
| 79 |
{%- endif %}
|
| 80 |
+
{%- if _has_tools %}
|
|
|
|
| 81 |
{{- '<|im_start|>system\n' }}
|
| 82 |
+
{{- '# Tools\n\nYou have access to the following functions:\n\n<tools>' }}
|
| 83 |
{%- for tool in tools %}
|
| 84 |
{{- '\n' }}
|
| 85 |
+
{{- tool | tojson }}
|
|
|
|
| 86 |
{%- endfor %}
|
| 87 |
+
{{- '\n</tools>' }}
|
| 88 |
{%- set tool_instructions %}
|
| 89 |
If you choose to call a function ONLY reply in the following format with NO suffix:
|
| 90 |
|
|
|
|
| 116 |
</IMPORTANT>
|
| 117 |
{%- endset %}
|
| 118 |
{{- '\n\n' ~ tool_instructions | trim }}
|
| 119 |
+
{%- if _sc %}
|
| 120 |
+
{{- '\n\n' + _sc }}
|
| 121 |
{%- endif %}
|
| 122 |
{{- '<|im_end|>\n' }}
|
| 123 |
+
{%- else %}
|
| 124 |
+
{%- if _sc %}
|
| 125 |
+
{{- '<|im_start|>system\n' + _sc + '<|im_end|>\n' }}
|
| 126 |
+
{%- endif %}
|
| 127 |
+
{%- endif %}
|
| 128 |
+
{%- set _last_idx = _msgs | length - 1 %}
|
| 129 |
+
{%- set ns = namespace(multi_step_tool=true, last_query_index=_last_idx) %}
|
| 130 |
+
{%- for message in _msgs[::-1] %}
|
| 131 |
+
{%- set index = (_msgs | length - 1) - loop.index0 %}
|
| 132 |
+
{%- if ns.multi_step_tool and message.role == 'user' %}
|
| 133 |
+
{%- set _rc = render_content(message.content, false) | trim %}
|
| 134 |
+
{%- if not (_rc.startswith('<tool_response>') and _rc.endswith('</tool_response>')) %}
|
| 135 |
+
{%- set ns.multi_step_tool = false %}
|
| 136 |
+
{%- set ns.last_query_index = index %}
|
| 137 |
+
{%- endif %}
|
| 138 |
+
{%- endif %}
|
| 139 |
+
{%- endfor %}
|
| 140 |
+
{%- if ns.multi_step_tool %}
|
| 141 |
+
{%- if _last_idx > 50 %}
|
| 142 |
+
{%- set ns.last_query_index = _last_idx %}
|
| 143 |
+
{%- else %}
|
| 144 |
+
{%- set ns.last_query_index = 0 %}
|
| 145 |
+
{%- endif %}
|
| 146 |
{%- endif %}
|
| 147 |
+
{%- set ns2 = namespace(prev_role='', consecutive_failures=0) %}
|
| 148 |
+
{%- for message in _msgs %}
|
| 149 |
{%- set is_system = (message.role == "system" or message.role == "developer") %}
|
| 150 |
+
{%- set content = render_content(message.content, true, is_system) | trim %}
|
| 151 |
{%- if '<|think_off|>' in content %}
|
| 152 |
+
{%- set ns_state.thinking = false %}
|
| 153 |
{%- set content = content | replace('<|think_off|>', '') | trim %}
|
| 154 |
{%- elif '<|think_on|>' in content %}
|
| 155 |
+
{%- set ns_state.thinking = true %}
|
| 156 |
{%- set content = content | replace('<|think_on|>', '') | trim %}
|
| 157 |
{%- endif %}
|
| 158 |
{%- if is_system %}
|
| 159 |
+
{{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}
|
| 160 |
+
{%- elif message.role == 'user' %}
|
| 161 |
+
{%- set ns2.consecutive_failures = 0 %}
|
| 162 |
+
{{- '<|im_start|>user\n' + content + '<|im_end|>\n' }}
|
| 163 |
+
{%- elif message.role == 'assistant' %}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
{%- set reasoning_content = '' %}
|
| 165 |
+
{%- if message.reasoning_content is defined and message.reasoning_content is not none %}
|
| 166 |
+
{%- if message.reasoning_content is string %}
|
| 167 |
+
{%- set reasoning_content = message.reasoning_content %}
|
| 168 |
+
{%- else %}
|
| 169 |
+
{%- set reasoning_content = message.reasoning_content | string %}
|
| 170 |
+
{%- endif %}
|
| 171 |
{%- else %}
|
| 172 |
+
{%- set _think_end = '' %}
|
| 173 |
{%- if '</think>' in content %}
|
| 174 |
+
{%- set _think_end = '</think>' %}
|
| 175 |
{%- elif '</thinking>' in content %}
|
| 176 |
+
{%- set _think_end = '</thinking>' %}
|
| 177 |
{%- elif '</ think>' in content %}
|
| 178 |
+
{%- set _think_end = '</ think>' %}
|
| 179 |
{%- elif '</think >' in content %}
|
| 180 |
+
{%- set _think_end = '</think >' %}
|
| 181 |
{%- endif %}
|
| 182 |
+
{%- if _think_end %}
|
| 183 |
+
{%- if _think_end == '</thinking>' %}
|
| 184 |
+
{%- set _think_start = '<thinking>' %}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
{%- else %}
|
| 186 |
+
{%- set _think_start = '<think>' %}
|
|
|
|
| 187 |
{%- endif %}
|
| 188 |
+
{%- set reasoning_content = content.split(_think_end)[0].rstrip('\n') %}
|
| 189 |
+
{%- if _think_start in reasoning_content %}
|
| 190 |
+
{%- set reasoning_content = reasoning_content.split(_think_start)[-1].lstrip('\n') %}
|
| 191 |
+
{%- endif %}
|
| 192 |
+
{%- set content = content.split(_think_end)[-1].lstrip('\n') %}
|
| 193 |
{%- endif %}
|
| 194 |
{%- endif %}
|
| 195 |
{%- set reasoning_content = reasoning_content | trim %}
|
| 196 |
+
{%- if (_preserve_thinking or loop.index0 > ns.last_query_index) and reasoning_content %}
|
| 197 |
+
{{- '<|im_start|>assistant\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
{%- else %}
|
| 199 |
+
{{- '<|im_start|>assistant\n' + content }}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
{%- endif %}
|
| 201 |
+
{%- if message.tool_calls is defined and message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
|
| 202 |
{%- for tool_call in message.tool_calls %}
|
| 203 |
+
{%- if tool_call.function is defined and tool_call.function is not none %}
|
| 204 |
+
{%- set tc = tool_call.function %}
|
| 205 |
+
{%- else %}
|
| 206 |
+
{%- set tc = tool_call %}
|
| 207 |
{%- endif %}
|
| 208 |
+
{%- if loop.first %}
|
| 209 |
+
{%- if content | trim %}
|
| 210 |
+
{{- '\n\n<tool_call>\n<function=' + tc.name + '>\n' }}
|
| 211 |
+
{%- else %}
|
| 212 |
+
{{- '<tool_call>\n<function=' + tc.name + '>\n' }}
|
| 213 |
+
{%- endif %}
|
| 214 |
+
{%- else %}
|
| 215 |
+
{{- '\n\n<tool_call>\n<function=' + tc.name + '>\n' }}
|
| 216 |
+
{%- endif %}
|
| 217 |
+
{%- if tc.arguments is defined and tc.arguments is not none %}
|
| 218 |
+
{%- if tc.arguments is mapping %}
|
| 219 |
+
{%- for args_name, args_value in tc.arguments.items() %}
|
| 220 |
+
{{- '<parameter=' + args_name + '>\n' }}
|
| 221 |
+
{%- if args_value is mapping or (args_value is sequence and args_value is not string) %}
|
| 222 |
+
{%- set _av = args_value | tojson %}
|
| 223 |
+
{%- else %}
|
| 224 |
+
{%- set _av = args_value | string %}
|
| 225 |
+
{%- endif %}
|
| 226 |
+
{%- if max_tool_arg_chars > 0 and _av | length > max_tool_arg_chars %}
|
| 227 |
+
{{- _av[:max_tool_arg_chars] + '\n[TRUNCATED — original length ' ~ (_av | length | string) ~ ' chars]' }}
|
| 228 |
+
{%- else %}
|
| 229 |
+
{{- _av }}
|
| 230 |
+
{%- endif %}
|
| 231 |
{{- '\n</parameter>\n' }}
|
| 232 |
{%- endfor %}
|
| 233 |
+
{%- elif tc.arguments is string and tc.arguments %}
|
| 234 |
+
{{- tc.arguments }}
|
|
|
|
|
|
|
|
|
|
| 235 |
{%- endif %}
|
| 236 |
{%- endif %}
|
| 237 |
+
{%- if loop.last %}
|
| 238 |
+
{{- '</function>\n</tool_call>\n' }}
|
| 239 |
+
{%- else %}
|
| 240 |
+
{{- '</function>\n</tool_call>' }}
|
| 241 |
+
{%- endif %}
|
| 242 |
{%- endfor %}
|
| 243 |
{%- endif %}
|
| 244 |
{{- '<|im_end|>\n' }}
|
| 245 |
+
{%- elif message.role == 'tool' %}
|
| 246 |
+
{%- set _content_lower = content | lower %}
|
| 247 |
+
{%- if content | length < 500 and '$ ' not in content and 'took ' not in _content_lower and ('"error":' in _content_lower or 'error:' in _content_lower or 'exception:' in _content_lower or 'traceback' in _content_lower or 'command not found' in _content_lower or 'invalid syntax' in _content_lower or 'failed to' in _content_lower) %}
|
| 248 |
+
{%- set ns2.consecutive_failures = ns2.consecutive_failures + 1 %}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
{%- else %}
|
| 250 |
+
{%- set ns2.consecutive_failures = 0 %}
|
|
|
|
| 251 |
{%- endif %}
|
| 252 |
+
{%- if ns2.prev_role != 'tool' %}
|
| 253 |
{{- '<|im_start|>user' }}
|
| 254 |
{%- endif %}
|
| 255 |
+
{%- if max_tool_response_chars > 0 and content | length > max_tool_response_chars %}
|
| 256 |
+
{%- set content = content[:max_tool_response_chars] + '\n[TRUNCATED — original length ' ~ (content | length | string) ~ ' chars]' %}
|
| 257 |
+
{%- endif %}
|
| 258 |
+
{{- '\n<tool_response>\n' + content }}
|
| 259 |
+
{%- if ns2.consecutive_failures >= 2 %}
|
| 260 |
+
{{- '\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.' }}
|
| 261 |
+
{%- elif ns2.consecutive_failures == 1 %}
|
| 262 |
+
{{- '\n\n⚠️ SYSTEM WARNING: The previous tool call returned an error. Diagnose the failure and retry with completely corrected arguments.' }}
|
| 263 |
{%- endif %}
|
| 264 |
{{- '\n</tool_response>' }}
|
| 265 |
+
{%- if loop.last %}
|
|
|
|
|
|
|
| 266 |
{{- '<|im_end|>\n' }}
|
| 267 |
+
{%- else %}
|
| 268 |
+
{%- set _next_role = _msgs[loop.index0 + 1].role %}
|
| 269 |
+
{%- if _next_role != 'tool' %}
|
| 270 |
+
{{- '<|im_end|>\n' }}
|
| 271 |
+
{%- endif %}
|
| 272 |
{%- endif %}
|
| 273 |
{%- else %}
|
| 274 |
+
{{- '<|im_start|>user\n[' + message.role + ']: ' + content + '<|im_end|>\n' }}
|
| 275 |
{%- endif %}
|
| 276 |
+
{%- set ns2.prev_role = message.role %}
|
| 277 |
{%- endfor %}
|
| 278 |
{%- if add_generation_prompt %}
|
| 279 |
{{- '<|im_start|>assistant\n' }}
|
| 280 |
+
{%- if not ns_state.thinking %}
|
| 281 |
{{- '<think>\n</think>\n' }}
|
| 282 |
+
{%- elif ns2.consecutive_failures >= 2 %}
|
| 283 |
{{- '<think>\n</think>\n' }}
|
| 284 |
{%- else %}
|
| 285 |
{{- '<think>\n' }}
|
chat_template_oneline.txt
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
{%- set image_count = namespace(value=0) %}{%- set video_count = namespace(value=0) %}{%- 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 'image' in item or 'image_url' in item or item.type == 'image' %}{%- 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 is defined and add_vision_id %}{{- 'Picture ' ~ image_count.value ~ ': ' }}{%- endif %}{{- '<|vision_start|><|image_pad|><|vision_end|>' }}{%- elif 'video' in item or item.type == 'video' %}{%- 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 is defined and 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 %}{%- endfor %}{%- elif content is none or content is undefined %}{{- '' }}{%- else %}{{- raise_exception('Unexpected content type.') }}{%- endif %}{%- endmacro %}{%- set ns_flags = namespace(enable_thinking=true, has_tools=false, last_tool_failed=false, consecutive_failures=0) %}{%- if enable_thinking is defined %}{%- set ns_flags.enable_thinking = enable_thinking %}{%- endif %}{%- if not messages %}{{- raise_exception('No messages provided.') }}{%- endif %}{%- set system_content = '' %}{%- set has_system = false %}{%- if messages[0].role == 'system' or messages[0].role == 'developer' %}{%- set has_system = true %}{%- set system_content = render_content(messages[0].content, false, true)|trim %}{%- if '<|think_off|>' in system_content %}{%- set ns_flags.enable_thinking = false %}{%- set system_content = system_content | replace('<|think_off|>', '') %}{%- endif %}{%- if '<|think_on|>' in system_content %}{%- set ns_flags.enable_thinking = true %}{%- set system_content = system_content | replace('<|think_on|>', '') %}{%- endif %}{%- set system_content = system_content | trim %}{%- endif %}{%- if tools and tools is iterable and tools is not mapping %}{%- set ns_flags.has_tools = true %}{{- '<|im_start|>system\n' }}{{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}{%- for tool in tools %}{{- '\n' }}{%- set fn = tool.function if tool.function is defined else tool %}{{- fn | tojson }}{%- endfor %}{{- "\n</tools>" }}{%- set tool_instructions %} If you choose to call a function ONLY reply in the following format with NO suffix: <think> Brief explanation of tool call </think> <tool_call> <function=example_function_name> <parameter=example_parameter_1> value_1 </parameter> <parameter=example_parameter_2> This is the value for the second parameter that can span multiple lines </parameter> </function> </tool_call> <IMPORTANT> Reminder: - 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. - ALL explanation and reasoning MUST be placed strictly inside the <think></think> block. - Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags. - If you choose to call a tool, you MUST output the <tool_call> block IMMEDIATELY after closing </think>. Do NOT output any conversational text before the tool call. - The <tool_call> and <function> tags MUST be at the very beginning of a new line, with NO spaces or indentation before them. - To call multiple functions, output a separate, completely closed <tool_call></tool_call> block for EACH function. Do NOT nest <tool_call> blocks. - If you have gathered all necessary data and do not need to call a tool, answer the question like normal and provide your final response to the user IMMEDIATELY after closing </think>. </IMPORTANT> {%- endset %}{{- '\n\n' ~ tool_instructions | trim }}{%- if has_system and system_content %}{{- '\n\n' + system_content }}{%- endif %}{{- '<|im_end|>\n' }}{%- elif has_system and system_content %}{{- '<|im_start|>system\n' + system_content + '<|im_end|>\n' }}{%- endif %}{%- for message in messages %}{%- set is_system = (message.role == "system" or message.role == "developer") %}{%- set content = render_content(message.content, true, is_system)|trim %}{%- if '<|think_off|>' in content %}{%- set ns_flags.enable_thinking = false %}{%- set content = content | replace('<|think_off|>', '') | trim %}{%- elif '<|think_on|>' in content %}{%- set ns_flags.enable_thinking = true %}{%- set content = content | replace('<|think_on|>', '') | trim %}{%- endif %}{%- if is_system %}{%- if not loop.first and content %}{{- '<|im_start|>system\n' + content + '<|im_end|>\n' }}{%- endif %}{%- elif message.role == "user" %}{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>\n' }}{%- set ns_flags.last_tool_failed = false %}{%- set ns_flags.consecutive_failures = 0 %}{%- elif message.role == "assistant" %}{%- set ns_flags.last_tool_failed = false %}{%- set reasoning_content = '' %}{%- if message.reasoning_content is string %}{%- set reasoning_content = message.reasoning_content %}{%- else %}{%- set think_end_token = '' %}{%- if '</think>' in content %}{%- set think_end_token = '</think>' %}{%- elif '</thinking>' in content %}{%- set think_end_token = '</thinking>' %}{%- elif '</ think>' in content %}{%- set think_end_token = '</ think>' %}{%- elif '</think >' in content %}{%- set think_end_token = '</think >' %}{%- endif %}{%- if think_end_token %}{%- set reasoning_parts = content.split(think_end_token) %}{%- set reasoning_content = reasoning_parts[0] %}{%- set content = reasoning_parts[1:] | join(think_end_token) %}{%- if '<think>' in reasoning_content %}{%- set r_prefix = reasoning_content.split('<think>')[0] | trim %}{%- set reasoning_content = reasoning_content.split('<think>')[1:] | join('<think>') | trim %}{%- set content = (r_prefix ~ '\n' ~ content) | trim %}{%- endif %}{%- elif '<think>' in content %}{%- set prefix = content.split('<think>')[0] %}{%- set think_part = content.split('<think>')[1:] | join('<think>') %}{%- if '<tool_call>' in think_part %}{%- set reasoning_content = think_part.split('<tool_call>')[0] %}{%- set content = prefix ~ '\n<tool_call>' ~ think_part.split('<tool_call>')[1:] | join('<tool_call>') %}{%- else %}{%- set reasoning_content = think_part %}{%- set content = prefix %}{%- endif %}{%- endif %}{%- endif %}{%- set reasoning_content = reasoning_content | trim %}{%- set content = content | trim %}{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}{%- if '<tool_call>' in content %}{%- set content = content.split('<tool_call>')[0] | trim %}{%- endif %}{%- endif %}{%- set show_think = true %}{%- if preserve_thinking is defined and preserve_thinking == false %}{%- set show_think = false %}{%- endif %}{%- if not reasoning_content %}{%- set show_think = false %}{%- endif %}{%- if show_think and ns_flags.enable_thinking is not false %}{%- if content %}{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n' + content }}{%- else %}{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>' }}{%- endif %}{%- else %}{%- if content %}{{- '<|im_start|>' + message.role + '\n' + content }}{%- else %}{{- '<|im_start|>' + message.role }}{%- endif %}{%- endif %}{%- if 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 %}{%- set tool_call = tool_call.function %}{%- endif %}{{- '\n<tool_call>\n' }}{{- '<function=' ~ tool_call.name ~ '>\n' }}{%- if tool_call.arguments is defined and tool_call.arguments is mapping %}{%- if tool_call.arguments | length > 0 %}{%- for args_name in tool_call.arguments %}{%- set args_value = tool_call.arguments[args_name] %}{{- '<parameter=' ~ args_name ~ '>\n' }}{%- set args_value = args_value | tojson if args_value is mapping or (args_value is iterable and args_value is not string) else args_value | string %}{{- args_value }}{{- '\n</parameter>\n' }}{%- endfor %}{%- endif %}{%- elif tool_call.arguments is defined and tool_call.arguments is string %}{%- if tool_call.arguments | trim | length > 0 %}{{- tool_call.arguments }}{{- '\n' }}{%- endif %}{%- endif %}{{- '</function>\n</tool_call>' }}{%- endfor %}{%- endif %}{{- '<|im_end|>\n' }}{%- elif message.role == "tool" %}{%- set content_lower = content | lower %}{%- if content | length < 500 and '$ ' not in content and 'took ' not in content_lower and ('"error":' in content_lower or 'error:' in content_lower or 'exception:' in content_lower or 'traceback' in content_lower or 'command not found' in content_lower or 'invalid syntax' in content_lower or 'failed to' in content_lower) %}{%- set ns_flags.last_tool_failed = true %}{%- set ns_flags.consecutive_failures = ns_flags.consecutive_failures + 1 %}{%- else %}{%- set ns_flags.last_tool_failed = false %}{%- set ns_flags.consecutive_failures = 0 %}{%- endif %}{%- if loop.index0 > 0 and messages[loop.index0 - 1].role != "tool" %}{{- '<|im_start|>user' }}{%- endif %}{{- '\n<tool_response>\n' }}{{- content }}{%- if ns_flags.last_tool_failed %}{%- if ns_flags.consecutive_failures >= 2 %}{{- '\n\n⚠️ SYSTEM WARNING: ' ~ ns_flags.consecutive_failures ~ ' consecutive tool errors detected. Your previous approach is incorrect. You MUST use a fundamentally different approach or corrected arguments.' }}{%- else %}{{- '\n\n⚠️ SYSTEM WARNING: The previous tool call returned an error. Diagnose the failure and retry with completely corrected arguments.' }}{%- endif %}{%- endif %}{{- '\n</tool_response>' }}{%- if not loop.last and messages[loop.index0 + 1].role != "tool" %}{{- '<|im_end|>\n' }}{%- elif loop.last %}{{- '<|im_end|>\n' }}{%- endif %}{%- else %}{{- raise_exception('Unexpected message role.') }}{%- endif %}{%- endfor %}{%- if add_generation_prompt %}{{- '<|im_start|>assistant\n' }}{%- if ns_flags.enable_thinking is false %}{{- '<think>\n</think>\n' }}{%- elif ns_flags.last_tool_failed and ns_flags.consecutive_failures >= 2 %}{{- '<think>\n</think>\n' }}{%- else %}{{- '<think>\n' }}{%- endif %}{%- endif %}
|
|
|
|
| 1 |
+
{%- set template_version = "qwen3.6-froggeric-v20" %}{%- 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 %}{%- set _preserve_thinking = preserve_thinking if preserve_thinking is defined else false %}{%- 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 _has_tools = (tools is defined and tools and tools is iterable and tools is not mapping) %}{%- set ns_state = namespace(thinking=enable_thinking) %}{%- if auto_disable_thinking_with_tools and _has_tools %}{%- set ns_state.thinking = false %}{%- endif %}{%- 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 %}{%- 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 %}{%- if not messages %}{{- raise_exception('No messages provided.') }}{%- endif %}{%- set _first_role = messages[0].role %}{%- if _first_role == 'system' or _first_role == 'developer' %}{%- set _sys_msg = messages[0] %}{%- set _msgs = messages[1:] %}{%- else %}{%- set _sys_msg = none %}{%- set _msgs = messages %}{%- endif %}{%- set _sc = '' %}{%- if _sys_msg is not none %}{%- set _sc = render_content(_sys_msg.content, false, true) | trim %}{%- if '<|think_off|>' in _sc %}{%- set ns_state.thinking = false %}{%- set _sc = _sc | replace('<|think_off|>', '') | trim %}{%- elif '<|think_on|>' in _sc %}{%- set ns_state.thinking = true %}{%- set _sc = _sc | replace('<|think_on|>', '') | trim %}{%- endif %}{%- endif %}{%- if _has_tools %}{{- '<|im_start|>system\n' }}{{- '# Tools\n\nYou have access to the following functions:\n\n<tools>' }}{%- for tool in tools %}{{- '\n' }}{{- tool | tojson }}{%- endfor %}{{- '\n</tools>' }}{%- set tool_instructions %} If you choose to call a function ONLY reply in the following format with NO suffix: <think> Brief explanation of tool call </think> <tool_call> <function=example_function_name> <parameter=example_parameter_1> value_1 </parameter> <parameter=example_parameter_2> This is the value for the second parameter that can span multiple lines </parameter> </function> </tool_call> <IMPORTANT> Reminder: - 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. - ALL explanation and reasoning MUST be placed strictly inside the <think></think> block. - Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags. - If you choose to call a tool, you MUST output the <tool_call> block IMMEDIATELY after closing </think>. Do NOT output any conversational text before the tool call. - The <tool_call> and <function> tags MUST be at the very beginning of a new line, with NO spaces or indentation before them. - To call multiple functions, output a separate, completely closed <tool_call></tool_call> block for EACH function. Do NOT nest <tool_call> blocks. - If you have gathered all necessary data and do not need to call a tool, answer the question like normal and provide your final response to the user IMMEDIATELY after closing </think>. </IMPORTANT> {%- endset %}{{- '\n\n' ~ tool_instructions | trim }}{%- if _sc %}{{- '\n\n' + _sc }}{%- endif %}{{- '<|im_end|>\n' }}{%- else %}{%- if _sc %}{{- '<|im_start|>system\n' + _sc + '<|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 '<|think_off|>' in content %}{%- set ns_state.thinking = false %}{%- set content = content | replace('<|think_off|>', '') | trim %}{%- elif '<|think_on|>' in content %}{%- set ns_state.thinking = true %}{%- set content = content | replace('<|think_on|>', '') | trim %}{%- 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 = '' %}{%- if message.reasoning_content is defined and message.reasoning_content is not none %}{%- if message.reasoning_content is string %}{%- set reasoning_content = message.reasoning_content %}{%- else %}{%- set reasoning_content = message.reasoning_content | string %}{%- endif %}{%- else %}{%- set _think_end = '' %}{%- if '</think>' in content %}{%- set _think_end = '</think>' %}{%- elif '</thinking>' in content %}{%- set _think_end = '</thinking>' %}{%- elif '</ think>' in content %}{%- set _think_end = '</ think>' %}{%- elif '</think >' in content %}{%- set _think_end = '</think >' %}{%- endif %}{%- if _think_end %}{%- if _think_end == '</thinking>' %}{%- 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) and reasoning_content %}{{- '<|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 %}{%- 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\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 mapping or (args_value is sequence and args_value is not string) %}{%- set _av = args_value | tojson %}{%- else %}{%- set _av = args_value | string %}{%- 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 %}{%- elif tc.arguments is string and tc.arguments %}{{- tc.arguments }}{%- endif %}{%- endif %}{%- if loop.last %}{{- '</function>\n</tool_call>\n' }}{%- else %}{{- '</function>\n</tool_call>' }}{%- endif %}{%- endfor %}{%- endif %}{{- '<|im_end|>\n' }}{%- elif message.role == 'tool' %}{%- set _content_lower = content | lower %}{%- if content | length < 500 and '$ ' not in content and 'took ' not in _content_lower and ('"error":' in _content_lower or 'error:' in _content_lower or 'exception:' in _content_lower or 'traceback' in _content_lower or 'command not found' in _content_lower or 'invalid syntax' in _content_lower or 'failed to' in _content_lower) %}{%- set ns2.consecutive_failures = ns2.consecutive_failures + 1 %}{%- else %}{%- set ns2.consecutive_failures = 0 %}{%- endif %}{%- if ns2.prev_role != 'tool' %}{{- '<|im_start|>user' }}{%- endif %}{%- if 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</think>\n' }}{%- elif ns2.consecutive_failures >= 2 %}{{- '<think>\n</think>\n' }}{%- else %}{{- '<think>\n' }}{%- endif %}{%- endif %}
|
scripts/test_v18.py
DELETED
|
@@ -1,404 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
Test suite for Qwen v18 chat templates.
|
| 4 |
-
Tests logical correctness using Python Jinja2 (minijinja compatibility verified separately).
|
| 5 |
-
|
| 6 |
-
Usage:
|
| 7 |
-
python3 scripts/test_v18.py
|
| 8 |
-
python3 scripts/test_v18.py qwen3.6 # test one variant
|
| 9 |
-
"""
|
| 10 |
-
|
| 11 |
-
import sys
|
| 12 |
-
import os
|
| 13 |
-
from pathlib import Path
|
| 14 |
-
from jinja2 import Environment
|
| 15 |
-
|
| 16 |
-
# ── Setup ──────────────────────────────────────────────────────────────────────
|
| 17 |
-
|
| 18 |
-
ROOT = Path(__file__).parent.parent
|
| 19 |
-
VARIANTS = ["root"]
|
| 20 |
-
VERSION = "v18"
|
| 21 |
-
|
| 22 |
-
def load_template() -> str:
|
| 23 |
-
path = ROOT / "chat_template.jinja"
|
| 24 |
-
return path.read_text(encoding="utf-8")
|
| 25 |
-
|
| 26 |
-
def render(template_src: str, messages: list, tools=None,
|
| 27 |
-
add_generation_prompt: bool = True,
|
| 28 |
-
enable_thinking=None, preserve_thinking=None) -> str:
|
| 29 |
-
env = Environment(keep_trailing_newline=False)
|
| 30 |
-
env.globals["raise_exception"] = lambda msg: (_ for _ in ()).throw(ValueError(msg))
|
| 31 |
-
tmpl = env.from_string(template_src)
|
| 32 |
-
kwargs = dict(messages=messages, tools=tools, add_generation_prompt=add_generation_prompt)
|
| 33 |
-
if enable_thinking is not None:
|
| 34 |
-
kwargs["enable_thinking"] = enable_thinking
|
| 35 |
-
if preserve_thinking is not None:
|
| 36 |
-
kwargs["preserve_thinking"] = preserve_thinking
|
| 37 |
-
return tmpl.render(**kwargs)
|
| 38 |
-
|
| 39 |
-
# ── Test helpers ───────────────────────────────────────────────────────────────
|
| 40 |
-
|
| 41 |
-
PASS = "\033[92m✓\033[0m"
|
| 42 |
-
FAIL = "\033[91m✗\033[0m"
|
| 43 |
-
|
| 44 |
-
results = []
|
| 45 |
-
|
| 46 |
-
def check(name: str, condition: bool, detail: str = ""):
|
| 47 |
-
status = PASS if condition else FAIL
|
| 48 |
-
results.append(condition)
|
| 49 |
-
suffix = f" ({detail})" if detail and not condition else ""
|
| 50 |
-
print(f" {status} {name}{suffix}")
|
| 51 |
-
|
| 52 |
-
# ── Tests ──────────────────────────────────────────────────────────────────────
|
| 53 |
-
|
| 54 |
-
def test_xml_tool_call_format(t: str):
|
| 55 |
-
"""Tool calls in history must use XML <function=...> format, not JSON."""
|
| 56 |
-
messages = [
|
| 57 |
-
{"role": "user", "content": "Get weather for Paris"},
|
| 58 |
-
{"role": "assistant", "content": "",
|
| 59 |
-
"tool_calls": [{"function": {"name": "get_weather",
|
| 60 |
-
"arguments": {"city": "Paris", "units": "celsius"}}}]},
|
| 61 |
-
{"role": "tool", "content": "Sunny, 22°C"},
|
| 62 |
-
]
|
| 63 |
-
tools = [{"name": "get_weather", "description": "Get weather",
|
| 64 |
-
"parameters": {"type": "object",
|
| 65 |
-
"properties": {"city": {"type": "string"},
|
| 66 |
-
"units": {"type": "string"}},
|
| 67 |
-
"required": ["city"]}}]
|
| 68 |
-
out = render(t, messages, tools=tools)
|
| 69 |
-
check("XML format: <function=...> present", "<function=get_weather>" in out,
|
| 70 |
-
f"got: {repr(out[out.find('<tool_call>'):out.find('<tool_call>')+120] if '<tool_call>' in out else 'no <tool_call>')}")
|
| 71 |
-
check("XML format: <parameter=city> present", "<parameter=city>" in out)
|
| 72 |
-
check("XML format: <parameter=units> present", "<parameter=units>" in out)
|
| 73 |
-
check("XML format: </function> present", "</function>" in out)
|
| 74 |
-
check("XML format: JSON {\"name\": absent in tool_call section",
|
| 75 |
-
'{"name":' not in out[out.rfind('<tool_call>'):] if '<tool_call>' in out else True,
|
| 76 |
-
f"tool_call section: {repr(out[out.rfind('<tool_call>'):out.rfind('<tool_call>')+120] if '<tool_call>' in out else 'none')}")
|
| 77 |
-
check("XML format: tool_instructions mention <function=", "<function=" in out)
|
| 78 |
-
|
| 79 |
-
def test_tool_instructions_format(t: str):
|
| 80 |
-
"""System prompt tool instructions must show XML example, not JSON."""
|
| 81 |
-
messages = [{"role": "user", "content": "Hello"}]
|
| 82 |
-
tools = [{"name": "noop", "description": "no-op",
|
| 83 |
-
"parameters": {"type": "object", "properties": {}, "required": []}}]
|
| 84 |
-
out = render(t, messages, tools=tools)
|
| 85 |
-
check("Instructions: XML example present", "<function=example_function_name>" in out)
|
| 86 |
-
check("Instructions: JSON example absent", '{"name": "tool_name"' not in out)
|
| 87 |
-
check("Instructions: <parameter= in example", "<parameter=example_parameter_1>" in out)
|
| 88 |
-
|
| 89 |
-
def test_normal_generation_prompt(t: str):
|
| 90 |
-
"""Normal generation prompt opens <think> block."""
|
| 91 |
-
messages = [{"role": "user", "content": "Hello"}]
|
| 92 |
-
out = render(t, messages)
|
| 93 |
-
check("Normal gen-prompt: ends with <think>\\n", out.endswith("<think>\n"),
|
| 94 |
-
f"tail: {repr(out[-30:])}")
|
| 95 |
-
|
| 96 |
-
def test_thinking_bypass(t: str):
|
| 97 |
-
"""When thinking disabled via enable_thinking=False, bypass is injected."""
|
| 98 |
-
messages = [{"role": "user", "content": "Hello"}]
|
| 99 |
-
out = render(t, messages, enable_thinking=False)
|
| 100 |
-
check("Think bypass: <think>\\n\\n</think>\\n\\n present",
|
| 101 |
-
"<think>\n\n</think>\n\n" in out, f"tail: {repr(out[-60:])}")
|
| 102 |
-
check("Think bypass: no open-only <think>\\n at end",
|
| 103 |
-
not out.endswith("<think>\n"))
|
| 104 |
-
|
| 105 |
-
def test_think_off_token(t: str):
|
| 106 |
-
"""<|think_off|> in system message disables thinking."""
|
| 107 |
-
messages = [
|
| 108 |
-
{"role": "system", "content": "You are helpful.<|think_off|>"},
|
| 109 |
-
{"role": "user", "content": "Hello"},
|
| 110 |
-
]
|
| 111 |
-
out = render(t, messages)
|
| 112 |
-
check("<|think_off|> disables thinking", "<think>\n\n</think>\n\n" in out)
|
| 113 |
-
check("<|think_off|> token stripped from output", "<|think_off|>" not in out)
|
| 114 |
-
|
| 115 |
-
def test_think_on_after_off(t: str):
|
| 116 |
-
"""<|think_on|> re-enables thinking after <|think_off|>."""
|
| 117 |
-
messages = [
|
| 118 |
-
{"role": "system", "content": "<|think_off|>"},
|
| 119 |
-
{"role": "user", "content": "Step 1"},
|
| 120 |
-
{"role": "assistant", "content": "Done."},
|
| 121 |
-
{"role": "user", "content": "<|think_on|>Now think"},
|
| 122 |
-
]
|
| 123 |
-
out = render(t, messages)
|
| 124 |
-
check("<|think_on|> re-enables thinking", out.endswith("<think>\n"),
|
| 125 |
-
f"tail: {repr(out[-40:])}")
|
| 126 |
-
|
| 127 |
-
def test_tier1_error_escalation(t: str):
|
| 128 |
-
"""First tool error injects Tier 1 correction hint."""
|
| 129 |
-
messages = [
|
| 130 |
-
{"role": "user", "content": "Read a file"},
|
| 131 |
-
{"role": "assistant", "content": "",
|
| 132 |
-
"tool_calls": [{"function": {"name": "read_file",
|
| 133 |
-
"arguments": {"path": "/foo", "pages": "1-30"}}}]},
|
| 134 |
-
{"role": "tool", "content": "Pages range exceeds maximum of 20 pages per request."},
|
| 135 |
-
]
|
| 136 |
-
tools = [{"name": "read_file", "description": "Read",
|
| 137 |
-
"parameters": {"type": "object", "properties": {"path": {"type": "string"}},
|
| 138 |
-
"required": ["path"]}}]
|
| 139 |
-
out = render(t, messages, tools=tools)
|
| 140 |
-
check("Tier 1: correction hint in gen-prompt",
|
| 141 |
-
"The previous tool call returned an error" in out,
|
| 142 |
-
f"tail: {repr(out[-120:])}")
|
| 143 |
-
check("Tier 1: think block still open (not bypassed)", out.endswith("\n"))
|
| 144 |
-
|
| 145 |
-
def test_tier2_error_escalation(t: str):
|
| 146 |
-
"""Two consecutive tool errors trigger Tier 2 bypass."""
|
| 147 |
-
tool_error = "Pages range exceeds maximum of 20 pages per request."
|
| 148 |
-
messages = [
|
| 149 |
-
{"role": "user", "content": "Read a file"},
|
| 150 |
-
{"role": "assistant", "content": "",
|
| 151 |
-
"tool_calls": [{"function": {"name": "read_file",
|
| 152 |
-
"arguments": {"path": "/foo", "pages": "1-30"}}}]},
|
| 153 |
-
{"role": "tool", "content": tool_error},
|
| 154 |
-
{"role": "assistant", "content": "",
|
| 155 |
-
"tool_calls": [{"function": {"name": "read_file",
|
| 156 |
-
"arguments": {"path": "/foo", "pages": "1-25"}}}]},
|
| 157 |
-
{"role": "tool", "content": tool_error},
|
| 158 |
-
]
|
| 159 |
-
tools = [{"name": "read_file", "description": "Read",
|
| 160 |
-
"parameters": {"type": "object", "properties": {"path": {"type": "string"}},
|
| 161 |
-
"required": ["path"]}}]
|
| 162 |
-
out = render(t, messages, tools=tools)
|
| 163 |
-
check("Tier 2: think bypass injected", "<think>\n\n</think>\n\n" in out,
|
| 164 |
-
f"tail: {repr(out[-200:])}")
|
| 165 |
-
check("Tier 2: escalation warning present",
|
| 166 |
-
"consecutive tool errors" in out or "consecutive" in out,
|
| 167 |
-
f"tail: {repr(out[-200:])}")
|
| 168 |
-
|
| 169 |
-
def test_length_gated_detection(t: str):
|
| 170 |
-
"""Long tool response (code content with 'error') must NOT trigger error flag."""
|
| 171 |
-
long_content = ("// Error handling\nfunction handleError(e) {\n"
|
| 172 |
-
" throw new Error('invalid input');\n}\n") * 30 # >> 500 chars
|
| 173 |
-
messages = [
|
| 174 |
-
{"role": "user", "content": "Read the code"},
|
| 175 |
-
{"role": "assistant", "content": "",
|
| 176 |
-
"tool_calls": [{"function": {"name": "read_file",
|
| 177 |
-
"arguments": {"path": "app.js"}}}]},
|
| 178 |
-
{"role": "tool", "content": long_content},
|
| 179 |
-
]
|
| 180 |
-
tools = [{"name": "read_file", "description": "Read",
|
| 181 |
-
"parameters": {"type": "object", "properties": {"path": {"type": "string"}},
|
| 182 |
-
"required": ["path"]}}]
|
| 183 |
-
out = render(t, messages, tools=tools)
|
| 184 |
-
check("Length gate: long response with 'error' does NOT trigger hint",
|
| 185 |
-
"The previous tool call returned an error" not in out,
|
| 186 |
-
f"tail: {repr(out[-80:])}")
|
| 187 |
-
check("Length gate: normal gen-prompt after long response",
|
| 188 |
-
out.endswith("<think>\n"), f"tail: {repr(out[-40:])}")
|
| 189 |
-
|
| 190 |
-
def test_error_counter_resets_on_success(t: str):
|
| 191 |
-
"""After a successful tool call, the consecutive failure counter resets."""
|
| 192 |
-
tool_error = "Error: file not found."
|
| 193 |
-
messages = [
|
| 194 |
-
{"role": "user", "content": "Do something"},
|
| 195 |
-
{"role": "assistant", "content": "",
|
| 196 |
-
"tool_calls": [{"function": {"name": "read_file", "arguments": {"path": "/bad"}}}]},
|
| 197 |
-
{"role": "tool", "content": tool_error}, # error → cf=1
|
| 198 |
-
{"role": "assistant", "content": "",
|
| 199 |
-
"tool_calls": [{"function": {"name": "read_file", "arguments": {"path": "/good"}}}]},
|
| 200 |
-
{"role": "tool", "content": "file content here " * 30}, # success, long → cf=0
|
| 201 |
-
{"role": "assistant", "content": "",
|
| 202 |
-
"tool_calls": [{"function": {"name": "read_file", "arguments": {"path": "/bad2"}}}]},
|
| 203 |
-
{"role": "tool", "content": tool_error}, # error → cf=1 again (not 2)
|
| 204 |
-
]
|
| 205 |
-
tools = [{"name": "read_file", "description": "Read",
|
| 206 |
-
"parameters": {"type": "object", "properties": {"path": {"type": "string"}},
|
| 207 |
-
"required": ["path"]}}]
|
| 208 |
-
out = render(t, messages, tools=tools)
|
| 209 |
-
# Should be Tier 1 (cf=1), not Tier 2 (cf>=2)
|
| 210 |
-
check("Counter reset: Tier 1 after success+new error (not Tier 2)",
|
| 211 |
-
"The previous tool call returned an error" in out and
|
| 212 |
-
"consecutive tool errors" not in out,
|
| 213 |
-
f"tail: {repr(out[-200:])}")
|
| 214 |
-
|
| 215 |
-
def test_historical_thinking_stripped(t: str):
|
| 216 |
-
"""Historical assistant <think> blocks are stripped (not last message)."""
|
| 217 |
-
messages = [
|
| 218 |
-
{"role": "user", "content": "Q1"},
|
| 219 |
-
{"role": "assistant", "content": "<think>\nmy thoughts\n</think>\n\nAnswer 1"},
|
| 220 |
-
{"role": "user", "content": "Q2"},
|
| 221 |
-
]
|
| 222 |
-
out = render(t, messages)
|
| 223 |
-
check("Historical think stripped by default", "my thoughts" not in out)
|
| 224 |
-
|
| 225 |
-
def test_preserve_thinking(t: str):
|
| 226 |
-
"""With preserve_thinking=True, historical <think> blocks are kept."""
|
| 227 |
-
messages = [
|
| 228 |
-
{"role": "user", "content": "Q1"},
|
| 229 |
-
{"role": "assistant", "content": "<think>\nmy thoughts\n</think>\n\nAnswer 1"},
|
| 230 |
-
{"role": "user", "content": "Q2"},
|
| 231 |
-
]
|
| 232 |
-
out = render(t, messages, preserve_thinking=True)
|
| 233 |
-
check("preserve_thinking=True keeps historical thoughts", "my thoughts" in out)
|
| 234 |
-
|
| 235 |
-
def test_developer_role(t: str):
|
| 236 |
-
"""developer role is accepted (same as system)."""
|
| 237 |
-
messages = [
|
| 238 |
-
{"role": "developer", "content": "You are a coder."},
|
| 239 |
-
{"role": "user", "content": "Write code"},
|
| 240 |
-
]
|
| 241 |
-
try:
|
| 242 |
-
out = render(t, messages)
|
| 243 |
-
check("developer role: no crash", True)
|
| 244 |
-
check("developer role: content rendered", "You are a coder." in out)
|
| 245 |
-
except Exception as e:
|
| 246 |
-
check("developer role: no crash", False, str(e))
|
| 247 |
-
|
| 248 |
-
def test_mid_conversation_system(t: str):
|
| 249 |
-
"""System messages mid-conversation are rendered chronologically."""
|
| 250 |
-
messages = [
|
| 251 |
-
{"role": "user", "content": "Hello"},
|
| 252 |
-
{"role": "assistant", "content": "Hi"},
|
| 253 |
-
{"role": "system", "content": "You must now speak in French."},
|
| 254 |
-
{"role": "user", "content": "What's up?"},
|
| 255 |
-
]
|
| 256 |
-
try:
|
| 257 |
-
out = render(t, messages)
|
| 258 |
-
check("Mid-conv system: no crash", True)
|
| 259 |
-
check("Mid-conv system: content present", "You must now speak in French." in out)
|
| 260 |
-
except Exception as e:
|
| 261 |
-
check("Mid-conv system: no crash", False, str(e))
|
| 262 |
-
|
| 263 |
-
def test_tool_response_wrapping(t: str):
|
| 264 |
-
"""Tool responses are wrapped in <tool_response> tags."""
|
| 265 |
-
messages = [
|
| 266 |
-
{"role": "user", "content": "Get data"},
|
| 267 |
-
{"role": "assistant", "content": "",
|
| 268 |
-
"tool_calls": [{"function": {"name": "fetch", "arguments": {"url": "https://example.com"}}}]},
|
| 269 |
-
{"role": "tool", "content": "data here"},
|
| 270 |
-
]
|
| 271 |
-
tools = [{"name": "fetch", "description": "Fetch URL",
|
| 272 |
-
"parameters": {"type": "object", "properties": {"url": {"type": "string"}},
|
| 273 |
-
"required": ["url"]}}]
|
| 274 |
-
out = render(t, messages, tools=tools)
|
| 275 |
-
check("Tool response: <tool_response> wrapper present", "<tool_response>" in out)
|
| 276 |
-
check("Tool response: content inside wrapper", "data here" in out)
|
| 277 |
-
|
| 278 |
-
def test_no_tools_no_crash(t: str):
|
| 279 |
-
"""Template works without any tools passed."""
|
| 280 |
-
messages = [{"role": "user", "content": "What is 2+2?"}]
|
| 281 |
-
try:
|
| 282 |
-
out = render(t, messages)
|
| 283 |
-
check("No tools: no crash", True)
|
| 284 |
-
check("No tools: normal gen-prompt", out.endswith("<think>\n"))
|
| 285 |
-
except Exception as e:
|
| 286 |
-
check("No tools: no crash", False, str(e))
|
| 287 |
-
|
| 288 |
-
def test_string_arguments_passthrough(t: str):
|
| 289 |
-
"""String tool arguments (pre-serialized JSON) are passed through as-is."""
|
| 290 |
-
messages = [
|
| 291 |
-
{"role": "user", "content": "Search"},
|
| 292 |
-
{"role": "assistant", "content": "",
|
| 293 |
-
"tool_calls": [{"function": {"name": "search",
|
| 294 |
-
"arguments": '{"query": "python", "limit": 5}'}}]},
|
| 295 |
-
{"role": "tool", "content": "results"},
|
| 296 |
-
]
|
| 297 |
-
tools = [{"name": "search", "description": "Search",
|
| 298 |
-
"parameters": {"type": "object", "properties": {"query": {"type": "string"}},
|
| 299 |
-
"required": ["query"]}}]
|
| 300 |
-
out = render(t, messages, tools=tools)
|
| 301 |
-
check("String args: passthrough without crash", "search" in out)
|
| 302 |
-
|
| 303 |
-
# ── New tests for v16 fixes ────────────────────────────────────────────────────
|
| 304 |
-
|
| 305 |
-
def test_shell_result_false_positive(t: str):
|
| 306 |
-
"""Short grep results containing 'error' in identifiers must NOT trigger error flag."""
|
| 307 |
-
shell_result = '$ grep -n "error_message" orchestrator.go (timeout 5s)\n\n661: "error_message": "",\n\nTook 0.1s'
|
| 308 |
-
messages = [
|
| 309 |
-
{"role": "user", "content": "Search for error_message"},
|
| 310 |
-
{"role": "assistant", "content": "",
|
| 311 |
-
"tool_calls": [{"function": {"name": "shell",
|
| 312 |
-
"arguments": {"cmd": "grep -n error_message file.go"}}}]},
|
| 313 |
-
{"role": "tool", "content": shell_result},
|
| 314 |
-
]
|
| 315 |
-
tools = [{"name": "shell", "description": "Run shell command",
|
| 316 |
-
"parameters": {"type": "object", "properties": {"cmd": {"type": "string"}},
|
| 317 |
-
"required": ["cmd"]}}]
|
| 318 |
-
out = render(t, messages, tools=tools)
|
| 319 |
-
check("Shell false-positive: grep with 'error_message' not flagged",
|
| 320 |
-
"The previous tool call returned an error" not in out,
|
| 321 |
-
f"tail: {repr(out[-80:])}")
|
| 322 |
-
check("Shell false-positive: normal gen-prompt after grep result",
|
| 323 |
-
out.endswith("<think>\n"), f"tail: {repr(out[-40:])}")
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
def test_no_thinking_with_error_escalation(t: str):
|
| 327 |
-
"""When enable_thinking=False and a tool errors, correction hint must NOT open a <think> block."""
|
| 328 |
-
tool_error = "Pages range exceeds maximum of 20 pages per request."
|
| 329 |
-
messages = [
|
| 330 |
-
{"role": "user", "content": "Read a file"},
|
| 331 |
-
{"role": "assistant", "content": "",
|
| 332 |
-
"tool_calls": [{"function": {"name": "read_file",
|
| 333 |
-
"arguments": {"path": "/foo", "pages": "1-30"}}}]},
|
| 334 |
-
{"role": "tool", "content": tool_error},
|
| 335 |
-
]
|
| 336 |
-
tools = [{"name": "read_file", "description": "Read",
|
| 337 |
-
"parameters": {"type": "object", "properties": {"path": {"type": "string"}},
|
| 338 |
-
"required": ["path"]}}]
|
| 339 |
-
out = render(t, messages, tools=tools, enable_thinking=False)
|
| 340 |
-
check("No-think + error: correction hint present",
|
| 341 |
-
"The previous tool call returned an error" in out,
|
| 342 |
-
f"tail: {repr(out[-120:])}")
|
| 343 |
-
check("No-think + error: does not end with open think block",
|
| 344 |
-
not out.rstrip().endswith("<think>"),
|
| 345 |
-
f"tail: {repr(out[-80:])}")
|
| 346 |
-
check("No-think + error: no unclosed <think> in error section",
|
| 347 |
-
"<think>\nThe previous" not in out,
|
| 348 |
-
f"tail: {repr(out[-120:])}")
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
# ── Runner ─────────────────────────────────────────────────────────────────────
|
| 352 |
-
|
| 353 |
-
TESTS = [
|
| 354 |
-
test_xml_tool_call_format,
|
| 355 |
-
test_tool_instructions_format,
|
| 356 |
-
test_normal_generation_prompt,
|
| 357 |
-
test_thinking_bypass,
|
| 358 |
-
test_think_off_token,
|
| 359 |
-
test_think_on_after_off,
|
| 360 |
-
test_tier1_error_escalation,
|
| 361 |
-
test_tier2_error_escalation,
|
| 362 |
-
test_length_gated_detection,
|
| 363 |
-
test_error_counter_resets_on_success,
|
| 364 |
-
test_historical_thinking_stripped,
|
| 365 |
-
test_preserve_thinking,
|
| 366 |
-
test_developer_role,
|
| 367 |
-
test_mid_conversation_system,
|
| 368 |
-
test_tool_response_wrapping,
|
| 369 |
-
test_no_tools_no_crash,
|
| 370 |
-
test_string_arguments_passthrough,
|
| 371 |
-
test_shell_result_false_positive,
|
| 372 |
-
test_no_thinking_with_error_escalation,
|
| 373 |
-
]
|
| 374 |
-
results: list[bool] = []
|
| 375 |
-
|
| 376 |
-
def run_tests():
|
| 377 |
-
print(f"\n{'═'*60}")
|
| 378 |
-
print(f" Testing v17 Chat Template")
|
| 379 |
-
print(f"{'═'*60}")
|
| 380 |
-
try:
|
| 381 |
-
tmpl = load_template()
|
| 382 |
-
except FileNotFoundError:
|
| 383 |
-
print(f" Template not found: chat_template.jinja")
|
| 384 |
-
return
|
| 385 |
-
for fn in TESTS:
|
| 386 |
-
label = fn.__name__.replace("test_", "").replace("_", " ").title()
|
| 387 |
-
print(f"\n [{label}]")
|
| 388 |
-
fn(tmpl)
|
| 389 |
-
|
| 390 |
-
if __name__ == "__main__":
|
| 391 |
-
results.clear()
|
| 392 |
-
run_tests()
|
| 393 |
-
|
| 394 |
-
total = len(results)
|
| 395 |
-
passed = sum(results)
|
| 396 |
-
failed = total - passed
|
| 397 |
-
print(f"\n{'═'*60}")
|
| 398 |
-
print(f" Results: {passed}/{total} passed", end="")
|
| 399 |
-
if failed:
|
| 400 |
-
print(f" \033[91m({failed} failed)\033[0m")
|
| 401 |
-
else:
|
| 402 |
-
print(f" \033[92m(all passed)\033[0m")
|
| 403 |
-
print(f"{'═'*60}\n")
|
| 404 |
-
sys.exit(0 if failed == 0 else 1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
scripts/test_v20.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import json
|
| 4 |
+
import traceback
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
from jinja2 import Environment, FileSystemLoader, StrictUndefined
|
| 8 |
+
except ImportError:
|
| 9 |
+
print("Error: jinja2 is required to run tests. Please install it using 'pip install jinja2'")
|
| 10 |
+
sys.exit(1)
|
| 11 |
+
|
| 12 |
+
TEMPLATE_FILE = 'chat_template.jinja'
|
| 13 |
+
TEMPLATE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 14 |
+
|
| 15 |
+
env = Environment(
|
| 16 |
+
loader=FileSystemLoader(TEMPLATE_DIR),
|
| 17 |
+
undefined=StrictUndefined,
|
| 18 |
+
keep_trailing_newline=True,
|
| 19 |
+
lstrip_blocks=True,
|
| 20 |
+
trim_blocks=True
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
def raise_exception(msg):
|
| 24 |
+
raise Exception(msg)
|
| 25 |
+
|
| 26 |
+
env.globals['raise_exception'] = raise_exception
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
template = env.get_template(TEMPLATE_FILE)
|
| 30 |
+
except Exception as e:
|
| 31 |
+
print(f"Error loading template: {e}")
|
| 32 |
+
sys.exit(1)
|
| 33 |
+
|
| 34 |
+
def run_test(name, messages, tools=None, kwargs=None, expected_in=None, expected_not_in=None, expect_error=False):
|
| 35 |
+
if kwargs is None:
|
| 36 |
+
kwargs = {}
|
| 37 |
+
|
| 38 |
+
print(f"\n--- Running Test: {name} ---")
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
render_kwargs = {'messages': messages, 'add_generation_prompt': True}
|
| 42 |
+
if tools is not None:
|
| 43 |
+
render_kwargs['tools'] = tools
|
| 44 |
+
render_kwargs.update(kwargs)
|
| 45 |
+
|
| 46 |
+
rendered = template.render(**render_kwargs)
|
| 47 |
+
|
| 48 |
+
if expect_error:
|
| 49 |
+
print("❌ FAILED: Expected an exception but got none.")
|
| 50 |
+
return False
|
| 51 |
+
|
| 52 |
+
success = True
|
| 53 |
+
|
| 54 |
+
if expected_in:
|
| 55 |
+
for ex in expected_in:
|
| 56 |
+
if ex not in rendered:
|
| 57 |
+
print(f"❌ FAILED: Missing expected string:\n'''{ex}'''")
|
| 58 |
+
print(f"Rendered:\n{rendered}")
|
| 59 |
+
success = False
|
| 60 |
+
|
| 61 |
+
if expected_not_in:
|
| 62 |
+
for n_ex in expected_not_in:
|
| 63 |
+
if n_ex in rendered:
|
| 64 |
+
print(f"❌ FAILED: Found string that should NOT be present:\n'''{n_ex}'''")
|
| 65 |
+
print(f"Rendered:\n{rendered}")
|
| 66 |
+
success = False
|
| 67 |
+
|
| 68 |
+
if success:
|
| 69 |
+
print("✅ PASSED")
|
| 70 |
+
return True
|
| 71 |
+
return False
|
| 72 |
+
|
| 73 |
+
except Exception as e:
|
| 74 |
+
if expect_error:
|
| 75 |
+
print(f"✅ PASSED (Caught expected error: {e})")
|
| 76 |
+
return True
|
| 77 |
+
print(f"❌ FAILED with exception:\n{traceback.format_exc()}")
|
| 78 |
+
return False
|
| 79 |
+
|
| 80 |
+
# Tests
|
| 81 |
+
tests_passed = 0
|
| 82 |
+
tests_total = 0
|
| 83 |
+
|
| 84 |
+
def execute_test(*args, **kwargs):
|
| 85 |
+
global tests_passed, tests_total
|
| 86 |
+
tests_total += 1
|
| 87 |
+
if run_test(*args, **kwargs):
|
| 88 |
+
tests_passed += 1
|
| 89 |
+
|
| 90 |
+
# 1. auto_disable_thinking_with_tools (Default logic)
|
| 91 |
+
execute_test(
|
| 92 |
+
"auto_disable_thinking_with_tools (enabled via kwarg)",
|
| 93 |
+
messages=[{"role": "user", "content": "Hello!"}],
|
| 94 |
+
tools=[{"name": "test_tool"}],
|
| 95 |
+
kwargs={"auto_disable_thinking_with_tools": True},
|
| 96 |
+
expected_in=["<think>\n</think>\n"], # Should be stripped
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
execute_test(
|
| 100 |
+
"auto_disable_thinking_with_tools (disabled via kwarg -> allows thinking)",
|
| 101 |
+
messages=[{"role": "user", "content": "Hello!"}],
|
| 102 |
+
tools=[{"name": "test_tool"}],
|
| 103 |
+
kwargs={"auto_disable_thinking_with_tools": False},
|
| 104 |
+
expected_in=["<think>\n"],
|
| 105 |
+
expected_not_in=["<think>\n</think>\n"]
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
# 2. inline <|think_on|> overrides auto_disable_thinking_with_tools
|
| 109 |
+
execute_test(
|
| 110 |
+
"inline <|think_on|> overrides auto_disable",
|
| 111 |
+
messages=[{"role": "user", "content": "Hello! <|think_on|>"}],
|
| 112 |
+
tools=[{"name": "test_tool"}],
|
| 113 |
+
kwargs={"auto_disable_thinking_with_tools": True},
|
| 114 |
+
expected_in=["<think>\n"],
|
| 115 |
+
expected_not_in=["<think>\n</think>\n", "<|think_on|>"] # Tag must be stripped
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
# 3. Payload truncation
|
| 119 |
+
execute_test(
|
| 120 |
+
"max_tool_arg_chars truncation",
|
| 121 |
+
messages=[{"role": "user", "content": "Call tool"}, {"role": "assistant", "content": "", "tool_calls": [{"function": {"name": "test", "arguments": {"param": "1234567890"}}}]}],
|
| 122 |
+
kwargs={"max_tool_arg_chars": 5},
|
| 123 |
+
expected_in=["12345\n[TRUNCATED"]
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
execute_test(
|
| 127 |
+
"max_tool_response_chars truncation",
|
| 128 |
+
messages=[{"role": "user", "content": "Do it"}, {"role": "assistant", "content": "calling", "tool_calls": [{"name": "test"}]}, {"role": "tool", "content": "1234567890"}],
|
| 129 |
+
kwargs={"max_tool_response_chars": 5},
|
| 130 |
+
expected_in=["<tool_response>\n12345\n[TRUNCATED"]
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
# 4. Mid-conversation System Prompt
|
| 134 |
+
execute_test(
|
| 135 |
+
"mid-conversation system prompt",
|
| 136 |
+
messages=[{"role": "user", "content": "Hello"}, {"role": "system", "content": "Reminder: Be polite"}],
|
| 137 |
+
expected_in=["<|im_start|>system\nReminder: Be polite<|im_end|>"]
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# 5. Parallel tools delimiter
|
| 141 |
+
execute_test(
|
| 142 |
+
"parallel tools delimiter",
|
| 143 |
+
messages=[{"role": "user", "content": "x"}, {"role": "assistant", "content": "", "tool_calls": [{"name": "t1"}, {"name": "t2"}]}],
|
| 144 |
+
expected_in=["</tool_call>\n\n<tool_call>"]
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
# 6. Deep Agent Fallback
|
| 148 |
+
execute_test(
|
| 149 |
+
"deep agent fallback (no user message)",
|
| 150 |
+
messages=[{"role": "system", "content": "Sys"}, {"role": "tool", "content": "test"}],
|
| 151 |
+
expected_in=["<|im_start|>system\nSys", "<|im_start|>user\n<tool_response>"]
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
# 7. Error Escalation
|
| 155 |
+
execute_test(
|
| 156 |
+
"error escalation warnings",
|
| 157 |
+
messages=[
|
| 158 |
+
{"role": "user", "content": "Do it"},
|
| 159 |
+
{"role": "tool", "content": "error: something failed"},
|
| 160 |
+
{"role": "assistant", "content": "calling"},
|
| 161 |
+
{"role": "tool", "content": "error: failed again"}
|
| 162 |
+
],
|
| 163 |
+
expected_in=["⚠️ SYSTEM WARNING: 2 consecutive tool errors", "<think>\n</think>\n"]
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
print(f"\n=============================")
|
| 167 |
+
print(f"Test Summary: {tests_passed} / {tests_total} passed.")
|
| 168 |
+
if tests_passed == tests_total:
|
| 169 |
+
print("All tests passed successfully! 🎉")
|
| 170 |
+
sys.exit(0)
|
| 171 |
+
else:
|
| 172 |
+
print("Some tests failed.")
|
| 173 |
+
sys.exit(1)
|