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 mixins: Arc<ContextMixins>,
246 supports_add_generation_prompt: bool,
247 /// How message content is shaped for the template. `Auto` uses
248 /// `requires_content_arrays`, per-role text-array capabilities, and
249 /// `image_placeholder_template`.
250 content_format: ChatTemplateContentFormat,
251 requires_content_arrays: bool,
252 /// Roles whose text parts the selected template renders without printing
253 /// their containers. Keep these arrays so the template owns separators.
254 default_native_text_array_roles: Vec<&'static str>,
255 tool_use_native_text_array_roles: Vec<&'static str>,
256 /// When true, strip tool definitions from the chat template when tool_choice is "none".
257 /// This prevents models from generating raw XML tool calls in the content field.
258 exclude_tools_when_tool_choice_none: bool,
259 /// Cached per selected template variant; native namespace rendering was
260 /// introduced by the template's `deferred_render_mode` argument.
261 /// A capable default must not opt an older tool-use variant into native tools.
262 default_template_handles_native_tools: bool,
263 tool_use_template_handles_native_tools: bool,
264 /// True if the `default` template natively references `reasoning_content`.
265 /// When true and rendering through `default`, skip injection — the template
266 /// handles it. Tracked separately for `default` and `tool_use` because HF
267 /// configs may register different sources for each: Gemma4's `tool_use`
268 /// template is adapted by `normalize_chat_template_source` to read
269 /// `reasoning_content`, while its `default` template is not. A single global
270 /// flag would wrongly suppress injection on the untouched `default` path and
271 /// silently drop prior assistant reasoning on no-tool renders.
272 default_template_handles_reasoning: bool,
273 /// True if the `tool_use` template natively references `reasoning_content`.
274 /// See `default_template_handles_reasoning` for rationale.
275 tool_use_template_handles_reasoning: bool,
276 /// True if the `default` template renders a string `reasoning_content` but
277 /// not the segment array sent with interleaved tool calls (MiniMax-M2 and
278 /// Qwen3 read it only when it `is string`). When true and rendering through
279 /// `default`, join the segments into the string the template expects.
280 default_template_requires_reasoning_string: bool,
281 /// See `default_template_requires_reasoning_string` for rationale.
282 tool_use_template_requires_reasoning_string: bool,
283 /// Per-family placeholder template for image content parts when flattening
284 /// mixed text+image content arrays into a single string (`preserve_arrays`
285 /// = false path). `{n}` in the template is substituted with the 1-based
286 /// image index. `None` when the model's chat template handles content
287 /// arrays natively (Qwen-VL family) or when we have no flatten strategy
288 /// for it (no MM-aware routing benefit either way).
289 image_placeholder_template: Option<&'static str>,
290 /// True if the `default` template branches on `tool_call.arguments is string`
291 /// and renders string arguments verbatim (Qwen3, Hermes, etc.; templates that
292 /// only use the test to reject strings don't count). When true and rendering
293 /// through `default`, skip pre-parsing the JSON-string
294 /// `tool_calls[].function.arguments` into an object — the template wants the
295 /// raw string verbatim. Pre-parsing forces the `tojson`-with-object branch and
296 /// re-emits with minijinja's compact separators, which breaks append-only
297 /// prefix matching across multi-step tool-use turns. Tracked separately for
298 /// `default` and `tool_use` because HF configs may register different sources
299 /// for each, and because `arguments is string` is tool_calls-specific — legacy
300 /// `function_call.arguments` lives outside that branch and is still
301 /// normalized unconditionally.
302 default_template_handles_tool_calls_arguments_string: bool,
303 /// True if the `tool_use` template branches on `tool_call.arguments is string`.
304 /// See `default_template_handles_tool_calls_arguments_string` for rationale.
305 tool_use_template_handles_tool_calls_arguments_string: bool,
306 /// Message-shape restrictions the `default` template enforces.
307 default_system_normalization: SystemNormalization,
308 /// Message-shape restrictions the `tool_use` template enforces.
309 /// Kept separate because dict-form HF configs may register templates with
310 /// different constraints.
311 tool_use_system_normalization: SystemNormalization,
312}
313
314// /// OpenAI Standard Prompt Formatter
315// pub trait StandardPromptFormatter {
316// fn render(&self, context: &impl StandardPromptContext) -> Result<String>;
317// }
318
319// pub trait StandardPromptContext {
320// fn messages(&self) -> Value;
321// fn tools(&self) -> Option<Value>;
322// }
323
324#[derive(Debug, Clone, Default)]
325pub struct ContextMixins {
326 context_mixins: HashSet<PromptContextMixin>,
327}
328
329fn is_deepseek_v41(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
330 match model_type_lower.as_deref() {
331 Some("deepseek_v41") => true,
332 Some(_) => false,
333 None => [
334 "deepseek-v4.1",
335 "deepseek_v4.1",
336 "deepseek.v4.1",
337 "deepseekv4.1",
338 ]
339 .iter()
340 .any(|prefix| {
341 display_name_lower
342 .strip_prefix(prefix)
343 .is_some_and(|suffix| suffix.is_empty() || suffix.starts_with(['-', '_', '.']))
344 }),
345 }
346}
347
348/// Decides whether to activate the DeepSeek-V4 native formatter.
349///
350/// Primary signal: config.json `model_type`. DeepSeek-V4-Pro and V4-Flash both
351/// ship `"model_type": "deepseek_v4"`, set by the model author — this survives
352/// any `--served-model-name` rename.
353///
354/// Fallback: `display_name`, tight-matched against
355/// `^deepseek(?:[-_.])?v4(?:[-_.]|$)`. Only consulted when config.json is
356/// absent (tokenizer-only MDCs) or unreadable; a concrete config.json value
357/// that is *not* `deepseek_v4` is authoritative and suppresses the fallback.
358fn is_deepseek_v4(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
359 match model_type_lower.as_deref() {
360 Some("deepseek_v4") => true,
361 Some(_) => false, // config.json says something else — trust it
362 None => is_deepseek_v4_name(display_name_lower),
363 }
364}
365
366/// Decides whether to activate the DeepSeek-V3.2 (non-Exp) native formatter.
367/// Same config-primary / name-fallback rule as V4.
368fn is_deepseek_v3_2_non_exp(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
369 let name_match = display_name_lower.contains("deepseek")
370 && display_name_lower.contains("v3.2")
371 && !display_name_lower.contains("exp");
372 match model_type_lower.as_deref() {
373 // HF ships `deepseek_v32` (no underscore between 3 and 2); Dynamo's
374 // internal/tool-parser key is `deepseek_v3_2`. Accept both.
375 Some("deepseek_v3_2" | "deepseek_v32") => !display_name_lower.contains("exp"),
376 Some(_) => false,
377 None => name_match,
378 }
379}
380
381/// Tight, anchored match for DeepSeek-V4 display names. Equivalent to the
382/// regex `^deepseek(?:[-_.])?v4(?:[-_.]|$)` over an already-lowercased string.
383/// Written with string ops to avoid pulling in the `regex` crate.
384///
385/// Rejects composite names that previously short-circuited the V4 branch:
386/// - `deepseek-v3.2-v4-foo` (the `v3.2` variant is the real one)
387/// - `deepseek-v40` / `deepseek-v4pro` (no separator after `v4`)
388/// - `my-deepseek-v4` (prefix must be at the start)
389fn is_deepseek_v4_name(name_lower: &str) -> bool {
390 let Some(rest) = name_lower.strip_prefix("deepseek") else {
391 return false;
392 };
393 // Optional single separator between "deepseek" and "v4".
394 let rest = rest
395 .strip_prefix(|c: char| matches!(c, '-' | '_' | '.'))
396 .unwrap_or(rest);
397 let Some(after_v4) = rest.strip_prefix("v4") else {
398 return false;
399 };
400 // `v4` must end the name or be followed by a separator — anything else
401 // (e.g. `v40`, `v4pro`) is a different model family.
402 after_v4.is_empty() || after_v4.starts_with(['-', '_', '.'])
403}
404
405#[cfg(test)]
406mod detection_tests {
407 use super::{is_deepseek_v3_2_non_exp, is_deepseek_v4, is_deepseek_v4_name, is_kimi_k3};
408
409 #[test]
410 fn kimi_k3_detection_prefers_config_model_type() {
411 for model_type in ["kimi_k3", "kimi_k31"] {
412 assert!(is_kimi_k3(&Some(model_type.to_string()), "served-name"));
413 assert!(
414 super::kimi_k3_formatter_for(&Some(model_type.to_string()), "served-name", false)
415 .is_some()
416 );
417 }
418 assert!(!is_kimi_k3(
419 &Some("kimi_k2".to_string()),
420 "moonshot-kimi-k3"
421 ));
422 assert!(is_kimi_k3(&None, "moonshot-kimi-k3"));
423 assert!(is_kimi_k3(&None, "kimi_k3-instruct"));
424 assert!(!is_kimi_k3(&None, "kimi-k2.5"));
425 }
426
427 #[test]
428 fn v4_name_matches_canonical_variants() {
429 for name in [
430 "deepseek-v4",
431 "deepseek_v4",
432 "deepseek.v4",
433 "deepseekv4",
434 "deepseek-v4-pro",
435 "deepseek-v4-flash",
436 "deepseek-v4-flash-2507",
437 "deepseek-v4.1",
438 "deepseek_v4_thinking",
439 ] {
440 assert!(is_deepseek_v4_name(name), "expected {name} to match V4");
441 }
442 }
443
444 #[test]
445 fn v4_name_rejects_non_v4() {
446 // Composite names that previously short-circuited to V4 before the
447 // V3.2 branch — now correctly rejected.
448 for name in [
449 "deepseek-v3.2-v4-foo",
450 "my-deepseek-v4",
451 "deepseek-v40",
452 "deepseek-v4pro",
453 "deepseekv40",
454 "deepseek-v3",
455 "deepseek-v3.2",
456 "deepseek-r1",
457 "qwen3-v4", // only deepseek-prefixed names qualify
458 "dsflash",
459 "",
460 ] {
461 assert!(
462 !is_deepseek_v4_name(name),
463 "expected {name} to NOT match V4",
464 );
465 }
466 }
467
468 #[test]
469 fn v4_detection_prefers_config_model_type() {
470 // config.json `model_type = "deepseek_v4"` wins regardless of what
471 // the operator calls the model via --served-model-name.
472 let v4 = Some("deepseek_v4".to_string());
473 for display in ["dsflash", "my-pet-model", "llama-3-8b", ""] {
474 assert!(
475 is_deepseek_v4(&v4, display),
476 "config says deepseek_v4, display {display:?} — expected V4",
477 );
478 }
479
480 // A concrete non-V4 config.json suppresses the display-name fallback.
481 // Even if the operator names the served model "deepseek-v4", a model
482 // with `model_type = "llama"` is NOT DeepSeek-V4.
483 let llama = Some("llama".to_string());
484 for display in ["deepseek-v4", "deepseek-v4-flash", "anything"] {
485 assert!(
486 !is_deepseek_v4(&llama, display),
487 "config says llama, display {display:?} — expected NOT V4",
488 );
489 }
490
491 // No config.json — fall back to display-name match.
492 assert!(is_deepseek_v4(&None, "deepseek-v4-flash"));
493 assert!(!is_deepseek_v4(&None, "dsflash"));
494
495 // A config.json with `"model_type": ""` is treated as "no signal" at
496 // the call site (normalized to None before is_deepseek_v4 is called),
497 // so the display-name fallback still runs — pin that contract.
498 let empty: Option<String> = None;
499 assert!(is_deepseek_v4(&empty, "deepseek-v4-flash"));
500 assert!(!is_deepseek_v4(&empty, "dsflash"));
501 }
502
503 #[test]
504 fn v3_2_detection_prefers_config_model_type() {
505 // config says deepseek_v3_2, any non-"exp" display name triggers.
506 let v3_2 = Some("deepseek_v3_2".to_string());
507 assert!(is_deepseek_v3_2_non_exp(&v3_2, "whatever"));
508 assert!(is_deepseek_v3_2_non_exp(&v3_2, "deepseek-v3.2"));
509 // V3.2-Exp is a separate model family; suppress even via config.
510 assert!(!is_deepseek_v3_2_non_exp(&v3_2, "deepseek-v3.2-exp"));
511
512 // The actual HF config.json spelling has no underscore between 3 and 2
513 // (`deepseek_v32`). It must trigger identically to the internal key.
514 let hf_real = Some("deepseek_v32".to_string());
515 assert!(is_deepseek_v3_2_non_exp(&hf_real, "whatever"));
516 assert!(is_deepseek_v3_2_non_exp(&hf_real, "deepseek-v3.2-nvfp4"));
517 assert!(!is_deepseek_v3_2_non_exp(&hf_real, "deepseek-v3.2-exp"));
518
519 // Other config types lose regardless of display name.
520 let other = Some("deepseek_v4".to_string());
521 assert!(!is_deepseek_v3_2_non_exp(&other, "deepseek-v3.2"));
522
523 // No config — fall back to the original display-name heuristic.
524 assert!(is_deepseek_v3_2_non_exp(&None, "deepseek-v3.2-pro"));
525 assert!(!is_deepseek_v3_2_non_exp(&None, "deepseek-v3.2-exp"));
526 assert!(!is_deepseek_v3_2_non_exp(&None, "deepseek-v4"));
527 }
528}