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