llmman 0.1.689

Run any agent on any model, models stored as OCI images
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//! What a model's chat template lets a request choose about thinking,
//! read off the template text: the `reasoning_effort` levels it compares
//! against, whether it reads `enable_thinking`, whether it thinks at
//! all. Qwen3.8 takes `low`/`medium`/`xhigh` and raises on anything
//! else; gpt-oss reads `reasoning_effort` but names only its default;
//! Qwen3.5 and Gemma 4 have just the switch; Llama 3 has none.
//! `llmman launch` offers an integration exactly these (see
//! `cmd::launch::opencode::opencode_variants`), never a level the model rejects.
//! Also whether it renders a request's `tools` ([`handles_tools`]).

use std::ops::Range;

/// Every `reasoning_effort` level any template or provider spells,
/// lowest first.
pub const EFFORT_LEVELS: &[&str] = &["minimal", "low", "medium", "high", "xhigh", "max"];

/// What a template that reads `reasoning_effort` without naming its
/// choices is taken to accept: gpt-oss's three, which every provider
/// takes too (see `cmd::serve::anthropic::portable_efforts`).
pub const DEFAULT_EFFORT_LEVELS: &[&str] = &["low", "medium", "high"];

/// The levels llmman applies to a switch-only template: on, with a token
/// budget for `minimal` and `low` (`openai::effort_budget_tokens`).
pub const BUDGETED_EFFORT_LEVELS: &[&str] = &["minimal", "low", "medium", "high"];

/// Ollama's `model.Thinking`: the `think` values a model takes, and the
/// one used when a request sends none or one it does not take.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct Thinking {
    pub values: Vec<serde_json::Value>,
    pub default: serde_json::Value,
}

/// A chat template's thinking controls.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ThinkingControls {
    /// The template mentions thinking or reasoning at all. llama-server
    /// can switch any such model off (`enable_thinking: false`, or an
    /// empty think block where the template has no switch).
    pub thinks: bool,
    /// The template reads `enable_thinking`, so a kwarg turns thinking on
    /// as well as off (Gemma 4 defaults it off).
    pub enable_thinking: bool,
    /// The `reasoning_effort` levels it distinguishes, lowest first; empty
    /// when it reads none.
    pub efforts: Vec<&'static str>,
    /// Thinking is on when a request says nothing (Gemma 4's is off).
    pub default_on: bool,
    /// The level the template uses without `reasoning_effort`:
    /// `reasoning_effort|default('xhigh')`.
    pub default_effort: Option<&'static str>,
}

impl ThinkingControls {
    /// The choices to offer, in cycle order: `none` for a model that
    /// thinks, then its levels, or `thinking` when a switch is all it has.
    pub fn choices(&self) -> Vec<&'static str> {
        if !self.thinks {
            return Vec::new();
        }
        let mut choices = vec!["none"];
        if !self.efforts.is_empty() {
            choices.extend(&self.efforts);
        } else if self.enable_thinking {
            choices.push("thinking");
        }
        choices
    }

    /// Thinks, but a `reasoning_effort` level only switches it on.
    pub fn thinks_without_levels(&self) -> bool {
        self.thinks && self.efforts.is_empty()
    }

    /// The `think` values `/api/show` reports: off, then the template's
    /// levels, or [`BUDGETED_EFFORT_LEVELS`] if `budgeted` and it is
    /// switch-only, else on. The default is what an omitted `think` does.
    pub fn thinking(&self, budgeted: bool) -> Option<Thinking> {
        if !self.thinks {
            return None;
        }
        let levels: &[&str] = match (self.efforts.is_empty(), self.enable_thinking && budgeted) {
            (false, _) => &self.efforts,
            (true, true) => BUDGETED_EFFORT_LEVELS,
            (true, false) => &[],
        };
        let mut values = vec![false.into()];
        values.extend(levels.iter().map(|level| (*level).into()));
        let default = match levels {
            [] => {
                values.push(true.into());
                self.default_on.into()
            }
            _ if !self.default_on => false.into(),
            _ => self
                .default_effort
                .filter(|level| levels.contains(level))
                .unwrap_or(if levels.contains(&"medium") {
                    "medium"
                } else {
                    levels[levels.len() - 1]
                })
                .into(),
        };
        Some(Thinking { values, default })
    }
}

