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