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
51impl PromptFormatter {
52 pub fn from_parts(
53 config: ChatTemplate,
54 context: ContextMixins,
55 exclude_tools_when_tool_choice_none: bool,
56 ) -> Result<PromptFormatter> {
57 let formatter = HfTokenizerConfigJsonFormatter::with_options(
58 config,
59 context,
60 exclude_tools_when_tool_choice_none,
61 )?;
62 Ok(Self::OAI(Arc::new(formatter)))
63 }
64}
65
66/// Chat Template Jinja Renderer
67///
68/// Manages a Jinja environment with registered templates for chat formatting.
69/// Handles two types of ChatTemplateValue templates:
70///
71/// 1. String template: Registered as the 'default' template
72/// 2. Map template: Contains 'tool_use' and/or 'default' templates
73/// - tool_use: Template for tool-based interactions
74/// - default: Template for standard chat interactions
75///
76/// If the map contains both keys, the `tool_use` template is registered as the `tool_use` template
77/// and the `default` template is registered as the `default` template.
78struct JinjaEnvironment {
79 env: Environment<'static>,
80}
81
82/// Formatter for HuggingFace tokenizer config JSON templates
83///
84/// Implements chat template rendering based on HuggingFace's tokenizer_config.json format.
85/// Supports:
86/// - Tool usage templates
87/// - Generation prompts
88/// - Context mixins for template customization
89#[derive(Debug)]
90struct HfTokenizerConfigJsonFormatter {
91 env: Environment<'static>,
92 config: ChatTemplate,
93 mixins: Arc<ContextMixins>,
94 supports_add_generation_prompt: bool,
95 requires_content_arrays: bool,
96 /// When true, strip tool definitions from the chat template when tool_choice is "none".
97 /// This prevents models from generating raw XML tool calls in the content field.
98 exclude_tools_when_tool_choice_none: bool,
99 /// True if the `default` template natively references `reasoning_content`.
100 /// When true and rendering through `default`, skip injection — the template
101 /// handles it. Tracked separately for `default` and `tool_use` because HF
102 /// configs may register different sources for each: Gemma4's `tool_use`
103 /// template is adapted by `normalize_chat_template_source` to read
104 /// `reasoning_content`, while its `default` template is not. A single global
105 /// flag would wrongly suppress injection on the untouched `default` path and
106 /// silently drop prior assistant reasoning on no-tool renders.
107 default_template_handles_reasoning: bool,
108 /// True if the `tool_use` template natively references `reasoning_content`.
109 /// See `default_template_handles_reasoning` for rationale.
110 tool_use_template_handles_reasoning: bool,
111 /// Per-family placeholder template for image content parts when flattening
112 /// mixed text+image content arrays into a single string (`preserve_arrays`
113 /// = false path). `{n}` in the template is substituted with the 1-based
114 /// image index. `None` when the model's chat template handles content
115 /// arrays natively (Qwen-VL family) or when we have no flatten strategy
116 /// for it (no MM-aware routing benefit either way).
117 image_placeholder_template: Option<&'static str>,
118 /// True if the `default` template branches on `tool_call.arguments is string`
119 /// (Qwen3, Hermes, etc.). When true and rendering through `default`, skip
120 /// pre-parsing the JSON-string `tool_calls[].function.arguments` into an
121 /// object — the template wants the raw string verbatim. Pre-parsing forces
122 /// the `tojson`-with-object branch and re-emits with minijinja's compact
123 /// separators, which breaks append-only prefix matching across multi-step
124 /// tool-use turns. Tracked separately for `default` and `tool_use` because
125 /// HF configs may register different sources for each, and because
126 /// `arguments is string` is tool_calls-specific — legacy
127 /// `function_call.arguments` lives outside that branch and is still
128 /// normalized unconditionally.
129 default_template_handles_tool_calls_arguments_string: bool,
130 /// True if the `tool_use` template branches on `tool_call.arguments is string`.
131 /// See `default_template_handles_tool_calls_arguments_string` for rationale.
132 tool_use_template_handles_tool_calls_arguments_string: bool,
133}
134
135// /// OpenAI Standard Prompt Formatter
136// pub trait StandardPromptFormatter {
137// fn render(&self, context: &impl StandardPromptContext) -> Result<String>;
138// }
139
140// pub trait StandardPromptContext {
141// fn messages(&self) -> Value;
142// fn tools(&self) -> Option<Value>;
143// }
144
145#[derive(Debug, Clone, Default)]
146pub struct ContextMixins {
147 context_mixins: HashSet<PromptContextMixin>,
148}
149
150/// Decides whether to activate the DeepSeek-V4 native formatter.
151///
152/// Primary signal: config.json `model_type`. DeepSeek-V4-Pro and V4-Flash both
153/// ship `"model_type": "deepseek_v4"`, set by the model author — this survives
154/// any `--served-model-name` rename.
155///
156/// Fallback: `display_name`, tight-matched against
157/// `^deepseek(?:[-_.])?v4(?:[-_.]|$)`. Only consulted when config.json is
158/// absent (tokenizer-only MDCs) or unreadable; a concrete config.json value
159/// that is *not* `deepseek_v4` is authoritative and suppresses the fallback.
160fn is_deepseek_v4(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
161 match model_type_lower.as_deref() {
162 Some("deepseek_v4") => true,
163 Some(_) => false, // config.json says something else — trust it
164 None => is_deepseek_v4_name(display_name_lower),
165 }
166}
167
168/// Decides whether to activate the DeepSeek-V3.2 (non-Exp) native formatter.
169/// Same config-primary / name-fallback rule as V4.
170fn is_deepseek_v3_2_non_exp(model_type_lower: &Option<String>, display_name_lower: &str) -> bool {
171 let name_match = display_name_lower.contains("deepseek")
172 && display_name_lower.contains("v3.2")
173 && !display_name_lower.contains("exp");
174 match model_type_lower.as_deref() {
175 // HF ships `deepseek_v32` (no underscore between 3 and 2); Dynamo's
176 // internal/tool-parser key is `deepseek_v3_2`. Accept both.
177 Some("deepseek_v3_2" | "deepseek_v32") => !display_name_lower.contains("exp"),
178 Some(_) => false,
179 None => name_match,
180 }
181}
182
183/// Tight, anchored match for DeepSeek-V4 display names. Equivalent to the
184/// regex `^deepseek(?:[-_.])?v4(?:[-_.]|$)` over an already-lowercased string.
185/// Written with string ops to avoid pulling in the `regex` crate.
186///
187/// Rejects composite names that previously short-circuited the V4 branch:
188/// - `deepseek-v3.2-v4-foo` (the `v3.2` variant is the real one)
189/// - `deepseek-v40` / `deepseek-v4pro` (no separator after `v4`)
190/// - `my-deepseek-v4` (prefix must be at the start)
191fn is_deepseek_v4_name(name_lower: &str) -> bool {
192 let Some(rest) = name_lower.strip_prefix("deepseek") else {
193 return false;
194 };
195 // Optional single separator between "deepseek" and "v4".
196 let rest = rest
197 .strip_prefix(|c: char| matches!(c, '-' | '_' | '.'))
198 .unwrap_or(rest);
199 let Some(after_v4) = rest.strip_prefix("v4") else {
200 return false;
201 };
202 // `v4` must end the name or be followed by a separator — anything else
203 // (e.g. `v40`, `v4pro`) is a different model family.
204 after_v4.is_empty() || after_v4.starts_with(['-', '_', '.'])
205}
206
207#[cfg(test)]
208mod detection_tests {
209 use super::{is_deepseek_v3_2_non_exp, is_deepseek_v4, is_deepseek_v4_name};
210
211 #[test]
212 fn v4_name_matches_canonical_variants() {
213 for name in [
214 "deepseek-v4",
215 "deepseek_v4",
216 "deepseek.v4",
217 "deepseekv4",
218 "deepseek-v4-pro",
219 "deepseek-v4-flash",
220 "deepseek-v4-flash-2507",
221 "deepseek-v4.1",
222 "deepseek_v4_thinking",
223 ] {
224 assert!(is_deepseek_v4_name(name), "expected {name} to match V4");
225 }
226 }
227
228 #[test]
229 fn v4_name_rejects_non_v4() {
230 // Composite names that previously short-circuited to V4 before the
231 // V3.2 branch — now correctly rejected.
232 for name in [
233 "deepseek-v3.2-v4-foo",
234 "my-deepseek-v4",
235 "deepseek-v40",
236 "deepseek-v4pro",
237 "deepseekv40",
238 "deepseek-v3",
239 "deepseek-v3.2",
240 "deepseek-r1",
241 "qwen3-v4", // only deepseek-prefixed names qualify
242 "dsflash",
243 "",
244 ] {
245 assert!(
246 !is_deepseek_v4_name(name),
247 "expected {name} to NOT match V4",
248 );
249 }
250 }
251
252 #[test]
253 fn v4_detection_prefers_config_model_type() {
254 // config.json `model_type = "deepseek_v4"` wins regardless of what
255 // the operator calls the model via --served-model-name.
256 let v4 = Some("deepseek_v4".to_string());
257 for display in ["dsflash", "my-pet-model", "llama-3-8b", ""] {
258 assert!(
259 is_deepseek_v4(&v4, display),
260 "config says deepseek_v4, display {display:?} — expected V4",
261 );
262 }
263
264 // A concrete non-V4 config.json suppresses the display-name fallback.
265 // Even if the operator names the served model "deepseek-v4", a model
266 // with `model_type = "llama"` is NOT DeepSeek-V4.
267 let llama = Some("llama".to_string());
268 for display in ["deepseek-v4", "deepseek-v4-flash", "anything"] {
269 assert!(
270 !is_deepseek_v4(&llama, display),
271 "config says llama, display {display:?} — expected NOT V4",
272 );
273 }
274
275 // No config.json — fall back to display-name match.
276 assert!(is_deepseek_v4(&None, "deepseek-v4-flash"));
277 assert!(!is_deepseek_v4(&None, "dsflash"));
278
279 // A config.json with `"model_type": ""` is treated as "no signal" at
280 // the call site (normalized to None before is_deepseek_v4 is called),
281 // so the display-name fallback still runs — pin that contract.
282 let empty: Option<String> = None;
283 assert!(is_deepseek_v4(&empty, "deepseek-v4-flash"));
284 assert!(!is_deepseek_v4(&empty, "dsflash"));
285 }
286
287 #[test]
288 fn v3_2_detection_prefers_config_model_type() {
289 // config says deepseek_v3_2, any non-"exp" display name triggers.
290 let v3_2 = Some("deepseek_v3_2".to_string());
291 assert!(is_deepseek_v3_2_non_exp(&v3_2, "whatever"));
292 assert!(is_deepseek_v3_2_non_exp(&v3_2, "deepseek-v3.2"));
293 // V3.2-Exp is a separate model family; suppress even via config.
294 assert!(!is_deepseek_v3_2_non_exp(&v3_2, "deepseek-v3.2-exp"));
295
296 // The actual HF config.json spelling has no underscore between 3 and 2
297 // (`deepseek_v32`). It must trigger identically to the internal key.
298 let hf_real = Some("deepseek_v32".to_string());
299 assert!(is_deepseek_v3_2_non_exp(&hf_real, "whatever"));
300 assert!(is_deepseek_v3_2_non_exp(&hf_real, "deepseek-v3.2-nvfp4"));
301 assert!(!is_deepseek_v3_2_non_exp(&hf_real, "deepseek-v3.2-exp"));
302
303 // Other config types lose regardless of display name.
304 let other = Some("deepseek_v4".to_string());
305 assert!(!is_deepseek_v3_2_non_exp(&other, "deepseek-v3.2"));
306
307 // No config — fall back to the original display-name heuristic.
308 assert!(is_deepseek_v3_2_non_exp(&None, "deepseek-v3.2-pro"));
309 assert!(!is_deepseek_v3_2_non_exp(&None, "deepseek-v3.2-exp"));
310 assert!(!is_deepseek_v3_2_non_exp(&None, "deepseek-v4"));
311 }
312}