/// Reads the thinking controls off `template`. Levels are the
/// [`EFFORT_LEVELS`] quoted in a Jinja block that names
/// `reasoning_effort` (or a variable derived from it), outside another
/// variable's `in (...)` list, narrowed to an `in (...)` test of
/// `reasoning_effort` naming two or more so an alias rewritten before it
/// (Docker's Qwen3.8 `high`) is not offered. Fewer than two named —
/// gpt-oss's `default("medium")` alone — means
/// [`DEFAULT_EFFORT_LEVELS`]. `none` is a switch, not a level.
pub fn thinking_controls(template: &str) -> ThinkingControls {
    let template = strip_comments(template);
    let lower = template.to_ascii_lowercase();
    let thinks = lower.contains("think") || lower.contains("reasoning");
    if !thinks {
        return ThinkingControls::default();
    }
    let enable_thinking = template.contains("enable_thinking");
    let efforts = if template.contains("reasoning_effort") {
        let effort_blocks: Vec<&str> = blocks(&template)
            .filter(|block| block.contains("reasoning_effort"))
            .collect();
        let levels_among = |literals: Vec<&str>| -> Vec<&'static str> {
            EFFORT_LEVELS
                .iter()
                .copied()
                .filter(|level| literals.contains(level))
                .collect()
        };
        // Literals in effort lists, and all but another variable's list's.
        let (mut accepted, mut named) = (Vec::new(), Vec::new());
        for block in effort_blocks {
            let mut from = 0;
            for (list, of_effort) in membership_lists(block) {
                if of_effort {
                    accepted.extend(quoted_literals(&block[list]));
                } else if list.start >= from {
                    named.extend(quoted_literals(&block[from..list.start]));
                    from = list.end;
                }
            }
            named.extend(quoted_literals(&block[from..]));
        }
        let (accepted, named) = (levels_among(accepted), levels_among(named));
        if accepted.len() >= 2 {
            accepted
        } else if named.len() >= 2 {
            named
        } else {
            DEFAULT_EFFORT_LEVELS.to_vec()
        }
    } else {
        Vec::new()
    };
    // Thinking starts on unless the template reads the switch only to turn it on.
    let squeezed: String = lower.split_whitespace().collect();
    let default_on = !enable_thinking
        || [
            "enable_thinkingisfalse",
            "enable_thinking==false",
            "notenable_thinking",
            "enable_thinkingisundefinedor",
            "enable_thinkingisnotdefinedor",
            "enable_thinking|default(true)",
        ]
        .iter()
        .any(|test| squeezed.contains(test));
    let default_effort = squeezed
        .split_once("reasoning_effort|default(")
        .and_then(|(_, rest)| {
            rest.starts_with(['\'', '"']).then_some(())?;
            let literal = quoted_literals(rest).next()?;
            EFFORT_LEVELS
                .iter()
                .copied()
                .find(|level| *level == literal)
        });
    ThinkingControls {
        thinks,
        enable_thinking,
        efforts,
        default_on,
        default_effort,
    }
}

/// Whether `template` renders a request's tools: it names the variable
/// `tools` in a block, as ollama's own `tools` capability test does for
/// Go templates. One that only handles `tool_calls` has nowhere to put
/// the definitions, so is not one.
pub fn handles_tools(template: &str) -> bool {
    blocks(&strip_comments(template)).any(|block| names_variable(block, "tools"))
}

