chat_template.rs 13.7 KB
Newer Older
1
2
3
4
5
6
//! Chat template support for tokenizers using Jinja2 templates
//!
//! This module provides functionality to apply chat templates to messages,
//! similar to HuggingFace transformers' apply_chat_template method.

use anyhow::{anyhow, Result};
7
use minijinja::{context, machinery, Environment, Value};
8
use serde_json;
9
use std::collections::HashMap;
10

11
12
13
14
15
16
17
/// Chat template content format
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChatTemplateContentFormat {
    /// Content is a simple string
    String,
    /// Content is a list of structured parts (OpenAI format)
    OpenAI,
18
19
}

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
impl Default for ChatTemplateContentFormat {
    fn default() -> Self {
        Self::String
    }
}

impl std::fmt::Display for ChatTemplateContentFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::String => write!(f, "string"),
            Self::OpenAI => write!(f, "openai"),
        }
    }
}

/// Detect the content format expected by a Jinja2 chat template
///
/// This implements the same detection logic as SGLang's detect_jinja_template_content_format
/// which uses AST parsing to look for content iteration patterns.
///
/// Returns:
/// - ChatTemplateContentFormat::OpenAI if template expects structured content (list of parts)
/// - ChatTemplateContentFormat::String if template expects simple string content
pub fn detect_chat_template_content_format(template: &str) -> ChatTemplateContentFormat {
    // Use AST-based detection (enabled by default)
    if let Some(format) = detect_format_with_ast(template) {
        return format;
    }

    // Default to string format if AST parsing fails
    ChatTemplateContentFormat::String
}

/// AST-based detection using minijinja's unstable machinery
/// This implements the exact same logic as SGLang's _is_var_or_elems_access functions
fn detect_format_with_ast(template: &str) -> Option<ChatTemplateContentFormat> {
    use minijinja::machinery::{parse, WhitespaceConfig};
    use minijinja::syntax::SyntaxConfig;

    // Parse the template into AST
    let ast = match parse(
        template,
        "template",
        SyntaxConfig {},
        WhitespaceConfig::default(),
    ) {
        Ok(ast) => ast,
        Err(_) => return Some(ChatTemplateContentFormat::String),
    };

    // Traverse AST looking for patterns that indicate OpenAI format
    let has_iteration = find_content_iteration_in_ast(&ast);
    let has_structure_checks = find_content_structure_checks_in_ast(&ast);
    let has_assignment_patterns = find_variable_assignment_patterns_in_ast(&ast);

    if has_iteration || has_structure_checks || has_assignment_patterns {
        Some(ChatTemplateContentFormat::OpenAI)
    } else {
        Some(ChatTemplateContentFormat::String)
    }
}

/// Find content iteration patterns in AST
/// Implements the same logic as SGLang's AST traversal
fn find_content_iteration_in_ast(ast: &machinery::ast::Stmt) -> bool {
    use machinery::ast::Stmt;

    match ast {
        Stmt::Template(template) => {
            // Recursively check all children
            template
                .children
                .iter()
                .any(|child| find_content_iteration_in_ast(child))
        }
        Stmt::ForLoop(for_loop) => {
            // Check if this for-loop iterates over message content
            is_var_or_elems_access(&for_loop.iter, "message", "content") ||
            is_var_or_elems_access(&for_loop.iter, "msg", "content") ||
            is_var_or_elems_access(&for_loop.iter, "m", "content") ||
            // Also check the body for nested loops
            for_loop.body.iter().any(|stmt| find_content_iteration_in_ast(stmt))
        }
        Stmt::IfCond(if_cond) => {
            // Check true and false branches
            if_cond
                .true_body
                .iter()
                .any(|stmt| find_content_iteration_in_ast(stmt))
                || if_cond
                    .false_body
                    .iter()
                    .any(|stmt| find_content_iteration_in_ast(stmt))
        }
        _ => false, // Other statement types don't contain loops
    }
}

/// Check if expression accesses varname['key'] or varname.key
/// Implements SGLang's _is_var_or_elems_access logic using actual AST nodes
fn is_var_or_elems_access(expr: &machinery::ast::Expr, varname: &str, key: &str) -> bool {
    use machinery::ast::Expr;

    match expr {
        // Check for attribute access: varname.key
        Expr::GetAttr(getattr) => is_var_access(&getattr.expr, varname) && getattr.name == key,
        // Check for item access: varname['key'] or varname["key"]
        Expr::GetItem(getitem) => {
            is_var_access(&getitem.expr, varname) && is_const_string(&getitem.subscript_expr, key)
        }
        // Handle filters and tests that might wrap the access
        Expr::Filter(filter) => {
            if let Some(ref expr) = filter.expr {
                is_var_or_elems_access(expr, varname, key)
            } else {
                false
            }
        }
        Expr::Test(test) => is_var_or_elems_access(&test.expr, varname, key),
        _ => false,
    }
}

