Skip to main content

dynamo_renderer/template/
tokcfg.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//based on: https://github.com/EricLBuehler/mistral.rs/blob/d970bb5feb863acf8e8ec90de97e18221fb959f1/mistralrs-core/src/pipeline/chat_template.rs
5
6use std::collections::HashMap;
7
8use chrono::{DateTime, Local};
9use either::Either;
10use std::borrow::Cow;
11
12use minijinja::value::{Kwargs, StringInput, from_args};
13use minijinja::{Error, ErrorKind, Output, State, Value, escape_formatter};
14use serde::{Deserialize, Serialize};
15
16use crate::python::{
17    PyFloats, PyJsonFormatter, is_python_space, python_float_repr, python_split_whitespace,
18    python_splitlines,
19};
20
21#[allow(dead_code)]
22#[derive(Debug, Deserialize)]
23pub struct AddedTokensDecoder {
24    __type: Option<String>,
25    pub content: String,
26    lstrip: bool,
27    normalized: bool,
28    rstrip: bool,
29    single_word: bool,
30    special: Option<bool>,
31}
32
33pub fn raise_exception(msg: String) -> Result<String, minijinja::Error> {
34    Err(minijinja::Error::new(ErrorKind::InvalidOperation, msg))
35}
36
37#[derive(Debug, Deserialize)]
38pub struct BeginEndUnkTok(
39    #[serde(with = "either::serde_untagged")] pub Either<String, AddedTokensDecoder>,
40);
41
42/// Support older tool use patterns where the tool use template was separate from the default/chat template.
43/// Modern patterns use a single template with a `tool_use` key, e.g.
44///
45/// ```jinja
46/// {%- if tools is not none and tool_choice is not none %}
47/// ```
48#[derive(Debug, Deserialize)]
49pub struct ChatTemplateValue(
50    #[serde(with = "either::serde_untagged")] pub Either<String, Vec<HashMap<String, String>>>,
51);
52
53/// If present, pad_token is usually a single value. Deepseek R1 and it's distill's use a map.
54#[allow(dead_code)]
55#[derive(Debug, Deserialize)]
56pub struct PadTokenValue(
57    #[serde(with = "either::serde_untagged")] pub Either<String, AddedTokensDecoder>,
58);
59
60#[allow(dead_code)]
61#[derive(Debug, Deserialize, Default)]
62/// Template for chat models including bos/eos/unk as well as the chat template.
63pub struct ChatTemplate {
64    pub bos_token: Option<BeginEndUnkTok>,
65    pub eos_token: Option<BeginEndUnkTok>,
66    pub unk_token: Option<BeginEndUnkTok>,
67
68    /// Jinja format [chat templating] for chat completion.
69    ///
70    /// [chat templating]: https://huggingface.co/docs/transformers/chat_templating
71    pub chat_template: Option<ChatTemplateValue>,
72
73    // future
74    add_bos_token: Option<bool>,
75    add_eos_token: Option<bool>,
76    added_tokens_decoder: Option<HashMap<String, AddedTokensDecoder>>,
77    additional_special_tokens: Option<Vec<String>>,
78    clean_up_tokenization_spaces: Option<bool>,
79    device_map: Option<String>,
80    legacy: Option<bool>,
81    model_max_length: Option<f64>,
82    pad_token: Option<PadTokenValue>,
83    sp_model_kwargs: Option<HashMap<String, String>>,
84    spaces_between_special_tokens: Option<bool>,
85    tokenizer_class: Option<String>,
86    truncation_size: Option<String>,
87    use_default_system_prompt: Option<bool>,
88
89    /// The `added_tokens` of the model's `tokenizer.json`; see
90    /// [`ChatTemplate::with_tokenizer_json`].
91    #[serde(skip)]
92    tokenizer_added_tokens: Vec<AddedTokensDecoder>,
93
94    /// See [`ChatTemplate::with_request_control_tokens_as_text`]; `None` is the
95    /// default, on.
96    #[serde(skip)]
97    pub(crate) request_control_tokens_as_text: Option<bool>,
98}
99
100impl ChatTemplate {
101    pub fn eos_tok(&self) -> Option<String> {
102        match self.eos_token.as_ref()?.0 {
103            Either::Left(ref lit) => Some(lit.clone()),
104            Either::Right(ref added) => Some(added.content.clone()),
105        }
106    }
107
108    pub fn bos_tok(&self) -> Option<String> {
109        match self.bos_token.as_ref()?.0 {
110            Either::Left(ref lit) => Some(lit.clone()),
111            Either::Right(ref added) => Some(added.content.clone()),
112        }
113    }
114
115    pub fn unk_tok(&self) -> Option<String> {
116        match self.unk_token.as_ref()?.0 {
117            Either::Left(ref lit) => Some(lit.clone()),
118            Either::Right(ref added) => Some(added.content.clone()),
119        }
120    }
121
122    /// Add the `added_tokens` of the model's `tokenizer.json` to
123    /// [`ChatTemplate::added_token_spellings`]. Some repos declare no
124    /// `added_tokens_decoder` in `tokenizer_config.json` (DeepSeek V3/R1,
125    /// GLM-5, Gemma 4), so their chat markers are listed only there.
126    pub fn with_tokenizer_json(mut self, tokenizer_json: &str) -> anyhow::Result<Self> {
127        #[derive(Deserialize)]
128        struct TokenizerJson {
129            #[serde(default)]
130            added_tokens: Vec<AddedTokensDecoder>,
131        }
132        self.tokenizer_added_tokens =
133            serde_json::from_str::<TokenizerJson>(tokenizer_json)?.added_tokens;
134        Ok(self)
135    }
136
137    /// Whether control-token spellings in request text render as ordinary
138    /// text, so that only the template's own markers encode as control tokens.
139    /// On by default; `false` turns it off, except under a template with
140    /// Harmony framing, which always renders this way.
141    ///
142    /// The spellings come back as ordinary segments of
143    /// [`OAIPromptFormatter::render_prompt`](crate::OAIPromptFormatter::render_prompt),
144    /// to encode with [`crate::RenderedPrompt::encode_segments`]; `render`
145    /// returns the same text without them. A model that lists its markers
146    /// only in `tokenizer.json` also needs [`ChatTemplate::with_tokenizer_json`].
147    /// In assistant history, a marker the template itself reads stays a
148    /// control token.
149    pub fn with_request_control_tokens_as_text(mut self, enabled: bool) -> Self {
150        self.request_control_tokens_as_text = Some(enabled);
151        self
152    }
153
154    /// Spellings the tokenizer turns into one added token, each with whether it
155    /// is `special`: every `added_tokens_decoder` entry, the `tokenizer.json`
156    /// `added_tokens` when given, the `additional_special_tokens`, and the
157    /// bos/eos/unk literals. Whitespace-only spellings are dropped; a spelling
158    /// listed twice is special if either entry says so. Sorted for a stable
159    /// result.
160    pub(crate) fn added_token_spellings(&self) -> Vec<(String, bool)> {
161        fn insert(spellings: &mut HashMap<String, bool>, spelling: Option<String>, special: bool) {
162            if let Some(spelling) = spelling
163                && !spelling.trim().is_empty()
164            {
165                *spellings.entry(spelling).or_insert(false) |= special;
166            }
167        }
168        let mut spellings = HashMap::new();
169        for token in self
170            .added_tokens_decoder
171            .iter()
172            .flat_map(HashMap::values)
173            .chain(&self.tokenizer_added_tokens)
174        {
175            insert(
176                &mut spellings,
177                Some(token.content.clone()),
178                token.special.unwrap_or(false),
179            );
180        }
181        for token in self.additional_special_tokens.iter().flatten() {
182            insert(&mut spellings, Some(token.clone()), true);
183        }
184        insert(&mut spellings, self.bos_tok(), true);
185        insert(&mut spellings, self.eos_tok(), true);
186        insert(&mut spellings, self.unk_tok(), true);
187        let mut spellings: Vec<_> = spellings.into_iter().collect();
188        spellings.sort();
189        spellings
190    }
191}
192
193#[allow(dead_code)]
194#[derive(Debug, Deserialize)]
195pub struct GenerationConfig {
196    #[serde(with = "either::serde_untagged")]
197    bos_token_id: Either<u32, Vec<u32>>,
198    #[serde(with = "either::serde_untagged")]
199    eos_token_id: Either<u32, Vec<u32>>,
200}
201
202/// Python `str` of a non-integer float (`1e-06`, `1e+16`, `nan`); minijinja never uses
203/// an exponent (`0.000001`, `10000000000000000.0`) and prints `NaN`. `None` for every
204/// other value.
205fn python_float_str(value: &Value) -> Option<String> {
206    if !value.is_number() || value.is_integer() {
207        return None;
208    }
209    f64::try_from(value.clone()).ok().map(python_float_repr)
210}
211
212/// Output formatter for `{{ x }}`. HF renders through Python, which prints a float
213/// with `str`; see [`python_float_str`]. Other values are unchanged. `~` concatenation
214/// is a VM op that can't be overridden, and filters that stringify values themselves
215/// (`join`, `replace`, ...) use minijinja's spelling, so `'x' ~ 1e-6` and
216/// `[1e-6] | join` still render `0.000001`.
217pub fn python_formatter(out: &mut Output, state: &State, value: &Value) -> Result<(), Error> {
218    match python_float_str(value) {
219        Some(text) => out.write_str(&text).map_err(Error::from),
220        None => escape_formatter(out, state, value),
221    }
222}
223
224/// The `string` filter with Python `str` floats, matching [`python_formatter`];
225/// other values go to the builtin.
226pub fn python_string(state: &State, value: &Value) -> Result<Value, Error> {
227    match python_float_str(value) {
228        Some(text) => Ok(Value::from(text)),
229        None => minijinja::filters::string(state, value),
230    }
231}
232
233/// minijinja-contrib's pycompat string methods, with Python's whitespace where
234/// Rust's differs: `strip`, `lstrip`, `rstrip` and `split()` also treat U+001C..U+001F
235/// as whitespace, `isspace` is false for `""`, and `splitlines` ends lines at every
236/// Python line break. HF renders templates through Python, so `m.content.strip()` must
237/// strip what Python strips.
238pub fn python_methods(
239    state: &State,
240    value: &Value,
241    method: &str,
242    args: &[Value],
243) -> Result<Value, Error> {
244    if let Some(s) = value.as_str() {
245        match method {
246            "strip" | "lstrip" | "rstrip" => {
247                let (chars,): (Option<&str>,) = from_args(args)?;
248                if chars.is_none() {
249                    let trimmed = match method {
250                        "strip" => s.trim_matches(is_python_space),
251                        "lstrip" => s.trim_start_matches(is_python_space),
252                        _ => s.trim_end_matches(is_python_space),
253                    };
254                    return Ok(StringInput::new(state, value)?.preserve_safety(trimmed.to_owned()));
255                }
256            }
257            "split" => {
258                let (sep, maxsplit): (Option<&str>, Option<i64>) = from_args(args)?;
259                if sep.is_none() {
260                    let maxsplit = maxsplit.and_then(|n| usize::try_from(n).ok());
261                    return Ok(python_split_whitespace(s, maxsplit)
262                        .into_iter()
263                        .map(|part| {
264                            if value.is_safe() {
265                                Value::from_safe_string(part.to_owned())
266                            } else {
267                                Value::from(part)
268                            }
269                        })
270                        .collect());
271                }
272            }
273            "splitlines" => {
274                let (keepends,): (Option<bool>,) = from_args(args)?;
275                return Ok(python_splitlines(s, keepends.unwrap_or(false))
276                    .into_iter()
277                    .map(|part| {
278                        if value.is_safe() {
279                            Value::from_safe_string(part.to_owned())
280                        } else {
281                            Value::from(part)
282                        }
283                    })
284                    .collect());
285            }
286            "isspace" => {
287                let () = from_args(args)?;
288                return Ok(Value::from(!s.is_empty() && s.chars().all(is_python_space)));
289            }
290            _ => {}
291        }
292    }
293    minijinja_contrib::pycompat::unknown_method_callback(state, value, method, args)
294}
295
296/// Jinja2's `trim` filter, `str.strip(chars)`, with Python's whitespace by default;
297/// see [`python_methods`].
298pub fn python_trim(value: StringInput<'_>, chars: Option<Cow<'_, str>>) -> Value {
299    match chars {
300        Some(chars) => minijinja::filters::trim(value, Some(chars)),
301        None => {
302            let trimmed = value.as_str().trim_matches(is_python_space).to_owned();
303            value.preserve_safety(trimmed)
304        }
305    }
306}
307
308/// Mirrors HF transformers' `tojson` filter, not stock Jinja2's. Transformers
309/// overrides Jinja's HTML-safe `tojson` with plain
310/// `json.dumps(x, ensure_ascii=False)` in its chat-template environment, and
311/// vLLM/SGLang render through that — so chat templates (and the models trained
312/// on their output) expect Python separators and **no** HTML escaping
313/// (`'`, `<`, `>`, `&` stay literal). serde_json leaves non-ASCII unescaped by
314/// default, matching `ensure_ascii=False`.
315pub fn tojson(value: Value, kwargs: Kwargs) -> Result<Value, Error> {
316    let value = crate::python::template_json(value).map_err(|err| {
317        Error::new(ErrorKind::BadSerialization, "cannot serialize to JSON").with_source(err)
318    })?;
319    let mut buf = Vec::new();
320    let result = if let Ok(indent) = kwargs.get("indent") {
321        // Python `json.dumps(indent=n)` separators are `(",", ": ")` with the
322        // item separator followed by newline + indent — PrettyFormatter matches.
323        let repeat = b" ".repeat(indent);
324        let formatter = PyFloats(serde_json::ser::PrettyFormatter::with_indent(&repeat));
325        let mut serializer = serde_json::Serializer::with_formatter(&mut buf, formatter);
326        value.serialize(&mut serializer)
327    } else {
328        let mut serializer = serde_json::Serializer::with_formatter(&mut buf, PyJsonFormatter);
329        value.serialize(&mut serializer)
330    };
331    result.map_err(|err| {
332        Error::new(ErrorKind::BadSerialization, "cannot serialize to JSON").with_source(err)
333    })?;
334    String::from_utf8(buf)
335        .map_err(|err| {
336            Error::new(ErrorKind::BadSerialization, "cannot serialize to JSON").with_source(err)
337        })
338        .map(Value::from_safe_string)
339}
340
341/// Parse a JSON string into a structured value.
342///
343/// HuggingFace/transformers chat-template environments expose this filter, and several
344/// published templates depend on it — e.g. Step-3.7-Flash's `tool_use` block applies it to
345/// a tool call's `arguments`, which arrive as a JSON *string*, to iterate the decoded
346/// object. Without it minijinja aborts the render with `unknown filter: fromjson`, which
347/// fails every multi-turn tool-call request.
348///
349/// Values that are not strings pass through untouched, so templates that apply the filter
350/// defensively to an already-decoded value keep rendering.
351pub fn fromjson(value: Value) -> Result<Value, Error> {
352    let Some(text) = value.as_str() else {
353        return Ok(value);
354    };
355    let parsed: serde_json::Value = serde_json::from_str(text).map_err(|err| {
356        Error::new(ErrorKind::InvalidOperation, "cannot parse JSON").with_source(err)
357    })?;
358    Ok(crate::python::template_value(&parsed))
359}
360
361pub fn strftime_now(format_str: &str) -> Result<Value, Error> {
362    let local: DateTime<Local> = Local::now();
363    Ok(Value::from_safe_string(
364        local.format(format_str).to_string(),
365    ))
366}
367
368#[cfg(test)]
369mod fromjson_tests {
370    use super::*;
371
372    #[test]
373    fn parses_json_object_string() {
374        let out = fromjson(Value::from(r#"{"location":"San Francisco","n":3}"#)).unwrap();
375        assert_eq!(
376            out.get_attr("location").unwrap().as_str(),
377            Some("San Francisco")
378        );
379        assert_eq!(out.get_attr("n").unwrap().to_string(), "3");
380    }
381
382    #[test]
383    fn parses_json_array_string() {
384        let out = fromjson(Value::from(r#"[1,2,3]"#)).unwrap();
385        assert_eq!(out.len(), Some(3));
386    }
387
388    #[test]
389    fn passes_through_non_string() {
390        // Already-decoded values must survive a defensive `| fromjson`.
391        let already = crate::python::template_value(&serde_json::json!({"a": 1}));
392        let out = fromjson(already).unwrap();
393        assert_eq!(out.get_attr("a").unwrap().to_string(), "1");
394    }
395
396    #[test]
397    fn errors_on_malformed_json() {
398        assert!(fromjson(Value::from("{not json")).is_err());
399    }
400
401    /// Regression: renders the shape of Step-3.7-Flash's `tool_use` block, where a tool
402    /// call's `arguments` arrive as a JSON string. Before the filter existed this failed
403    /// with `unknown filter: fromjson`, 500-ing every multi-turn tool-call request.
404    #[test]
405    fn renders_tool_use_block_with_json_string_arguments() {
406        let mut env = minijinja::Environment::new();
407        env.add_filter("fromjson", fromjson);
408        env.add_template(
409            "tool_use",
410            "{% for tc in tool_calls %}{% set a = tc.function.arguments | fromjson %}\
411CALL {{ tc.function.name }} loc={{ a.location }} unit={{ a.unit }}{% endfor %}",
412        )
413        .unwrap();
414        let rendered = env
415            .get_template("tool_use")
416            .unwrap()
417            .render(minijinja::context! { tool_calls => serde_json::json!([{
418                "function": {
419                    "name": "get_weather",
420                    "arguments": "{\"location\":\"San Francisco\",\"unit\":\"F\"}"
421                }
422            }])})
423            .expect("tool_use template must render once `fromjson` is registered");
424        assert_eq!(rendered, "CALL get_weather loc=San Francisco unit=F");
425    }
426}