/// Whether `block` uses the variable `name`: the whole word, outside a
/// string, and not an attribute (`message.tools`).
fn names_variable(block: &str, name: &str) -> bool {
    let bytes = block.as_bytes();
    let is_word = |b: u8| b.is_ascii_alphanumeric() || b == b'_';
    let (mut at, mut previous) = (0, None::<u8>);
    while at < bytes.len() {
        let c = bytes[at];
        if c == b'\'' || c == b'"' {
            // To the closing quote; a backslash escapes the next byte.
            at += 1;
            while at < bytes.len() && bytes[at] != c {
                at += if bytes[at] == b'\\' { 2 } else { 1 };
            }
            at += 1;
            previous = Some(c);
        } else if is_word(c) {
            let end = bytes[at..]
                .iter()
                .position(|b| !is_word(*b))
                .map_or(bytes.len(), |n| at + n);
            if &block[at..end] == name && previous != Some(b'.') {
                return true;
            }
            at = end;
            previous = Some(b'a');
        } else {
            if !c.is_ascii_whitespace() {
                previous = Some(c);
            }
            at += 1;
        }
    }
    false
}

/// `template` without its `{# ... #}` comments.
fn strip_comments(template: &str) -> String {
    let mut out = String::with_capacity(template.len());
    let mut rest = template;
    while let Some(start) = rest.find("{#") {
        out.push_str(&rest[..start]);
        match rest[start..].find("#}") {
            Some(end) => rest = &rest[start + end + 2..],
            None => return out,
        }
    }
    out.push_str(rest);
    out
}

/// Each `{% ... %}` and `{{ ... }}` of `template`, in order.
fn blocks(template: &str) -> impl Iterator<Item = &str> {
    let mut rest = template;
    std::iter::from_fn(move || {
        let start = rest.find("{%").into_iter().chain(rest.find("{{")).min()?;
        let close = if rest[start..].starts_with("{%") {
            "%}"
        } else {
            "}}"
        };
        let end = rest[start + 2..].find(close)?;
        let block = &rest[start + 2..start + 2 + end];
        rest = &rest[start + 2 + end + 2..];
        Some(block)
    })
}

/// The span inside each `in (...)` or `in [...]` list in `block`, and
/// whether its left operand names `reasoning_effort` (or a variable
/// derived from it).
fn membership_lists(block: &str) -> impl Iterator<Item = (Range<usize>, bool)> + '_ {
    block.match_indices("in").filter_map(|(at, _)| {
        // `in` as a word: not the tail of `min` or `join`.
        let before = block[..at].chars().next_back()?;
        if !(before.is_whitespace() || before == ')') {
            return None;
        }
        let after = &block[at + 2..];
        let open = at + 2 + (after.len() - after.trim_start().len());
        let close = match block[open..].chars().next()? {
            '(' => ')',
            '[' => ']',
            _ => return None,
        };
        let end = open + block[open..].find(close)?;
        let lhs = block[..at].trim_end();
        let lhs = lhs.strip_suffix("not").map_or(lhs, str::trim_end);
        Some((
            open + 1..end,
            left_operand(lhs).contains("reasoning_effort"),
        ))
    })
}

/// The operand `before` ends with: `x.y`, `x | f`, `x|f('a')`, `( x | f )`.
fn left_operand(before: &str) -> &str {
    let bytes = before.as_bytes();
    let (mut start, mut depth) = (bytes.len(), 0usize);
    while start > 0 {
        let c = bytes[start - 1];
        match c {
            b')' | b']' => depth += 1,
            b'(' | b'[' if depth > 0 => depth -= 1,
            _ if depth > 0 => {}
            // Space joins only around a filter's `|`.
            _ if c.is_ascii_whitespace() => {
                let pipe_after = before[start..].trim_start().starts_with('|');
                let pipe_before = before[..start - 1].trim_end().ends_with('|');
                if !(pipe_after || pipe_before) {
                    break;
                }
            }
            _ if c.is_ascii_alphanumeric() || b"_.|".contains(&c) => {}
            _ => break,
        }
        start -= 1;
    }
    &before[start..]
}