/// Check if expression is a variable access (like {{ varname }})
/// Implements SGLang's _is_var_access logic
fn is_var_access(expr: &machinery::ast::Expr, varname: &str) -> bool {
    matches!(expr, machinery::ast::Expr::Var(var) if var.id == varname)
}

/// Check if expression is a constant string with the given value
fn is_const_string(expr: &machinery::ast::Expr, value: &str) -> bool {
    matches!(expr, machinery::ast::Expr::Const(const_expr)
        if const_expr.value.as_str() == Some(value))
}

/// Find content structure checks in AST (like content[0], content|length)
fn find_content_structure_checks_in_ast(ast: &machinery::ast::Stmt) -> bool {
    use machinery::ast::Stmt;

    match ast {
        Stmt::Template(template) => template
            .children
            .iter()
            .any(|child| find_content_structure_checks_in_ast(child)),
        Stmt::ForLoop(for_loop) => for_loop
            .body
            .iter()
            .any(|stmt| find_content_structure_checks_in_ast(stmt)),
        Stmt::IfCond(if_cond) => {
            // Check if condition has content structure checks
            has_content_structure_check_expr(&if_cond.expr)
                || if_cond
                    .true_body
                    .iter()
                    .any(|stmt| find_content_structure_checks_in_ast(stmt))
                || if_cond
                    .false_body
                    .iter()
                    .any(|stmt| find_content_structure_checks_in_ast(stmt))
        }
        Stmt::EmitExpr(expr) => has_content_structure_check_expr(&expr.expr),
        _ => false,
    }
}

/// Find variable assignment patterns like set content = message['content']
fn find_variable_assignment_patterns_in_ast(ast: &machinery::ast::Stmt) -> bool {
    use machinery::ast::Stmt;

    match ast {
        Stmt::Template(template) => template
            .children
            .iter()
            .any(|child| find_variable_assignment_patterns_in_ast(child)),
        Stmt::ForLoop(for_loop) => {
            // Check if this for-loop body contains both assignment and iteration
            let has_assignment = for_loop
                .body
                .iter()
                .any(|stmt| is_content_assignment_stmt(stmt));
            let has_iteration = for_loop.body.iter().any(|stmt| {
                is_content_variable_iteration(stmt)
                    || matches!(stmt, Stmt::IfCond(if_cond) if
                        if_cond.true_body.iter().any(|s| is_content_variable_iteration(s)) ||
                        if_cond.false_body.iter().any(|s| is_content_variable_iteration(s))
                    )
            });

            (has_assignment && has_iteration)
                || for_loop
                    .body
                    .iter()
                    .any(|stmt| find_variable_assignment_patterns_in_ast(stmt))
        }
        Stmt::IfCond(if_cond) => {
            if_cond
                .true_body
                .iter()
                .any(|stmt| find_variable_assignment_patterns_in_ast(stmt))
                || if_cond
                    .false_body
                    .iter()
                    .any(|stmt| find_variable_assignment_patterns_in_ast(stmt))
223
        }
224
        _ => false,
225
    }
226
227
228
229
230
}

/// Check if expression has content structure checks (index access, length, etc.)
fn has_content_structure_check_expr(expr: &machinery::ast::Expr) -> bool {
    use machinery::ast::Expr;
231

232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
    match expr {
        // Check for content[0] - index access
        Expr::GetItem(getitem) => {
            is_content_access(&getitem.expr) && is_numeric_constant(&getitem.subscript_expr)
        }
        // Check for content|length - filter with length
        Expr::Filter(filter) => {
            if let Some(ref filter_expr) = filter.expr {
                is_content_access(filter_expr) && filter.name == "length"
            } else {
                false
            }
        }
        // Check for content is sequence/iterable
        Expr::Test(test) => {
            is_content_access(&test.expr) && (test.name == "sequence" || test.name == "iterable")
        }
        _ => false,
250
    }
251
252
253
254
255
}

/// Check if statement assigns message content to a variable
fn is_content_assignment_stmt(stmt: &machinery::ast::Stmt) -> bool {
    use machinery::ast::Stmt;
256

257
258
259
260
261
262
263
    match stmt {
        Stmt::Set(set_stmt) => {
            // Check if this is setting content = message['content']
            is_var_access(&set_stmt.target, "content")
                && is_var_or_elems_access(&set_stmt.expr, "message", "content")
        }
        _ => false,
264
    }
265
}
266

