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