Skip to main content

dynamo_renderer/
lib.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Prompt Formatting
5//!
6//! Standalone, runtime-free chat-template / prompt formatting for
7//! OpenAI-compatible inference frontends. Renders HuggingFace `chat_template`
8//! jinja2 (via `minijinja` + `minijinja-contrib` pycompat), handles tool
9//! usage formatting and generation-prompt handling.
10//!
11//! Consumers implement [`OAIChatLikeRequest`] for their request type (or use
12//! the ready-made impl for `dynamo-protocols`' OpenAI chat request) and render
13//! with a [`PromptFormatter`] built from a HuggingFace `tokenizer_config.json`
14//! ([`ChatTemplate`]).
15//!
16//! This crate is a *bridge* between OpenAI request types ([`dynamo_protocols`])
17//! and prompt rendering. Most formatters return text; segment-sensitive native
18//! formats can preserve tokenizer policy through [`RenderedPrompt`].
19
20// TODO:
21// 1. Query if `add_generation_prompt` is present in the prompt template
22// 2. Support for models with add_generation_prompt:
23//    - PALS (Prefix-Assisted Language Sampling)
24//    - Continuation - Detected on user turns, where we can return
25//      partial assistant responses without add_generation_prompt
26
27use anyhow::Result;
28use minijinja::value::Value;
29use std::collections::HashMap;
30use std::sync::Arc;
31
32/// Re-export of `dynamo-tokenizers` as a one-import convenience: consumers that
33/// want both tokenization and chat templating can reach the tokenizer types via
34/// `dynamo_renderer::dynamo_tokenizers::*` without adding a second dependency.
35pub use dynamo_tokenizers;
36
37pub mod deepseek;
38pub mod inkling;
39pub mod kimi_k3;
40mod template;
41
42pub use template::{
43    ChatTemplate, ChatTemplateValue, ContextMixins, deepseek_formatter_for, kimi_k3_formatter_for,
44    may_be_fix_tool_schema, native_formatter_for,
45};
46
47/// Selects which context-mixin behaviors a template renders with.
48///
49/// Carried on the model deployment card (`prompt_context`) and consumed by the
50/// chat-template renderer via [`ContextMixins`].
51#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
52#[serde(rename_all = "snake_case")]
53pub enum PromptContextMixin {
54    /// Support OAI Chat Messages and Tools
55    OaiChat,
56
57    /// Enables templates with `{{datetime}}` to be rendered with the current date and time.
58    Llama3DateTime,
59}
60
61/// Shared helper: extract a boolean thinking toggle from `chat_template_args`.
62///
63/// Reads the two equivalent keys (`thinking`, `enable_thinking` — vLLM's
64/// canonical kwarg) in order and returns the first bool value found, or `None`
65/// if neither key is present (or neither carries a bool). Used by the V4
66/// formatter's `resolve_thinking_mode` and by reasoning-parser gating in
67/// consumers so both paths agree on the signal interpretation.
68pub fn thinking_bool_from_args(args: Option<&HashMap<String, serde_json::Value>>) -> Option<bool> {
69    let args = args?;
70    for key in ["thinking", "enable_thinking"] {
71        if let Some(v) = args.get(key).and_then(|x| x.as_bool()) {
72            return Some(v);
73        }
74    }
75    None
76}
77
78#[derive(Debug)]
79pub enum TokenInput {
80    Single(Vec<u32>),
81    Batch(Vec<Vec<u32>>),
82}
83
84#[derive(Debug)]
85pub enum TextInput {
86    Single(String),
87    Batch(Vec<String>),
88}
89
90#[derive(Debug)]
91pub enum PromptInput {
92    Tokens(TokenInput),
93    Text(TextInput),
94}
95
96/// One owned prompt segment with an explicit special-token trust boundary.
97#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct RenderedSegment {
99    pub text: String,
100    pub allow_special: bool,
101}
102
103impl RenderedSegment {
104    pub fn new(text: impl Into<String>, allow_special: bool) -> Self {
105        Self {
106            text: text.into(),
107            allow_special,
108        }
109    }
110
111    pub fn as_encode_segment(&self) -> dynamo_tokenizers::EncodeSegment<'_> {
112        dynamo_tokenizers::EncodeSegment::new(&self.text, self.allow_special)
113    }
114}
115
116/// A rendered prompt plus its optional tokenization boundaries.
117///
118/// The prompt owns its segment text while `dynamo-tokenizers` borrows that text
119/// during encoding. Keeping the types separate preserves the tokenizer crate's
120/// published zero-copy `EncodeSegment<'_>` API.
121#[derive(Debug, Clone, PartialEq, Eq)]
122pub struct RenderedPrompt {
123    text: String,
124    segments: Option<Vec<RenderedSegment>>,
125}
126
127impl RenderedPrompt {
128    pub fn text(text: String) -> Self {
129        Self {
130            text,
131            segments: None,
132        }
133    }
134
135    pub fn segmented(segments: Vec<RenderedSegment>) -> Self {
136        let text = segments
137            .iter()
138            .map(|segment| segment.text.as_str())
139            .collect();
140        Self {
141            text,
142            segments: Some(segments),
143        }
144    }
145
146    pub fn as_str(&self) -> &str {
147        &self.text
148    }
149
150    pub fn segments(&self) -> Option<&[RenderedSegment]> {
151        self.segments.as_deref()
152    }
153
154    pub fn encode_segments(&self) -> Option<Vec<dynamo_tokenizers::EncodeSegment<'_>>> {
155        Some(
156            self.segments()?
157                .iter()
158                .map(RenderedSegment::as_encode_segment)
159                .collect(),
160        )
161    }
162
163    pub fn into_text(self) -> String {
164        self.text
165    }
166}
167
168/// A prompt-rendering failure caused by the request rather than server state.
169///
170/// Callers can downcast an [`anyhow::Error`] to this type and map it to their
171/// protocol's invalid-request status without treating every template failure as
172/// a client error.
173#[derive(Debug, Clone, PartialEq, Eq)]
174pub enum PromptRenderError {
175    InvalidRequest(String),
176}
177
178impl PromptRenderError {
179    pub fn invalid_request(message: impl Into<String>) -> Self {
180        Self::InvalidRequest(message.into())
181    }
182}
183
184impl std::fmt::Display for PromptRenderError {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        match self {
187            Self::InvalidRequest(message) => f.write_str(message),
188        }
189    }
190}
191
192impl std::error::Error for PromptRenderError {}
193
194/// Trait that defines a request that can map to an OpenAI-like request.
195///
196/// Implement this for your request type to render it through a
197/// [`PromptFormatter`]. Media/multimodal IO config is intentionally *not* part
198/// of this trait — it is a preprocessing concern owned by the consumer, kept
199/// off the rendering surface so this crate stays runtime-free.
200pub trait OAIChatLikeRequest {
201    fn model(&self) -> String;
202    fn messages(&self) -> Value;
203    fn typed_messages(&self) -> Option<&[dynamo_protocols::types::ChatCompletionRequestMessage]> {
204        None
205    }
206    fn tools(&self) -> Option<Value> {
207        None
208    }
209    fn tool_choice(&self) -> Option<Value> {
210        None
211    }
212    fn response_format(&self) -> Option<Value> {
213        None
214    }
215
216    /// OpenAI-compatible reasoning-effort control, when the request type
217    /// exposes it as a top-level field.
218    fn reasoning_effort(&self) -> Option<Value> {
219        None
220    }
221
222    fn should_add_generation_prompt(&self) -> bool;
223
224    /// Optional additional args to merge into the chat template context
225    fn chat_template_args(&self) -> Option<&HashMap<String, serde_json::Value>> {
226        None
227    }
228
229    /// Returns the type of input for the prompt. Default is Text.
230    fn prompt_input_type(&self) -> PromptInput {
231        PromptInput::Text(TextInput::Single(String::new()))
232    }
233
234    /// Extract tokens if the input is pre-tokenized
235    fn extract_tokens(&self) -> Option<TokenInput> {
236        None
237    }
238
239    fn extract_text(&self) -> Option<TextInput> {
240        None
241    }
242
243    fn mm_processor_kwargs(&self) -> Option<&serde_json::Value> {
244        None
245    }
246}
247
248pub trait OAIPromptFormatter: Send + Sync + 'static {
249    fn supports_add_generation_prompt(&self) -> bool;
250    fn render(&self, req: &dyn OAIChatLikeRequest) -> Result<String>;
251
252    /// Source message indices in rendered media order; `None` preserves arrival order.
253    /// An explicit order must be a permutation of all source-message indices.
254    /// Parts within each message retain their original order.
255    fn media_message_order(&self, _request: &dyn OAIChatLikeRequest) -> Option<Vec<usize>> {
256        None
257    }
258
259    fn render_prompt(&self, req: &dyn OAIChatLikeRequest) -> Result<RenderedPrompt> {
260        self.render(req).map(RenderedPrompt::text)
261    }
262}
263
264/// Reject Kimi-style Partial Mode in a formatter that cannot leave the final
265/// assistant turn open for continuation.
266///
267/// `partial: false` and `partial: null` are ordinary message metadata and are
268/// intentionally ignored. Supporting formatters (currently Kimi K3) do not
269/// call this helper and implement the open-turn rendering themselves.
270pub(crate) fn reject_unsupported_partial_assistant(messages: &serde_json::Value) -> Result<()> {
271    let has_partial =
272        messages.as_array().into_iter().flatten().any(|message| {
273            message.get("partial").and_then(serde_json::Value::as_bool) == Some(true)
274        });
275    if has_partial {
276        return Err(PromptRenderError::invalid_request(
277            "assistant `partial: true` is not supported by this model's prompt formatter",
278        )
279        .into());
280    }
281    Ok(())
282}
283
284/// Reject non-empty message-level tool declarations on roles where a formatter
285/// does not support that field. `tools: null` and `tools: []` declare nothing.
286pub(crate) fn reject_unsupported_message_tools(
287    messages: &serde_json::Value,
288    supported_tool_roles: &[&str],
289) -> Result<()> {
290    let offending = messages.as_array().into_iter().flatten().find(|message| {
291        let declares_tools = message
292            .get("tools")
293            .is_some_and(|tools| !tools.is_null() && !tools.as_array().is_some_and(Vec::is_empty));
294        let role_is_supported = message
295            .get("role")
296            .and_then(serde_json::Value::as_str)
297            .is_some_and(|role| supported_tool_roles.contains(&role));
298        declares_tools && !role_is_supported
299    });
300
301    if let Some(message) = offending {
302        let role = message
303            .get("role")
304            .and_then(serde_json::Value::as_str)
305            .unwrap_or("<missing>");
306        return Err(PromptRenderError::invalid_request(format!(
307            "message-level `tools` on role {role:?} are not supported by this model's prompt \
308             formatter"
309        ))
310        .into());
311    }
312    Ok(())
313}
314
315#[derive(Clone)]
316pub enum PromptFormatter {
317    OAI(Arc<dyn OAIPromptFormatter>),
318}
319
320// No-op formatter: used for models without chat_template
321#[derive(Debug, Default)]
322pub struct NoOpFormatter;
323
324impl OAIPromptFormatter for NoOpFormatter {
325    fn supports_add_generation_prompt(&self) -> bool {
326        false
327    }
328
329    fn render(&self, req: &dyn OAIChatLikeRequest) -> Result<String> {
330        let messages = req.messages();
331        let messages_json = serde_json::to_value(&messages)?;
332        reject_unsupported_partial_assistant(&messages_json)?;
333        reject_unsupported_message_tools(&messages_json, &[])?;
334
335        let first_message = messages
336            .get_item_by_index(0)
337            .map_err(|_| anyhow::Error::msg("No message at index 0 or messages array is empty"))?;
338
339        let content = first_message
340            .get_attr("content")
341            .map_err(|_| anyhow::Error::msg("First message has no 'content' field"))?;
342
343        let content_str = content
344            .as_str()
345            .ok_or_else(|| anyhow::Error::msg("Message content is not a string"))?
346            .to_string();
347        Ok(content_str)
348    }
349}
350
351impl PromptFormatter {
352    pub fn no_op() -> Self {
353        Self::OAI(Arc::new(NoOpFormatter))
354    }
355}
356
357#[cfg(test)]
358mod rendered_prompt_tests {
359    use super::{
360        NoOpFormatter, OAIPromptFormatter, PromptRenderError, RenderedPrompt, RenderedSegment,
361    };
362
363    #[test]
364    fn owned_segments_borrow_into_tokenizer_segments() {
365        let prompt = RenderedPrompt::segmented(vec![
366            RenderedSegment::new("<|open|>", true),
367            RenderedSegment::new("user text", false),
368        ]);
369
370        let segments = prompt.encode_segments().expect("segmented prompt");
371        assert_eq!(segments[0].text, "<|open|>");
372        assert!(segments[0].allow_special);
373        assert_eq!(segments[1].text, "user text");
374        assert!(!segments[1].allow_special);
375        assert_eq!(prompt.as_str(), "<|open|>user text");
376    }
377
378    #[test]
379    fn no_op_formatter_rejects_unsupported_partial_assistant() {
380        let request: dynamo_protocols::types::CreateChatCompletionRequest =
381            serde_json::from_value(serde_json::json!({
382                "model": "test",
383                "messages": [
384                    {"role": "user", "content": "Continue"},
385                    {"role": "assistant", "content": "prefix", "partial": true}
386                ]
387            }))
388            .unwrap();
389
390        let error = NoOpFormatter.render(&request).unwrap_err();
391        assert!(matches!(
392            error.downcast_ref::<PromptRenderError>(),
393            Some(PromptRenderError::InvalidRequest(message))
394                if message.contains("`partial: true` is not supported")
395        ));
396    }
397
398    #[test]
399    fn no_op_formatter_rejects_message_level_tools() {
400        let request: dynamo_protocols::types::CreateChatCompletionRequest =
401            serde_json::from_value(serde_json::json!({
402                "model": "test",
403                "messages": [
404                    {"role": "system", "tools": [{"name": "lookup"}]},
405                    {"role": "user", "content": "Continue"}
406                ]
407            }))
408            .unwrap();
409
410        let error = NoOpFormatter.render(&request).unwrap_err();
411        assert!(matches!(
412            error.downcast_ref::<PromptRenderError>(),
413            Some(PromptRenderError::InvalidRequest(message))
414                if message.contains("message-level `tools`")
415        ));
416    }
417}