267
268
269
270
271
272
273
274
275
276
/// Check if statement iterates over content variable
fn is_content_variable_iteration(stmt: &machinery::ast::Stmt) -> bool {
    use machinery::ast::{Expr, Stmt};

    match stmt {
        Stmt::ForLoop(for_loop) => {
            // Check if iterating over a variable named "content"
            matches!(for_loop.iter, Expr::Var(ref var) if var.id == "content")
        }
        _ => false,
277
278
279
    }
}

280
281
282
283
284
285
286
287
288
289
290
291
/// Check if expression accesses content (message.content, message['content'], etc.)
fn is_content_access(expr: &machinery::ast::Expr) -> bool {
    is_var_or_elems_access(expr, "message", "content")
        || is_var_or_elems_access(expr, "msg", "content")
        || is_var_or_elems_access(expr, "m", "content")
}

/// Check if expression is a numeric constant (for index access)
fn is_numeric_constant(expr: &machinery::ast::Expr) -> bool {
    matches!(expr, machinery::ast::Expr::Const(const_expr) if const_expr.value.is_number())
}

292
293
294
295
296
297
298
299
300
301
/// Parameters for chat template application
#[derive(Default)]
pub struct ChatTemplateParams<'a> {
    pub add_generation_prompt: bool,
    pub continue_final_message: bool,
    pub tools: Option<&'a [serde_json::Value]>,
    pub documents: Option<&'a [serde_json::Value]>,
    pub template_kwargs: Option<&'a HashMap<String, serde_json::Value>>,
}

302
/// Chat template processor using Jinja2 - simple wrapper like HuggingFace
303
304
305
306
307
308
pub struct ChatTemplateProcessor {
    template: String,
}

impl ChatTemplateProcessor {
    /// Create a new chat template processor
309
310
    pub fn new(template: String) -> Self {
        ChatTemplateProcessor { template }
311
312
313
314
315
316
    }

    /// Apply the chat template to a list of messages
    ///
    /// This mimics the behavior of HuggingFace's apply_chat_template method
    /// but returns the formatted string instead of token IDs.
317
    /// Messages should be pre-processed into the format expected by the template.
318
319
    pub fn apply_chat_template(
        &self,
320
        messages: &[serde_json::Value],
321
        params: ChatTemplateParams,
322
    ) -> Result<String> {
323
324
325
326
        // Validate incompatible options
        if params.continue_final_message && params.add_generation_prompt {
            return Err(anyhow!("continue_final_message and add_generation_prompt are not compatible. Use continue_final_message when you want the model to continue the final message, and add_generation_prompt when you want to add a header that will prompt it to start a new assistant message instead."));
        }
327
328
329
330
331
332
333
334
335
336
337
        let mut env = Environment::new();

        // Register the template
        env.add_template("chat", &self.template)
            .map_err(|e| anyhow!("Failed to add template: {}", e))?;

        // Get the template
        let tmpl = env
            .get_template("chat")
            .map_err(|e| anyhow!("Failed to get template: {}", e))?;

338
        // Convert messages to minijinja::Value (messages already processed by router)
339
        let minijinja_messages: Vec<Value> = messages.iter().map(Value::from_serialize).collect();
340

341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
        let base_context = context! {
            messages => &minijinja_messages,
            add_generation_prompt => params.add_generation_prompt,
            tools => params.tools,
            documents => params.documents,
        };

        // Merge with template_kwargs if provided
        let ctx = if let Some(kwargs) = params.template_kwargs {
            context! {
                ..base_context,
                ..Value::from_serialize(kwargs)
            }
        } else {
            base_context
        };

        // Render the template
359
        let rendered = tmpl
360
            .render(&ctx)
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
            .map_err(|e| anyhow!("Failed to render template: {}", e))?;

        Ok(rendered)
    }
}

/// Load chat template from tokenizer config JSON
pub fn load_chat_template_from_config(config_path: &str) -> Result<Option<String>> {
    use std::fs;

    let content = fs::read_to_string(config_path)?;
    let config: serde_json::Value = serde_json::from_str(&content)?;

    // Look for chat_template in the config
    if let Some(template) = config.get("chat_template") {
        if let Some(template_str) = template.as_str() {
            return Ok(Some(template_str.to_string()));
        }
    }

    Ok(None)
}