Skip to main content

dynamo_renderer/
template.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{collections::HashSet, sync::Arc};
5
6use anyhow::{Ok, Result};
7use minijinja::Environment;
8
9use super::PromptContextMixin;
10
11mod context;
12mod formatters;
13mod minimax_m2;
14mod oai;
15mod tokcfg;
16
17use super::{OAIPromptFormatter, PromptFormatter};
18pub use oai::may_be_fix_tool_schema;
19pub use tokcfg::{ChatTemplate, ChatTemplateValue};
20
21/// If the model is a DeepSeek family whose HF repo doesn't ship a Jinja
22/// `chat_template`, return the native Rust formatter for it. Returns `None`
23/// for everything else (the caller then loads the HF `tokenizer_config.json`
24/// template via [`PromptFormatter::from_parts`]).
25///
26/// `model_type_lower` is the lowercased `config.json` `model_type` (authoritative,
27/// survives `--served-model-name` renames); `display_name_lower` is the
28/// lowercased served name, used only as a fallback when `model_type` is absent.
29pub fn deepseek_formatter_for(
30    model_type_lower: &Option<String>,
31    display_name_lower: &str,
32) -> Option<PromptFormatter> {
33    if is_deepseek_v41(model_type_lower, display_name_lower) {
34        return Some(PromptFormatter::OAI(Arc::new(
35            super::deepseek::v41::DeepSeekV41Formatter,
36        )));
37    }
38    if is_deepseek_v4(model_type_lower, display_name_lower) {
39        tracing::info!(
40            model_type = ?model_type_lower,
41            display_name = %display_name_lower,
42            "Detected DeepSeek V4 model, using native Rust formatter",
43        );
44        return Some(PromptFormatter::OAI(Arc::new(
45            super::deepseek::v4::DeepSeekV4Formatter::new_thinking(),
46        )));
47    }
48    if is_deepseek_v3_2_non_exp(model_type_lower, display_name_lower) {
49        tracing::info!("Detected DeepSeek V3.2 model (non-Exp), using native Rust formatter");
50        return Some(PromptFormatter::OAI(Arc::new(
51            super::deepseek::v32::DeepSeekV32Formatter::new_thinking(),
52        )));
53    }
54    None
55}
56
57/// If the model is Kimi K3, return its native XTML formatter. K3 ships no
58/// Jinja chat template and must preserve special-vs-ordinary segment boundaries
59/// until tokenization.
60pub fn kimi_k3_formatter_for(
61    model_type_lower: &Option<String>,
62    display_name_lower: &str,
63    exclude_tools_when_tool_choice_none: bool,
64) -> Option<PromptFormatter> {
65    if !is_kimi_k3(model_type_lower, display_name_lower) {
66        return None;
67    }
68
69    tracing::info!(
70        model_type = ?model_type_lower,
71        display_name = %display_name_lower,
72        "Detected Kimi K3 model, using native Rust XTML formatter",
73    );
74    Some(PromptFormatter::OAI(Arc::new(
75        super::kimi_k3::KimiK3Formatter::new(exclude_tools_when_tool_choice_none),
76    )))
77}
78
79fn is_kimi_k3(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
80    match model_type_lower.as_deref() {
81        Some("kimi_k3") => true,
82        Some(_) => false,
83        None => ["kimi-k3", "kimi_k3", "kimik3"]
84            .iter()
85            .any(|needle| display_name_lower.contains(needle)),
86    }
87}
88
89/// Select a native formatter for model families that do not ship a usable HF
90/// `chat_template`.
91///
92/// Inkling is selected only from the authoritative `config.json` model type;
93/// unlike display-name substring matching, this remains stable under
94/// `--served-model-name` aliases. DeepSeek keeps its existing fallback for
95/// older model cards that do not publish `model_type`.
96pub fn native_formatter_for(
97    model_type_lower: &Option<String>,
98    display_name_lower: &str,
99) -> Option<PromptFormatter> {
100    if model_type_lower.as_deref() == Some("inkling_mm_model") {
101        tracing::info!(
102            model_type = ?model_type_lower,
103            "Detected Inkling model, using native Rust formatter",
104        );
105        return Some(PromptFormatter::OAI(Arc::new(
106            super::inkling::InklingFormatter,
107        )));
108    }
109
110    deepseek_formatter_for(model_type_lower, display_name_lower)
111}
112
113impl PromptFormatter {
114    pub fn from_parts(
115        config: ChatTemplate,
116        context: ContextMixins,
117        exclude_tools_when_tool_choice_none: bool,
118    ) -> Result<PromptFormatter> {
119        let formatter = HfTokenizerConfigJsonFormatter::with_options(
120            config,
121            context,
122            exclude_tools_when_tool_choice_none,
123        )?;
124        Ok(Self::OAI(Arc::new(formatter)))
125    }
126}
127
128/// Chat Template Jinja Renderer
129///
130/// Manages a Jinja environment with registered templates for chat formatting.
131/// Handles two types of ChatTemplateValue templates:
132///
133/// 1. String template: Registered as the 'default' template
134/// 2. Map template: Contains 'tool_use' and/or 'default' templates
135///    - tool_use: Template for tool-based interactions
136///    - default: Template for standard chat interactions
137///
138///   If the map contains both keys, the `tool_use` template is registered as the `tool_use` template
139///   and the `default` template is registered as the `default` template.
140struct JinjaEnvironment {
141    env: Environment<'static>,
142}
143
144/// Which message-shape restrictions one chat template enforces, probed once at
145/// load. Each rewrite in `normalize_system_messages` is gated on its own flag:
146/// the restrictions are independent, so a template that rejects a non-leading
147/// `system` (Qwen3.5) but accepts consecutive `user` turns keeps those turns
148/// separate instead of being reshaped for a rule it does not have.
149#[derive(Debug, Default, Clone, Copy)]
150struct SystemNormalization {
151    /// Template raises on a `system` turn that is not first.
152    demote_nonleading_system: bool,
153    /// Template raises on two adjacent `user` turns.
154    coalesce_consecutive_users: bool,
155}
156
157impl SystemNormalization {
158    fn is_required(&self) -> bool {
159        self.demote_nonleading_system || self.coalesce_consecutive_users
160    }
161}
162
163/// Formatter for HuggingFace tokenizer config JSON templates
164///
165/// Implements chat template rendering based on HuggingFace's tokenizer_config.json format.
166/// Supports:
167/// - Tool usage templates
168/// - Generation prompts
169/// - Context mixins for template customization
170#[derive(Debug)]
171struct HfTokenizerConfigJsonFormatter {
172    env: Environment<'static>,
173    config: ChatTemplate,
174    mixins: Arc<ContextMixins>,
175    supports_add_generation_prompt: bool,
176    requires_content_arrays: bool,
177    /// When true, strip tool definitions from the chat template when tool_choice is "none".
178    /// This prevents models from generating raw XML tool calls in the content field.
179    exclude_tools_when_tool_choice_none: bool,
180    /// Cached per selected template variant; native namespace rendering was
181    /// introduced by the template's `deferred_render_mode` argument.
182    /// A capable default must not opt an older tool-use variant into native tools.
183    default_template_handles_native_tools: bool,
184    tool_use_template_handles_native_tools: bool,
185    /// True if the `default` template natively references `reasoning_content`.
186    /// When true and rendering through `default`, skip injection — the template
187    /// handles it. Tracked separately for `default` and `tool_use` because HF
188    /// configs may register different sources for each: Gemma4's `tool_use`
189    /// template is adapted by `normalize_chat_template_source` to read
190    /// `reasoning_content`, while its `default` template is not. A single global
191    /// flag would wrongly suppress injection on the untouched `default` path and
192    /// silently drop prior assistant reasoning on no-tool renders.
193    default_template_handles_reasoning: bool,
194    /// True if the `tool_use` template natively references `reasoning_content`.
195    /// See `default_template_handles_reasoning` for rationale.
196    tool_use_template_handles_reasoning: bool,
197    /// True if the `default` template renders a string `reasoning_content` but
198    /// not the segment array sent with interleaved tool calls (MiniMax-M2 and
199    /// Qwen3 read it only when it `is string`). When true and rendering through
200    /// `default`, join the segments into the string the template expects.
201    default_template_requires_reasoning_string: bool,
202    /// See `default_template_requires_reasoning_string` for rationale.
203    tool_use_template_requires_reasoning_string: bool,
204    /// Per-family placeholder template for image content parts when flattening
205    /// mixed text+image content arrays into a single string (`preserve_arrays`
206    /// = false path). `{n}` in the template is substituted with the 1-based
207    /// image index. `None` when the model's chat template handles content
208    /// arrays natively (Qwen-VL family) or when we have no flatten strategy
209    /// for it (no MM-aware routing benefit either way).
210    image_placeholder_template: Option<&'static str>,
211    /// True if the `default` template branches on `tool_call.arguments is string`
212    /// and renders string arguments verbatim (Qwen3, Hermes, etc.; templates that
213    /// only use the test to reject strings don't count). When true and rendering
214    /// through `default`, skip pre-parsing the JSON-string
215    /// `tool_calls[].function.arguments` into an object — the template wants the
216    /// raw string verbatim. Pre-parsing forces the `tojson`-with-object branch and
217    /// re-emits with minijinja's compact separators, which breaks append-only
218    /// prefix matching across multi-step tool-use turns. Tracked separately for
219    /// `default` and `tool_use` because HF configs may register different sources
220    /// for each, and because `arguments is string` is tool_calls-specific — legacy
221    /// `function_call.arguments` lives outside that branch and is still
222    /// normalized unconditionally.
223    default_template_handles_tool_calls_arguments_string: bool,
224    /// True if the `tool_use` template branches on `tool_call.arguments is string`.
225    /// See `default_template_handles_tool_calls_arguments_string` for rationale.
226    tool_use_template_handles_tool_calls_arguments_string: bool,
227    /// Message-shape restrictions the `default` template enforces.
228    default_system_normalization: SystemNormalization,
229    /// Message-shape restrictions the `tool_use` template enforces.
230    /// Kept separate because dict-form HF configs may register templates with
231    /// different constraints.
232    tool_use_system_normalization: SystemNormalization,
233}
234
235// /// OpenAI Standard Prompt Formatter
236// pub trait StandardPromptFormatter {
237//     fn render(&self, context: &impl StandardPromptContext) -> Result<String>;
238// }
239
240// pub trait StandardPromptContext {
241//     fn messages(&self) -> Value;
242//     fn tools(&self) -> Option<Value>;
243// }
244
245#[derive(Debug, Clone, Default)]
246pub struct ContextMixins {
247    context_mixins: HashSet<PromptContextMixin>,
248}
249
250fn is_deepseek_v41(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
251    match model_type_lower.as_deref() {
252        Some("deepseek_v41") => true,
253        Some(_) => false,
254        None => [
255            "deepseek-v4.1",
256            "deepseek_v4.1",
257            "deepseek.v4.1",
258            "deepseekv4.1",
259        ]
260        .iter()
261        .any(|prefix| {
262            display_name_lower
263                .strip_prefix(prefix)
264                .is_some_and(|suffix| suffix.is_empty() || suffix.starts_with(['-', '_', '.']))
265        }),
266    }
267}
268
269/// Decides whether to activate the DeepSeek-V4 native formatter.
270///
271/// Primary signal: config.json `model_type`. DeepSeek-V4-Pro and V4-Flash both
272/// ship `"model_type": "deepseek_v4"`, set by the model author — this survives
273/// any `--served-model-name` rename.
274///
275/// Fallback: `display_name`, tight-matched against
276/// `^deepseek(?:[-_.])?v4(?:[-_.]|$)`. Only consulted when config.json is
277/// absent (tokenizer-only MDCs) or unreadable; a concrete config.json value
278/// that is *not* `deepseek_v4` is authoritative and suppresses the fallback.
279fn is_deepseek_v4(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
280    match model_type_lower.as_deref() {
281        Some("deepseek_v4") => true,
282        Some(_) => false, // config.json says something else — trust it
283        None => is_deepseek_v4_name(display_name_lower),
284    }
285}
286
287/// Decides whether to activate the DeepSeek-V3.2 (non-Exp) native formatter.
288/// Same config-primary / name-fallback rule as V4.
289fn is_deepseek_v3_2_non_exp(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
290    let name_match = display_name_lower.contains("deepseek")
291        && display_name_lower.contains("v3.2")
292        && !display_name_lower.contains("exp");
293    match model_type_lower.as_deref() {
294        // HF ships `deepseek_v32` (no underscore between 3 and 2); Dynamo's
295        // internal/tool-parser key is `deepseek_v3_2`. Accept both.
296        Some("deepseek_v3_2" | "deepseek_v32") => !display_name_lower.contains("exp"),
297        Some(_) => false,
298        None => name_match,
299    }
300}
301
302/// Tight, anchored match for DeepSeek-V4 display names. Equivalent to the
303/// regex `^deepseek(?:[-_.])?v4(?:[-_.]|$)` over an already-lowercased string.
304/// Written with string ops to avoid pulling in the `regex` crate.
305///
306/// Rejects composite names that previously short-circuited the V4 branch:
307/// - `deepseek-v3.2-v4-foo` (the `v3.2` variant is the real one)
308/// - `deepseek-v40` / `deepseek-v4pro` (no separator after `v4`)
309/// - `my-deepseek-v4` (prefix must be at the start)
310fn is_deepseek_v4_name(name_lower: &str) -> bool {
311    let Some(rest) = name_lower.strip_prefix("deepseek") else {
312        return false;
313    };
314    // Optional single separator between "deepseek" and "v4".
315    let rest = rest
316        .strip_prefix(|c: char| matches!(c, '-' | '_' | '.'))
317        .unwrap_or(rest);
318    let Some(after_v4) = rest.strip_prefix("v4") else {
319        return false;
320    };
321    // `v4` must end the name or be followed by a separator — anything else
322    // (e.g. `v40`, `v4pro`) is a different model family.
323    after_v4.is_empty() || after_v4.starts_with(['-', '_', '.'])
324}
325
326#[cfg(test)]
327mod detection_tests {
328    use super::{is_deepseek_v3_2_non_exp, is_deepseek_v4, is_deepseek_v4_name, is_kimi_k3};
329
330    #[test]
331    fn kimi_k3_detection_prefers_config_model_type() {
332        assert!(is_kimi_k3(&Some("kimi_k3".to_string()), "served-name"));
333        assert!(!is_kimi_k3(
334            &Some("kimi_k2".to_string()),
335            "moonshot-kimi-k3"
336        ));
337        assert!(is_kimi_k3(&None, "moonshot-kimi-k3"));
338        assert!(is_kimi_k3(&None, "kimi_k3-instruct"));
339        assert!(!is_kimi_k3(&None, "kimi-k2.5"));
340    }
341
342    #[test]
343    fn v4_name_matches_canonical_variants() {
344        for name in [
345            "deepseek-v4",
346            "deepseek_v4",
347            "deepseek.v4",
348            "deepseekv4",
349            "deepseek-v4-pro",
350            "deepseek-v4-flash",
351            "deepseek-v4-flash-2507",
352            "deepseek-v4.1",
353            "deepseek_v4_thinking",
354        ] {
355            assert!(is_deepseek_v4_name(name), "expected {name} to match V4");
356        }
357    }
358
359    #[test]
360    fn v4_name_rejects_non_v4() {
361        // Composite names that previously short-circuited to V4 before the
362        // V3.2 branch — now correctly rejected.
363        for name in [
364            "deepseek-v3.2-v4-foo",
365            "my-deepseek-v4",
366            "deepseek-v40",
367            "deepseek-v4pro",
368            "deepseekv40",
369            "deepseek-v3",
370            "deepseek-v3.2",
371            "deepseek-r1",
372            "qwen3-v4", // only deepseek-prefixed names qualify
373            "dsflash",
374            "",
375        ] {
376            assert!(
377                !is_deepseek_v4_name(name),
378                "expected {name} to NOT match V4",
379            );
380        }
381    }
382
383    #[test]
384    fn v4_detection_prefers_config_model_type() {
385        // config.json `model_type = "deepseek_v4"` wins regardless of what
386        // the operator calls the model via --served-model-name.
387        let v4 = Some("deepseek_v4".to_string());
388        for display in ["dsflash", "my-pet-model", "llama-3-8b", ""] {
389            assert!(
390                is_deepseek_v4(&v4, display),
391                "config says deepseek_v4, display {display:?} — expected V4",
392            );
393        }
394
395        // A concrete non-V4 config.json suppresses the display-name fallback.
396        // Even if the operator names the served model "deepseek-v4", a model
397        // with `model_type = "llama"` is NOT DeepSeek-V4.
398        let llama = Some("llama".to_string());
399        for display in ["deepseek-v4", "deepseek-v4-flash", "anything"] {
400            assert!(
401                !is_deepseek_v4(&llama, display),
402                "config says llama, display {display:?} — expected NOT V4",
403            );
404        }
405
406        // No config.json — fall back to display-name match.
407        assert!(is_deepseek_v4(&None, "deepseek-v4-flash"));
408        assert!(!is_deepseek_v4(&None, "dsflash"));
409
410        // A config.json with `"model_type": ""` is treated as "no signal" at
411        // the call site (normalized to None before is_deepseek_v4 is called),
412        // so the display-name fallback still runs — pin that contract.
413        let empty: Option<String> = None;
414        assert!(is_deepseek_v4(&empty, "deepseek-v4-flash"));
415        assert!(!is_deepseek_v4(&empty, "dsflash"));
416    }
417
418    #[test]
419    fn v3_2_detection_prefers_config_model_type() {
420        // config says deepseek_v3_2, any non-"exp" display name triggers.
421        let v3_2 = Some("deepseek_v3_2".to_string());
422        assert!(is_deepseek_v3_2_non_exp(&v3_2, "whatever"));
423        assert!(is_deepseek_v3_2_non_exp(&v3_2, "deepseek-v3.2"));
424        // V3.2-Exp is a separate model family; suppress even via config.
425        assert!(!is_deepseek_v3_2_non_exp(&v3_2, "deepseek-v3.2-exp"));
426
427        // The actual HF config.json spelling has no underscore between 3 and 2
428        // (`deepseek_v32`). It must trigger identically to the internal key.
429        let hf_real = Some("deepseek_v32".to_string());
430        assert!(is_deepseek_v3_2_non_exp(&hf_real, "whatever"));
431        assert!(is_deepseek_v3_2_non_exp(&hf_real, "deepseek-v3.2-nvfp4"));
432        assert!(!is_deepseek_v3_2_non_exp(&hf_real, "deepseek-v3.2-exp"));
433
434        // Other config types lose regardless of display name.
435        let other = Some("deepseek_v4".to_string());
436        assert!(!is_deepseek_v3_2_non_exp(&other, "deepseek-v3.2"));
437
438        // No config — fall back to the original display-name heuristic.
439        assert!(is_deepseek_v3_2_non_exp(&None, "deepseek-v3.2-pro"));
440        assert!(!is_deepseek_v3_2_non_exp(&None, "deepseek-v3.2-exp"));
441        assert!(!is_deepseek_v3_2_non_exp(&None, "deepseek-v4"));
442    }
443}