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    /// True if the `default` template natively references `reasoning_content`.
181    /// When true and rendering through `default`, skip injection — the template
182    /// handles it. Tracked separately for `default` and `tool_use` because HF
183    /// configs may register different sources for each: Gemma4's `tool_use`
184    /// template is adapted by `normalize_chat_template_source` to read
185    /// `reasoning_content`, while its `default` template is not. A single global
186    /// flag would wrongly suppress injection on the untouched `default` path and
187    /// silently drop prior assistant reasoning on no-tool renders.
188    default_template_handles_reasoning: bool,
189    /// True if the `tool_use` template natively references `reasoning_content`.
190    /// See `default_template_handles_reasoning` for rationale.
191    tool_use_template_handles_reasoning: bool,
192    /// True if the `default` template renders a string `reasoning_content` but
193    /// not the segment array sent with interleaved tool calls (MiniMax-M2 and
194    /// Qwen3 read it only when it `is string`). When true and rendering through
195    /// `default`, join the segments into the string the template expects.
196    default_template_requires_reasoning_string: bool,
197    /// See `default_template_requires_reasoning_string` for rationale.
198    tool_use_template_requires_reasoning_string: bool,
199    /// Per-family placeholder template for image content parts when flattening
200    /// mixed text+image content arrays into a single string (`preserve_arrays`
201    /// = false path). `{n}` in the template is substituted with the 1-based
202    /// image index. `None` when the model's chat template handles content
203    /// arrays natively (Qwen-VL family) or when we have no flatten strategy
204    /// for it (no MM-aware routing benefit either way).
205    image_placeholder_template: Option<&'static str>,
206    /// True if the `default` template branches on `tool_call.arguments is string`
207    /// and renders string arguments verbatim (Qwen3, Hermes, etc.; templates that
208    /// only use the test to reject strings don't count). When true and rendering
209    /// through `default`, skip pre-parsing the JSON-string
210    /// `tool_calls[].function.arguments` into an object — the template wants the
211    /// raw string verbatim. Pre-parsing forces the `tojson`-with-object branch and
212    /// re-emits with minijinja's compact separators, which breaks append-only
213    /// prefix matching across multi-step tool-use turns. Tracked separately for
214    /// `default` and `tool_use` because HF configs may register different sources
215    /// for each, and because `arguments is string` is tool_calls-specific — legacy
216    /// `function_call.arguments` lives outside that branch and is still
217    /// normalized unconditionally.
218    default_template_handles_tool_calls_arguments_string: bool,
219    /// True if the `tool_use` template branches on `tool_call.arguments is string`.
220    /// See `default_template_handles_tool_calls_arguments_string` for rationale.
221    tool_use_template_handles_tool_calls_arguments_string: bool,
222    /// Message-shape restrictions the `default` template enforces.
223    default_system_normalization: SystemNormalization,
224    /// Message-shape restrictions the `tool_use` template enforces.
225    /// Kept separate because dict-form HF configs may register templates with
226    /// different constraints.
227    tool_use_system_normalization: SystemNormalization,
228}
229
230// /// OpenAI Standard Prompt Formatter
231// pub trait StandardPromptFormatter {
232//     fn render(&self, context: &impl StandardPromptContext) -> Result<String>;
233// }
234
235// pub trait StandardPromptContext {
236//     fn messages(&self) -> Value;
237//     fn tools(&self) -> Option<Value>;
238// }
239
240#[derive(Debug, Clone, Default)]
241pub struct ContextMixins {
242    context_mixins: HashSet<PromptContextMixin>,
243}
244
245fn is_deepseek_v41(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
246    match model_type_lower.as_deref() {
247        Some("deepseek_v41") => true,
248        Some(_) => false,
249        None => [
250            "deepseek-v4.1",
251            "deepseek_v4.1",
252            "deepseek.v4.1",
253            "deepseekv4.1",
254        ]
255        .iter()
256        .any(|prefix| {
257            display_name_lower
258                .strip_prefix(prefix)
259                .is_some_and(|suffix| suffix.is_empty() || suffix.starts_with(['-', '_', '.']))
260        }),
261    }
262}
263
264/// Decides whether to activate the DeepSeek-V4 native formatter.
265///
266/// Primary signal: config.json `model_type`. DeepSeek-V4-Pro and V4-Flash both
267/// ship `"model_type": "deepseek_v4"`, set by the model author — this survives
268/// any `--served-model-name` rename.
269///
270/// Fallback: `display_name`, tight-matched against
271/// `^deepseek(?:[-_.])?v4(?:[-_.]|$)`. Only consulted when config.json is
272/// absent (tokenizer-only MDCs) or unreadable; a concrete config.json value
273/// that is *not* `deepseek_v4` is authoritative and suppresses the fallback.
274fn is_deepseek_v4(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
275    match model_type_lower.as_deref() {
276        Some("deepseek_v4") => true,
277        Some(_) => false, // config.json says something else — trust it
278        None => is_deepseek_v4_name(display_name_lower),
279    }
280}
281
282/// Decides whether to activate the DeepSeek-V3.2 (non-Exp) native formatter.
283/// Same config-primary / name-fallback rule as V4.
284fn is_deepseek_v3_2_non_exp(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
285    let name_match = display_name_lower.contains("deepseek")
286        && display_name_lower.contains("v3.2")
287        && !display_name_lower.contains("exp");
288    match model_type_lower.as_deref() {
289        // HF ships `deepseek_v32` (no underscore between 3 and 2); Dynamo's
290        // internal/tool-parser key is `deepseek_v3_2`. Accept both.
291        Some("deepseek_v3_2" | "deepseek_v32") => !display_name_lower.contains("exp"),
292        Some(_) => false,
293        None => name_match,
294    }
295}
296
297/// Tight, anchored match for DeepSeek-V4 display names. Equivalent to the
298/// regex `^deepseek(?:[-_.])?v4(?:[-_.]|$)` over an already-lowercased string.
299/// Written with string ops to avoid pulling in the `regex` crate.
300///
301/// Rejects composite names that previously short-circuited the V4 branch:
302/// - `deepseek-v3.2-v4-foo` (the `v3.2` variant is the real one)
303/// - `deepseek-v40` / `deepseek-v4pro` (no separator after `v4`)
304/// - `my-deepseek-v4` (prefix must be at the start)
305fn is_deepseek_v4_name(name_lower: &str) -> bool {
306    let Some(rest) = name_lower.strip_prefix("deepseek") else {
307        return false;
308    };
309    // Optional single separator between "deepseek" and "v4".
310    let rest = rest
311        .strip_prefix(|c: char| matches!(c, '-' | '_' | '.'))
312        .unwrap_or(rest);
313    let Some(after_v4) = rest.strip_prefix("v4") else {
314        return false;
315    };
316    // `v4` must end the name or be followed by a separator — anything else
317    // (e.g. `v40`, `v4pro`) is a different model family.
318    after_v4.is_empty() || after_v4.starts_with(['-', '_', '.'])
319}
320
321#[cfg(test)]
322mod detection_tests {
323    use super::{is_deepseek_v3_2_non_exp, is_deepseek_v4, is_deepseek_v4_name, is_kimi_k3};
324
325    #[test]
326    fn kimi_k3_detection_prefers_config_model_type() {
327        assert!(is_kimi_k3(&Some("kimi_k3".to_string()), "served-name"));
328        assert!(!is_kimi_k3(
329            &Some("kimi_k2".to_string()),
330            "moonshot-kimi-k3"
331        ));
332        assert!(is_kimi_k3(&None, "moonshot-kimi-k3"));
333        assert!(is_kimi_k3(&None, "kimi_k3-instruct"));
334        assert!(!is_kimi_k3(&None, "kimi-k2.5"));
335    }
336
337    #[test]
338    fn v4_name_matches_canonical_variants() {
339        for name in [
340            "deepseek-v4",
341            "deepseek_v4",
342            "deepseek.v4",
343            "deepseekv4",
344            "deepseek-v4-pro",
345            "deepseek-v4-flash",
346            "deepseek-v4-flash-2507",
347            "deepseek-v4.1",
348            "deepseek_v4_thinking",
349        ] {
350            assert!(is_deepseek_v4_name(name), "expected {name} to match V4");
351        }
352    }
353
354    #[test]
355    fn v4_name_rejects_non_v4() {
356        // Composite names that previously short-circuited to V4 before the
357        // V3.2 branch — now correctly rejected.
358        for name in [
359            "deepseek-v3.2-v4-foo",
360            "my-deepseek-v4",
361            "deepseek-v40",
362            "deepseek-v4pro",
363            "deepseekv40",
364            "deepseek-v3",
365            "deepseek-v3.2",
366            "deepseek-r1",
367            "qwen3-v4", // only deepseek-prefixed names qualify
368            "dsflash",
369            "",
370        ] {
371            assert!(
372                !is_deepseek_v4_name(name),
373                "expected {name} to NOT match V4",
374            );
375        }
376    }
377
378    #[test]
379    fn v4_detection_prefers_config_model_type() {
380        // config.json `model_type = "deepseek_v4"` wins regardless of what
381        // the operator calls the model via --served-model-name.
382        let v4 = Some("deepseek_v4".to_string());
383        for display in ["dsflash", "my-pet-model", "llama-3-8b", ""] {
384            assert!(
385                is_deepseek_v4(&v4, display),
386                "config says deepseek_v4, display {display:?} — expected V4",
387            );
388        }
389
390        // A concrete non-V4 config.json suppresses the display-name fallback.
391        // Even if the operator names the served model "deepseek-v4", a model
392        // with `model_type = "llama"` is NOT DeepSeek-V4.
393        let llama = Some("llama".to_string());
394        for display in ["deepseek-v4", "deepseek-v4-flash", "anything"] {
395            assert!(
396                !is_deepseek_v4(&llama, display),
397                "config says llama, display {display:?} — expected NOT V4",
398            );
399        }
400
401        // No config.json — fall back to display-name match.
402        assert!(is_deepseek_v4(&None, "deepseek-v4-flash"));
403        assert!(!is_deepseek_v4(&None, "dsflash"));
404
405        // A config.json with `"model_type": ""` is treated as "no signal" at
406        // the call site (normalized to None before is_deepseek_v4 is called),
407        // so the display-name fallback still runs — pin that contract.
408        let empty: Option<String> = None;
409        assert!(is_deepseek_v4(&empty, "deepseek-v4-flash"));
410        assert!(!is_deepseek_v4(&empty, "dsflash"));
411    }
412
413    #[test]
414    fn v3_2_detection_prefers_config_model_type() {
415        // config says deepseek_v3_2, any non-"exp" display name triggers.
416        let v3_2 = Some("deepseek_v3_2".to_string());
417        assert!(is_deepseek_v3_2_non_exp(&v3_2, "whatever"));
418        assert!(is_deepseek_v3_2_non_exp(&v3_2, "deepseek-v3.2"));
419        // V3.2-Exp is a separate model family; suppress even via config.
420        assert!(!is_deepseek_v3_2_non_exp(&v3_2, "deepseek-v3.2-exp"));
421
422        // The actual HF config.json spelling has no underscore between 3 and 2
423        // (`deepseek_v32`). It must trigger identically to the internal key.
424        let hf_real = Some("deepseek_v32".to_string());
425        assert!(is_deepseek_v3_2_non_exp(&hf_real, "whatever"));
426        assert!(is_deepseek_v3_2_non_exp(&hf_real, "deepseek-v3.2-nvfp4"));
427        assert!(!is_deepseek_v3_2_non_exp(&hf_real, "deepseek-v3.2-exp"));
428
429        // Other config types lose regardless of display name.
430        let other = Some("deepseek_v4".to_string());
431        assert!(!is_deepseek_v3_2_non_exp(&other, "deepseek-v3.2"));
432
433        // No config — fall back to the original display-name heuristic.
434        assert!(is_deepseek_v3_2_non_exp(&None, "deepseek-v3.2-pro"));
435        assert!(!is_deepseek_v3_2_non_exp(&None, "deepseek-v3.2-exp"));
436        assert!(!is_deepseek_v3_2_non_exp(&None, "deepseek-v4"));
437    }
438}