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
113/// How message `content` is shaped before the HF chat template sees it, with
114/// the semantics of vLLM's `--chat-template-content-format`.
115#[derive(Debug, Clone, Default, PartialEq, Eq)]
116pub enum ChatTemplateContentFormat {
117    /// Probe the template at load and pick a shape for it (Dynamo's default).
118    #[default]
119    Auto,
120    /// Flatten every message's content to one string, as vLLM's `string`
121    /// format does with its default `interleave_mm_strings=False`: one
122    /// placeholder per media item first, then the text parts, all joined
123    /// with `\n`.
124    String(MediaPlaceholders),
125    /// Pass every message's content as a list of parts, as vLLM's `openai`
126    /// format does.
127    OpenAi,
128}
129
130/// The model's placeholder for each modality, as vLLM's `get_placeholder_str`
131/// returns it. `{n}` is replaced with the item's 1-based index among that
132/// modality's items in the whole conversation. An empty placeholder adds none.
133#[derive(Debug, Clone, Default, PartialEq, Eq)]
134pub struct MediaPlaceholders {
135    pub image: String,
136    pub video: String,
137    pub audio: String,
138}
139
140impl PromptFormatter {
141    pub fn from_parts(
142        config: ChatTemplate,
143        context: ContextMixins,
144        exclude_tools_when_tool_choice_none: bool,
145    ) -> Result<PromptFormatter> {
146        Self::from_parts_with_content_format(
147            config,
148            context,
149            exclude_tools_when_tool_choice_none,
150            ChatTemplateContentFormat::Auto,
151        )
152    }
153
154    /// [`PromptFormatter::from_parts`] with an explicit content format.
155    pub fn from_parts_with_content_format(
156        config: ChatTemplate,
157        context: ContextMixins,
158        exclude_tools_when_tool_choice_none: bool,
159        content_format: ChatTemplateContentFormat,
160    ) -> Result<PromptFormatter> {
161        let mut formatter = HfTokenizerConfigJsonFormatter::with_options(
162            config,
163            context,
164            exclude_tools_when_tool_choice_none,
165        )?;
166        // Like vLLM, warn when the forced format disagrees with the template.
167        if matches!(content_format, ChatTemplateContentFormat::String(_))
168            && formatter.requires_content_arrays
169        {
170            tracing::warn!(
171                "chat template content format is `string`, but the template renders text only \
172                 from content arrays, so message text may be dropped"
173            );
174        }
175        formatter.content_format = content_format;
176        Ok(Self::OAI(Arc::new(formatter)))
177    }
178}
179
180/// Chat Template Jinja Renderer
181///
182/// Manages a Jinja environment with registered templates for chat formatting.
183/// Handles two types of ChatTemplateValue templates:
184///
185/// 1. String template: Registered as the 'default' template
186/// 2. Map template: Contains 'tool_use' and/or 'default' templates
187///    - tool_use: Template for tool-based interactions
188///    - default: Template for standard chat interactions
189///
190///   If the map contains both keys, the `tool_use` template is registered as the `tool_use` template
191///   and the `default` template is registered as the `default` template.
192struct JinjaEnvironment {
193    env: Environment<'static>,
194}
195
196/// Which message-shape restrictions one chat template enforces, probed once at
197/// load. Each rewrite in `normalize_system_messages` is gated on its own flag:
198/// the restrictions are independent, so a template that rejects a non-leading
199/// `system` (Qwen3.5) but accepts consecutive `user` turns keeps those turns
200/// separate instead of being reshaped for a rule it does not have.
201#[derive(Debug, Default, Clone, Copy)]
202struct SystemNormalization {
203    /// Template raises on a `system` turn that is not first.
204    demote_nonleading_system: bool,
205    /// Template raises on two adjacent `user` turns.
206    coalesce_consecutive_users: bool,
207}
208
209impl SystemNormalization {
210    fn is_required(&self) -> bool {
211        self.demote_nonleading_system || self.coalesce_consecutive_users
212    }
213}
214
215/// Formatter for HuggingFace tokenizer config JSON templates
216///
217/// Implements chat template rendering based on HuggingFace's tokenizer_config.json format.
218/// Supports:
219/// - Tool usage templates
220/// - Generation prompts
221/// - Context mixins for template customization
222#[derive(Debug)]
223struct HfTokenizerConfigJsonFormatter {
224    env: Environment<'static>,
225    config: ChatTemplate,
226    mixins: Arc<ContextMixins>,
227    supports_add_generation_prompt: bool,
228    /// How message content is shaped for the template. `Auto` uses
229    /// `requires_content_arrays` and `image_placeholder_template`.
230    content_format: ChatTemplateContentFormat,
231    requires_content_arrays: bool,
232    /// When true, strip tool definitions from the chat template when tool_choice is "none".
233    /// This prevents models from generating raw XML tool calls in the content field.
234    exclude_tools_when_tool_choice_none: bool,
235    /// Cached per selected template variant; native namespace rendering was
236    /// introduced by the template's `deferred_render_mode` argument.
237    /// A capable default must not opt an older tool-use variant into native tools.
238    default_template_handles_native_tools: bool,
239    tool_use_template_handles_native_tools: bool,
240    /// True if the `default` template natively references `reasoning_content`.
241    /// When true and rendering through `default`, skip injection — the template
242    /// handles it. Tracked separately for `default` and `tool_use` because HF
243    /// configs may register different sources for each: Gemma4's `tool_use`
244    /// template is adapted by `normalize_chat_template_source` to read
245    /// `reasoning_content`, while its `default` template is not. A single global
246    /// flag would wrongly suppress injection on the untouched `default` path and
247    /// silently drop prior assistant reasoning on no-tool renders.
248    default_template_handles_reasoning: bool,
249    /// True if the `tool_use` template natively references `reasoning_content`.
250    /// See `default_template_handles_reasoning` for rationale.
251    tool_use_template_handles_reasoning: bool,
252    /// True if the `default` template renders a string `reasoning_content` but
253    /// not the segment array sent with interleaved tool calls (MiniMax-M2 and
254    /// Qwen3 read it only when it `is string`). When true and rendering through
255    /// `default`, join the segments into the string the template expects.
256    default_template_requires_reasoning_string: bool,
257    /// See `default_template_requires_reasoning_string` for rationale.
258    tool_use_template_requires_reasoning_string: bool,
259    /// Per-family placeholder template for image content parts when flattening
260    /// mixed text+image content arrays into a single string (`preserve_arrays`
261    /// = false path). `{n}` in the template is substituted with the 1-based
262    /// image index. `None` when the model's chat template handles content
263    /// arrays natively (Qwen-VL family) or when we have no flatten strategy
264    /// for it (no MM-aware routing benefit either way).
265    image_placeholder_template: Option<&'static str>,
266    /// True if the `default` template branches on `tool_call.arguments is string`
267    /// and renders string arguments verbatim (Qwen3, Hermes, etc.; templates that
268    /// only use the test to reject strings don't count). When true and rendering
269    /// through `default`, skip pre-parsing the JSON-string
270    /// `tool_calls[].function.arguments` into an object — the template wants the
271    /// raw string verbatim. Pre-parsing forces the `tojson`-with-object branch and
272    /// re-emits with minijinja's compact separators, which breaks append-only
273    /// prefix matching across multi-step tool-use turns. Tracked separately for
274    /// `default` and `tool_use` because HF configs may register different sources
275    /// for each, and because `arguments is string` is tool_calls-specific — legacy
276    /// `function_call.arguments` lives outside that branch and is still
277    /// normalized unconditionally.
278    default_template_handles_tool_calls_arguments_string: bool,
279    /// True if the `tool_use` template branches on `tool_call.arguments is string`.
280    /// See `default_template_handles_tool_calls_arguments_string` for rationale.
281    tool_use_template_handles_tool_calls_arguments_string: bool,
282    /// Message-shape restrictions the `default` template enforces.
283    default_system_normalization: SystemNormalization,
284    /// Message-shape restrictions the `tool_use` template enforces.
285    /// Kept separate because dict-form HF configs may register templates with
286    /// different constraints.
287    tool_use_system_normalization: SystemNormalization,
288}
289
290// /// OpenAI Standard Prompt Formatter
291// pub trait StandardPromptFormatter {
292//     fn render(&self, context: &impl StandardPromptContext) -> Result<String>;
293// }
294
295// pub trait StandardPromptContext {
296//     fn messages(&self) -> Value;
297//     fn tools(&self) -> Option<Value>;
298// }
299
300#[derive(Debug, Clone, Default)]
301pub struct ContextMixins {
302    context_mixins: HashSet<PromptContextMixin>,
303}
304
305fn is_deepseek_v41(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
306    match model_type_lower.as_deref() {
307        Some("deepseek_v41") => true,
308        Some(_) => false,
309        None => [
310            "deepseek-v4.1",
311            "deepseek_v4.1",
312            "deepseek.v4.1",
313            "deepseekv4.1",
314        ]
315        .iter()
316        .any(|prefix| {
317            display_name_lower
318                .strip_prefix(prefix)
319                .is_some_and(|suffix| suffix.is_empty() || suffix.starts_with(['-', '_', '.']))
320        }),
321    }
322}
323
324/// Decides whether to activate the DeepSeek-V4 native formatter.
325///
326/// Primary signal: config.json `model_type`. DeepSeek-V4-Pro and V4-Flash both
327/// ship `"model_type": "deepseek_v4"`, set by the model author — this survives
328/// any `--served-model-name` rename.
329///
330/// Fallback: `display_name`, tight-matched against
331/// `^deepseek(?:[-_.])?v4(?:[-_.]|$)`. Only consulted when config.json is
332/// absent (tokenizer-only MDCs) or unreadable; a concrete config.json value
333/// that is *not* `deepseek_v4` is authoritative and suppresses the fallback.
334fn is_deepseek_v4(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
335    match model_type_lower.as_deref() {
336        Some("deepseek_v4") => true,
337        Some(_) => false, // config.json says something else — trust it
338        None => is_deepseek_v4_name(display_name_lower),
339    }
340}
341
342/// Decides whether to activate the DeepSeek-V3.2 (non-Exp) native formatter.
343/// Same config-primary / name-fallback rule as V4.
344fn is_deepseek_v3_2_non_exp(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
345    let name_match = display_name_lower.contains("deepseek")
346        && display_name_lower.contains("v3.2")
347        && !display_name_lower.contains("exp");
348    match model_type_lower.as_deref() {
349        // HF ships `deepseek_v32` (no underscore between 3 and 2); Dynamo's
350        // internal/tool-parser key is `deepseek_v3_2`. Accept both.
351        Some("deepseek_v3_2" | "deepseek_v32") => !display_name_lower.contains("exp"),
352        Some(_) => false,
353        None => name_match,
354    }
355}
356
357/// Tight, anchored match for DeepSeek-V4 display names. Equivalent to the
358/// regex `^deepseek(?:[-_.])?v4(?:[-_.]|$)` over an already-lowercased string.
359/// Written with string ops to avoid pulling in the `regex` crate.
360///
361/// Rejects composite names that previously short-circuited the V4 branch:
362/// - `deepseek-v3.2-v4-foo` (the `v3.2` variant is the real one)
363/// - `deepseek-v40` / `deepseek-v4pro` (no separator after `v4`)
364/// - `my-deepseek-v4` (prefix must be at the start)
365fn is_deepseek_v4_name(name_lower: &str) -> bool {
366    let Some(rest) = name_lower.strip_prefix("deepseek") else {
367        return false;
368    };
369    // Optional single separator between "deepseek" and "v4".
370    let rest = rest
371        .strip_prefix(|c: char| matches!(c, '-' | '_' | '.'))
372        .unwrap_or(rest);
373    let Some(after_v4) = rest.strip_prefix("v4") else {
374        return false;
375    };
376    // `v4` must end the name or be followed by a separator — anything else
377    // (e.g. `v40`, `v4pro`) is a different model family.
378    after_v4.is_empty() || after_v4.starts_with(['-', '_', '.'])
379}
380
381#[cfg(test)]
382mod detection_tests {
383    use super::{is_deepseek_v3_2_non_exp, is_deepseek_v4, is_deepseek_v4_name, is_kimi_k3};
384
385    #[test]
386    fn kimi_k3_detection_prefers_config_model_type() {
387        assert!(is_kimi_k3(&Some("kimi_k3".to_string()), "served-name"));
388        assert!(!is_kimi_k3(
389            &Some("kimi_k2".to_string()),
390            "moonshot-kimi-k3"
391        ));
392        assert!(is_kimi_k3(&None, "moonshot-kimi-k3"));
393        assert!(is_kimi_k3(&None, "kimi_k3-instruct"));
394        assert!(!is_kimi_k3(&None, "kimi-k2.5"));
395    }
396
397    #[test]
398    fn v4_name_matches_canonical_variants() {
399        for name in [
400            "deepseek-v4",
401            "deepseek_v4",
402            "deepseek.v4",
403            "deepseekv4",
404            "deepseek-v4-pro",
405            "deepseek-v4-flash",
406            "deepseek-v4-flash-2507",
407            "deepseek-v4.1",
408            "deepseek_v4_thinking",
409        ] {
410            assert!(is_deepseek_v4_name(name), "expected {name} to match V4");
411        }
412    }
413
414    #[test]
415    fn v4_name_rejects_non_v4() {
416        // Composite names that previously short-circuited to V4 before the
417        // V3.2 branch — now correctly rejected.
418        for name in [
419            "deepseek-v3.2-v4-foo",
420            "my-deepseek-v4",
421            "deepseek-v40",
422            "deepseek-v4pro",
423            "deepseekv40",
424            "deepseek-v3",
425            "deepseek-v3.2",
426            "deepseek-r1",
427            "qwen3-v4", // only deepseek-prefixed names qualify
428            "dsflash",
429            "",
430        ] {
431            assert!(
432                !is_deepseek_v4_name(name),
433                "expected {name} to NOT match V4",
434            );
435        }
436    }
437
438    #[test]
439    fn v4_detection_prefers_config_model_type() {
440        // config.json `model_type = "deepseek_v4"` wins regardless of what
441        // the operator calls the model via --served-model-name.
442        let v4 = Some("deepseek_v4".to_string());
443        for display in ["dsflash", "my-pet-model", "llama-3-8b", ""] {
444            assert!(
445                is_deepseek_v4(&v4, display),
446                "config says deepseek_v4, display {display:?} — expected V4",
447            );
448        }
449
450        // A concrete non-V4 config.json suppresses the display-name fallback.
451        // Even if the operator names the served model "deepseek-v4", a model
452        // with `model_type = "llama"` is NOT DeepSeek-V4.
453        let llama = Some("llama".to_string());
454        for display in ["deepseek-v4", "deepseek-v4-flash", "anything"] {
455            assert!(
456                !is_deepseek_v4(&llama, display),
457                "config says llama, display {display:?} — expected NOT V4",
458            );
459        }
460
461        // No config.json — fall back to display-name match.
462        assert!(is_deepseek_v4(&None, "deepseek-v4-flash"));
463        assert!(!is_deepseek_v4(&None, "dsflash"));
464
465        // A config.json with `"model_type": ""` is treated as "no signal" at
466        // the call site (normalized to None before is_deepseek_v4 is called),
467        // so the display-name fallback still runs — pin that contract.
468        let empty: Option<String> = None;
469        assert!(is_deepseek_v4(&empty, "deepseek-v4-flash"));
470        assert!(!is_deepseek_v4(&empty, "dsflash"));
471    }
472
473    #[test]
474    fn v3_2_detection_prefers_config_model_type() {
475        // config says deepseek_v3_2, any non-"exp" display name triggers.
476        let v3_2 = Some("deepseek_v3_2".to_string());
477        assert!(is_deepseek_v3_2_non_exp(&v3_2, "whatever"));
478        assert!(is_deepseek_v3_2_non_exp(&v3_2, "deepseek-v3.2"));
479        // V3.2-Exp is a separate model family; suppress even via config.
480        assert!(!is_deepseek_v3_2_non_exp(&v3_2, "deepseek-v3.2-exp"));
481
482        // The actual HF config.json spelling has no underscore between 3 and 2
483        // (`deepseek_v32`). It must trigger identically to the internal key.
484        let hf_real = Some("deepseek_v32".to_string());
485        assert!(is_deepseek_v3_2_non_exp(&hf_real, "whatever"));
486        assert!(is_deepseek_v3_2_non_exp(&hf_real, "deepseek-v3.2-nvfp4"));
487        assert!(!is_deepseek_v3_2_non_exp(&hf_real, "deepseek-v3.2-exp"));
488
489        // Other config types lose regardless of display name.
490        let other = Some("deepseek_v4".to_string());
491        assert!(!is_deepseek_v3_2_non_exp(&other, "deepseek-v3.2"));
492
493        // No config — fall back to the original display-name heuristic.
494        assert!(is_deepseek_v3_2_non_exp(&None, "deepseek-v3.2-pro"));
495        assert!(!is_deepseek_v3_2_non_exp(&None, "deepseek-v3.2-exp"));
496        assert!(!is_deepseek_v3_2_non_exp(&None, "deepseek-v4"));
497    }
498}