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