/// The contents of every `'...'` and `"..."` in `text`, in order.
fn quoted_literals(text: &str) -> impl Iterator<Item = &str> {
    let mut rest = text;
    std::iter::from_fn(move || {
        let start = rest.find(['\'', '"'])?;
        let quote = rest.as_bytes()[start] as char;
        let after = &rest[start + 1..];
        let end = after.find(quote)?;
        rest = &after[end + 1..];
        Some(&after[..end])
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Qwen3.8 as shipped in `docker.io/ai/qwen3.8`: `high` is rewritten
    /// to `xhigh` before the membership test; the error message names
    /// levels only inside one long string.
    const QWEN3_8: &str = r#"
{%- if enable_thinking is undefined or enable_thinking is true %}
    {%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}
    {%- if resolved_reasoning_effort == 'high' %}
        {%- set resolved_reasoning_effort = 'xhigh' %}
    {%- endif %}
    {%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}
        {{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}
    {%- endif %}
{%- endif %}
{%- if enable_thinking is defined and enable_thinking is false %}
    {{- '<think>\n\n</think>\n\n' }}
{%- endif %}
"#;

    #[test]
    fn qwen3_8_names_its_levels_and_its_switch() {
        let controls = thinking_controls(QWEN3_8);
        assert_eq!(
            controls,
            ThinkingControls {
                thinks: true,
                enable_thinking: true,
                efforts: vec!["low", "medium", "xhigh"],
                default_on: true,
                default_effort: Some("xhigh"),
            }
        );
        assert_eq!(controls.choices(), ["none", "low", "medium", "xhigh"]);
        assert!(!controls.thinks_without_levels());
        // Minified to one line, the same.
        let one_line = QWEN3_8.replace('\n', "");
        assert_eq!(thinking_controls(&one_line), controls);
        // Upstream's template, without the alias, the same.
        let upstream = QWEN3_8.replace(
            "{%- if resolved_reasoning_effort == 'high' %}\n        {%- set resolved_reasoning_effort = 'xhigh' %}\n    {%- endif %}",
            "",
        );
        assert!(!upstream.contains("'high'"));
        assert_eq!(thinking_controls(&upstream), controls);
    }

    /// A test naming fewer than two levels, a word ending in `in`, or a
    /// test of another variable does not narrow.
    #[test]
    fn a_membership_test_narrows_the_named_levels() {
        let t = "{%- if reasoning_effort == 'max' %}{% set reasoning_effort = 'high' %}{% endif %}\
                 {%- if reasoning_effort not in ['high', \"low\"] %}{{ raise_exception('bad') }}{% endif %}";
        assert_eq!(thinking_controls(t).efforts, vec!["low", "high"]);
        let one = "{%- if reasoning_effort in ('low',) or reasoning_effort == 'high' %}{% endif %}";
        assert_eq!(thinking_controls(one).efforts, vec!["low", "high"]);
        let join = "{{- reasoning_effort ~ join('low', 'high') ~ min('medium', 'max') }}";
        assert_eq!(
            thinking_controls(join).efforts,
            vec!["low", "medium", "high", "max"]
        );
        let other = "{%- if mode in ('low', 'high') and reasoning_effort in ('medium', 'max') %}";
        assert_eq!(thinking_controls(other).efforts, vec!["medium", "max"]);
        let bare = "{%- if mode in ('low', 'high') and reasoning_effort %}";
        assert_eq!(thinking_controls(bare).efforts, DEFAULT_EFFORT_LEVELS);
        let block = "reasoning_effort not in ('a', 'b') and y in ('c', 'd') \
                     or (reasoning_effort|lower) in[1] or reasoning_effort | lower in [2] \
                     or ( reasoning_effort | default('x') ) in (3) or reasoning_effort in (";
        assert_eq!(
            membership_lists(block)
                .map(|(list, of_effort)| (&block[list], of_effort))
                .collect::<Vec<_>>(),
            [
                ("'a', 'b'", true),
                ("'c', 'd'", false),
                ("1", true),
                ("2", true),
                ("3", true)
            ]
        );
    }

    /// gpt-oss reads `reasoning_effort` but names only its default.
    #[test]
    fn a_template_that_names_no_choices_gets_the_default_levels() {
        let gpt_oss = r#"
{%- if reasoning_effort is not defined %}{%- set reasoning_effort = "medium" %}{%- endif %}
{{- "Reasoning: " + reasoning_effort + "\n\n" }}
"#;
        assert_eq!(
            thinking_controls(gpt_oss).efforts,
            DEFAULT_EFFORT_LEVELS.to_vec()
        );
        assert!(!thinking_controls(gpt_oss).thinks_without_levels());
    }

    /// Qwen3.5, GLM-5, Gemma 4, Nemotron 3: `enable_thinking`, no levels.
    #[test]
    fn a_switch_alone_offers_off_and_on() {
        let gemma4 = "{%- set enable_thinking = enable_thinking | default(false) -%}\
                      {%- if enable_thinking -%}<|think|>{%- endif -%}";
        let controls = thinking_controls(gemma4);
        assert!(controls.enable_thinking && controls.efforts.is_empty());
        assert_eq!(controls.choices(), ["none", "thinking"]);
        assert!(controls.thinks_without_levels());
    }

    /// What `/api/show` reports: off, the levels or switch, and the default.
    #[test]
    fn thinking_reports_the_values_a_template_takes() {
        use serde_json::json;
        let thinking = |template: &str, budgeted| {
            let t = thinking_controls(template).thinking(budgeted)?;
            Some((json!(t.values), t.default))
        };
        // Named levels, defaulting to the template's own.
        assert_eq!(
            thinking(QWEN3_8, false),
            Some((json!([false, "low", "medium", "xhigh"]), json!("xhigh")))
        );
        let gpt_oss = r#"{{- "Reasoning: " + reasoning_effort | default("medium") }}"#;
        assert_eq!(
            thinking(gpt_oss, true),
            Some((json!([false, "low", "medium", "high"]), json!("medium")))
        );
        // A switch that only sees `false` starts on; Gemma 4's starts off.
        let qwen3_5 = "{%- if enable_thinking is defined and enable_thinking is false %}<think></think>{%- endif %}";
        let undefined =
            "{%- if enable_thinking is not defined or enable_thinking %}<think>{%- endif %}";
        assert_eq!(
            thinking(undefined, false),
            Some((json!([false, true]), json!(true)))
        );
        let gemma4 = "{%- set enable_thinking = enable_thinking | default(false) -%}{%- if enable_thinking -%}<|think|>{%- endif -%}";
        assert_eq!(
            thinking(qwen3_5, false),
            Some((json!([false, true]), json!(true)))
        );
        assert_eq!(
            thinking(gemma4, false),
            Some((json!([false, true]), json!(false)))
        );
        // llmman bounds a switch's levels where it can: Qwen3.5 0.8B, #816.
        assert_eq!(
            thinking(qwen3_5, true),
            Some((
                json!([false, "minimal", "low", "medium", "high"]),
                json!("medium")
            ))
        );
        assert_eq!(
            thinking(gemma4, true),
            Some((
                json!([false, "minimal", "low", "medium", "high"]),
                json!(false)
            ))
        );
        // Thinking nothing reads: always on, can be switched off.
        let kimi =
            "{%- if thinking is defined and thinking is false -%}<think></think>{%- endif -%}";
        assert_eq!(
            thinking(kimi, true),
            Some((json!([false, true]), json!(true)))
        );
        assert_eq!(thinking("{{ messages }}", true), None);
    }

    /// Kimi K2.5, MiniMax M2.5: thinking with nothing a kwarg reads.
    #[test]
    fn thinking_without_a_kwarg_offers_only_off() {
        let kimi =
            "{%- if thinking is defined and thinking is false -%}<think></think>{%- endif -%}";
        assert_eq!(thinking_controls(kimi).choices(), ["none"]);
        let minimax = "{%- set reasoning_content = content.split('</think>')[0] -%}";
        assert_eq!(thinking_controls(minimax).choices(), ["none"]);
    }

    /// Llama 3.1, Phi-4: no thinking anywhere — a comment mentioning it
    /// does not count.
    #[test]
    fn a_plain_template_has_no_controls() {
        let llama = "{# no thinking here #}{{- '<|start_header_id|>' + message['role'] }}";
        assert_eq!(thinking_controls(llama), ThinkingControls::default());
        assert!(thinking_controls(llama).choices().is_empty());
        assert!(!thinking_controls(llama).thinks_without_levels());
        assert_eq!(thinking_controls(""), ThinkingControls::default());
    }

    /// Levels come out in cycle order, once each, without `none`, and
    /// only from blocks that name the variable.
    #[test]
    fn levels_are_ordered_deduplicated_and_scoped_to_the_variables_blocks() {
        let t = r#"{%- if reasoning_effort == "max" or reasoning_effort == "low" or reasoning_effort == "none" %}
{%- if reasoning_effort == 'low' %}{%- set unrelated = 'high' %}"#;
        assert_eq!(thinking_controls(t).efforts, vec!["low", "max"]);
    }

    /// Qwen3.5, Llama 3.1, gpt-oss, a macro taking them.
    #[test]
    fn a_template_that_reads_tools_handles_them() {
        let qwen = r##"{%- if tools %}{{- '<|im_start|>system\n' }}{{- "# Tools\n\n<tools>" }}
{%- for tool in tools %}{{- "\n" }}{{- tool | tojson }}{%- endfor %}{%- endif %}"##;
        let llama = "{%- if not tools is defined %}{%- set tools = none %}{%- endif %}";
        let gpt_oss = "{{- tools | tojson(indent=2) -}}";
        let macro_ = "{%- macro render_tools(tools) -%}{{ tools|length }}{%- endmacro -%}";
        let one_line = "{%-if tools%}x{%-endif%}";
        for template in [qwen, llama, gpt_oss, macro_, one_line] {
            assert!(handles_tools(template), "{template}");
        }
        // An escaped quote does not end the string.
        assert!(handles_tools(r"{{ 'it\'s' ~ tools }}"));
    }

    /// Gemma 3, and mentions that are not the variable.
    #[test]
    fn a_template_that_never_reads_tools_does_not() {
        let gemma3 = "{{ bos_token }}{%- for message in messages -%}\
                      {{ '<start_of_turn>' + message['role'] + '\\n' }}{%- endfor -%}";
        assert!(!handles_tools(gemma3));
        for template in [
            // Neighbouring names.
            "{%- if tool_calls %}{{ custom_tools }}{{ tools_in_user_message }}{%- endif %}",
            "{%- for tool in message.tool_calls %}{%- endfor %}",
            // An attribute, a key and the argument of a filter.
            "{{ message.tools }}",
            "{{ message['tools'] }}",
            "{{ messages | map(attribute='tools') }}",
            // A string, a comment, text between blocks.
            r#"{{- "You may use tools." }}"#,
            "{# tools #}{{ x }}",
            "You may use tools. {{ x }}",
            "",
        ] {
            assert!(!handles_tools(template), "{template}");
        }
    }

    #[test]
    fn blocks_and_literals_are_walked_in_order() {
        assert_eq!(
            blocks("a {% if x %}b{{ y }}c {% end").collect::<Vec<_>>(),
            [" if x ", " y "]
        );
        assert_eq!(
            quoted_literals(r#"x in ('a', "b c") ~ 'd"#).collect::<Vec<_>>(),
            ["a", "b c"]
        );
        assert_eq!(strip_comments("a{# b #}c{# open"), "ac");
    }
}