template.rs 4.27 KB
Newer Older
Biswa Panda's avatar
Biswa Panda committed
1
2
3
4
5
// SPDX-FileCopyrightText: Copyright (c) 2024-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

use std::{collections::HashSet, sync::Arc};

6
use anyhow::{Context, Ok, Result};
Biswa Panda's avatar
Biswa Panda committed
7
8
use minijinja::Environment;

9
use crate::model_card::{ModelDeploymentCard, PromptContextMixin, PromptFormatterArtifact};
Biswa Panda's avatar
Biswa Panda committed
10
11
12
13
14
15
16

mod context;
mod formatters;
mod oai;
mod tokcfg;

use super::{OAIChatLikeRequest, OAIPromptFormatter, PromptFormatter};
17
use tokcfg::{ChatTemplate, ChatTemplateValue};
Biswa Panda's avatar
Biswa Panda committed
18
19

impl PromptFormatter {
20
    pub fn from_mdc(mdc: &ModelDeploymentCard) -> Result<PromptFormatter> {
Biswa Panda's avatar
Biswa Panda committed
21
22
        match mdc
            .prompt_formatter
23
            .as_ref()
Biswa Panda's avatar
Biswa Panda committed
24
25
26
            .ok_or(anyhow::anyhow!("MDC does not contain a prompt formatter"))?
        {
            PromptFormatterArtifact::HfTokenizerConfigJson(file) => {
27
                let content = std::fs::read_to_string(file)
28
                    .with_context(|| format!("fs:read_to_string '{file}'"))?;
29
                let mut config: ChatTemplate = serde_json::from_str(&content)?;
30

31
32
33
                // Some HF model (i.e. meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8)
                // stores the chat template in a separate file, we check if the file exists and
                // put the chat template into config as normalization.
34
                // This may also be a custom template provided via CLI flag.
35
                if let Some(PromptFormatterArtifact::HfChatTemplate(chat_template_file)) =
36
                    mdc.chat_template_file.as_ref()
37
                {
38
                    let chat_template = std::fs::read_to_string(chat_template_file)
39
40
41
42
43
                        .with_context(|| format!("fs:read_to_string '{}'", chat_template_file))?;
                    // clean up the string to remove newlines
                    let chat_template = chat_template.replace('\n', "");
                    config.chat_template = Some(ChatTemplateValue(either::Left(chat_template)));
                }
44
                Self::from_parts(
Biswa Panda's avatar
Biswa Panda committed
45
46
                    config,
                    mdc.prompt_context
47
                        .clone()
Biswa Panda's avatar
Biswa Panda committed
48
                        .map_or(ContextMixins::default(), |x| ContextMixins::new(&x)),
49
50
                )
            }
51
52
53
            PromptFormatterArtifact::HfChatTemplate(_) => Err(anyhow::anyhow!(
                "prompt_formatter should not have type HfChatTemplate"
            )),
54
            PromptFormatterArtifact::GGUF(gguf_path) => {
55
                let config = ChatTemplate::from_gguf(gguf_path)?;
56
                Self::from_parts(config, ContextMixins::default())
Biswa Panda's avatar
Biswa Panda committed
57
58
59
            }
        }
    }
60
61
62
63
64

    pub fn from_parts(config: ChatTemplate, context: ContextMixins) -> Result<PromptFormatter> {
        let formatter = HfTokenizerConfigJsonFormatter::new(config, context)?;
        Ok(Self::OAI(Arc::new(formatter)))
    }
Biswa Panda's avatar
Biswa Panda committed
65
66
67
68
69
70
71
72
73
74
75
}

/// Chat Template Jinja Renderer
///
/// Manages a Jinja environment with registered templates for chat formatting.
/// Handles two types of ChatTemplateValue templates:
///
/// 1. String template: Registered as the 'default' template
/// 2. Map template: Contains 'tool_use' and/or 'default' templates
///    - tool_use: Template for tool-based interactions
///    - default: Template for standard chat interactions
76
///
Biswa Panda's avatar
Biswa Panda committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
///   If the map contains both keys, the `tool_use` template is registered as the `tool_use` template
///   and the `default` template is registered as the `default` template.
struct JinjaEnvironment {
    env: Environment<'static>,
}

/// Formatter for HuggingFace tokenizer config JSON templates
///
/// Implements chat template rendering based on HuggingFace's tokenizer_config.json format.
/// Supports:
/// - Tool usage templates
/// - Generation prompts
/// - Context mixins for template customization
#[derive(Debug)]
struct HfTokenizerConfigJsonFormatter {
    env: Environment<'static>,
93
    config: ChatTemplate,
Biswa Panda's avatar
Biswa Panda committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
    mixins: Arc<ContextMixins>,
    supports_add_generation_prompt: bool,
}

// /// OpenAI Standard Prompt Formatter
// pub trait StandardPromptFormatter {
//     fn render(&self, context: &impl StandardPromptContext) -> Result<String>;
// }

// pub trait StandardPromptContext {
//     fn messages(&self) -> Value;
//     fn tools(&self) -> Option<Value>;
// }

#[derive(Debug, Clone, Default)]
pub struct ContextMixins {
    context_mixins: HashSet<PromptContextMixin>,
}