The power of modern large language models like Qwen3 doesn’t just come from their massive parameter counts; it’s also deeply embedded in the sophisticated logic of their chat templates. These templates are not simple string formatters—they are intricate engines that orchestrate the flow of conversation, manage context, and enable advanced capabilities like chain-of-thought reasoning and multi-tool use.

This post will dissect the Qwen3 chat template. We’ll explore how it masterfully handles reasoning traces and orchestrates complex tool calls, revealing why understanding this template is the key to unlocking the model’s full agentic potential.


The Anatomy of the Qwen3 Chat Template

The template can be broken down into four logical blocks, each with a distinct responsibility.

Block 1: The System Preamble & Tool Declaration

This initial block sets the stage for the entire conversation. Its primary job is to inform the model of its core instructions and, crucially, any tools it has at its disposal.

{# Block 1: Tool Definitions Preamble #}
{%- if tools %}
    {{- '<|im_start|>system\n' }}
    {%- if messages[0].role == 'system' %}
        {{- messages[0].content + '\n\n' }}
    {%- endif %}
    {{- "# Tools\n\nYou may call one or more functions to assist with the user query...\n<tools>" }}
    {%- for tool in tools %}
        {{- "\n" }}{{- tool | tojson }}
    {%- endfor %}
    {{- "\n</tools>\n\n...For each function call, return...\n</tool_call><|im_end|>\n" }}
{%- else %}
    {%- if messages[0].role == 'system' %}
        {{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
    {%- endif %}
{%- endif %}
  • What it does: If a tools list is provided, it injects a detailed system prompt. This prompt includes the JSON definitions for each tool wrapped in <tools> tags and explicit instructions on how to format a function call using the <tool_call> tag.
  • Why it matters: This is the model’s instruction manual. It front-loads the necessary information, ensuring the model knows its capabilities and the exact syntax required to use them from the very beginning.

Block 2: The Rolling Checkpoint for Context Pruning

This is arguably the most intelligent part of the template. It’s a dynamic context management system that prevents the conversation history from becoming bloated with old, irrelevant reasoning.

{# Block 2: Rolling Checkpoint System #}
{%- set ns = namespace(..., last_query_index=messages|length - 1) %}
{%- for message in messages[::-1] %}
    {%- set index = (messages|length - 1) - loop.index0 %}
    {%- if ... message.role == "user" and not(message.content.startswith('<tool_response>')) %}
        {%- set ns.last_query_index = index %}
    {%- endif %}
{%- endfor %}
  • What it does: It loops through the conversation in reverse to find the index of the last genuine user query (i.e., not a machine-generated tool response). This index becomes a “checkpoint.”
  • Why it matters: The model’s reasoning (<think> block) is only useful for the current problem it’s solving. This checkpoint allows the template to distinguish between the “active” part of the conversation and the “settled” history. As we’ll see, any reasoning before this checkpoint gets pruned.

Block 3 & 4: The Main Loop and Generation Prompt

This is the workhorse that builds the final prompt string, applying the logic from the checkpoint system.

{# Block 3: Main Conversation Loop & Message Formatting #}
{%- for message in messages %}
    ...
    {%- elif message.role == "assistant" %}
        ...
        {%- if loop.index0 > ns.last_query_index %}
            {# This turn is "active" -> show the <think> block #}
            {{- '<|im_start|>' + message.role + '\n<think>...' }}
        {%- else %}
            {# This turn is "historical" -> strip the <think> block #}
            {{- '<|im_start|>' + message.role + '\n' + content }}
        {%- endif %}
        ...
    {%- endif %}
{%- endfor %}
 
{# Block 4: Final Generation Prompt #}
{%- if add_generation_prompt %}
    {{- '<|im_start|>assistant\n<think>\n' }}
{%- endif %}
  • What it does: It iterates through messages chronologically. For each assistant message, it checks if the message’s index is past the “checkpoint.”
    • If past the checkpoint: The context is active, so the reasoning in the <think> block is preserved.
    • If before the checkpoint: The context is historical, and the reasoning is stripped out, leaving only the final content.
  • Why it matters: This dynamic pruning keeps the input prompt concise and focused, preventing the model from getting bogged down by its own previous thought processes.

The Magic of <think>: A Corrected Explanation of Reasoning Traces

The template’s handling of reasoning is governed by one strict rule: only reasoning that occurs after the last genuine user prompt is preserved. This creates different outcomes for conversations with and without tools.

The Standard Case: Conversations Without Tools

In a standard back-and-forth dialogue, this rule results in only the final assistant’s reasoning being shown.

Consider a two-round conversation:

  1. [User, index 1]: “What’s 5+3?”
  2. [Assistant, index 2]: Thinks “5+3=8”, responds “8”.
  3. [User, index 3]: “What’s 7*2?”
  4. [Assistant, index 4]: Thinks “7*2=14”, responds “14”.

The template first finds the checkpoint: the last real user query is at index 3. Then, it processes the history:

  • The assistant message at index 2 is not greater than 3, so its <think> block is stripped.
  • The assistant message at index 4 is greater than 3, so its <think> block is preserved.

Resulting Prompt:

<|im_start|>user
What's 5+3?<|im_end|>
<|im_start|>assistant
8<|im_end|>
<|im_start|>user
What's 7*2?<|im_end|>
<|im_start|>assistant
<think>
User wants 7*2. That's 14.
</think>

14<|im_end|>

This elegantly keeps the history clean while showing the logic for the most recent answer.

The Advanced Case: Conversations With Tools

The same rule applies, but the structure of tool-use conversations changes the outcome. Reasoning is only preserved for the chain of events following the last user prompt.

Consider a two-round tool-use conversation:

  1. [User, index 1]: “Calculate .”
  2. [Assistant, index 2]: Calls the calculator tool.
  3. [Tool Response, index 3]
  4. [Assistant, index 4]: Summarizes the result, “The result is 8.”
  5. [User, index 5]: “Calculate .”
  6. [Assistant, index 6]: Calls the calculator tool.
  7. …and so on.

Here, the checkpoint is at index 5.

  • The assistant messages at index 2 and 4 are not greater than 5, so their <think> blocks are stripped.
  • The assistant message at index 6 is greater than 5, so its <think> block is shown.

Resulting Prompt (abbreviated):

...
<|im_start|>user
Calculate 5+3...<|im_end|>
<|im_start|>assistant
<tool_call>...</tool_call><|im_end|>
<|im_start|>user
<tool_response>8</tool_response><|im_end|>
<|im_start|>assistant
The result is 8.<|im_end|>
<|im_start|>user
Calculate 7*2...<|im_end|>
<|im_start|>assistant
<think>
Now the user wants 7*2. Using the calculator again.
</think>
<tool_call>...</tool_call><|im_end|>
...

The key insight is that the template prunes the reasoning from entire previous tool-use cycles, keeping only the reasoning for the currently active cycle.


The Checkpoint in Action: A Concrete Explanation

The difference in behavior isn’t arbitrary; it’s a direct consequence of how the single, definitive rolling checkpoint is established and applied.

Let’s trace the indices again with this corrected understanding:

Without ToolsWith Tools
[0] System[0] System (with tool defs)
[1] User: “5+3?”[1] User: “5+3?”
[2] Assistant: “8” (2<3, Reasoning stripped)[2] Assistant (calls tool) (2<5, Reasoning stripped)
[3] User: “7*2?” (last_query_index=3)[3] User (<tool_response>) (ignored)
[4] Assistant: “14” (4 > 3, shows <think>)[4] Assistant (summarizes) (4<5, Reasoning stripped)
[5] User: “7*2?” (last_query_index=5)
[6] Assistant (calls tool) (6 > 5, shows <think>)
[7] User (<tool_response>) (ignored)
[8] Assistant (summarizes) (8 > 5, shows <think>)

This table clearly shows how the location of the last_query_index determines which assistant turns are considered “active” and thus deserving of having their reasoning preserved in the final prompt.


Practical Guide to Tool Usage

1. Define Your Tools

Structure your tool definitions as a list of dictionaries following the OpenAI function-calling standard.

tools = [
    {
        "type": "function",
        "function": {
            "name": "calculator",
            "description": "Perform mathematical calculations",
            "parameters": { ... }
        }
    }
]

2. Apply the Template

When calling tokenizer.apply_chat_template, you must pass the tools argument.

template_output = tokenizer.apply_chat_template(
    messages,
    tools=tools,
    enable_thinking=True, # To see reasoning
    tokenize=False,
    add_generation_prompt=True
)

3. Structure Tool Calls and Responses

Your application code must handle the model’s output and provide the results back in the correct format.

  • Model Output (Assistant Turn):
    "tool_calls": [
      {"id": "call_1", "function": {"name": "calculator", "arguments": "{...}"}}
    ]
  • Your Input (Tool Turn):
    {"role": "tool", "tool_call_id": "call_1", "name": "calculator", "content": "8"}

By understanding these deep, concrete mechanics, you can move beyond simply using Qwen3 and begin to leverage the full, orchestrated power that its chat template enables.