use serde::Serialize;
#[derive(Serialize, Clone)]
pub struct ChatMessage {
pub role: String,
pub content: String,
}
pub fn apply_chat_template(_template: Option<&str>, messages: &[ChatMessage]) -> String {
let mut out = String::new();
for m in messages {
out.push_str(&m.role);
out.push_str(": ");
out.push_str(&m.content);
out.push('\n');
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_role_and_content() {
let messages = vec![ChatMessage {
role: "user".to_string(),
content: "hello".to_string(),
}];
let out = apply_chat_template(None, &messages);
assert_eq!(out, "user: hello\n");
}
#[test]
fn formats_multiple_messages() {
let messages = vec![
ChatMessage {
role: "system".to_string(),
content: "You are helpful.".to_string(),
},
ChatMessage {
role: "user".to_string(),
content: "hi".to_string(),
},
];
let out = apply_chat_template(None, &messages);
assert_eq!(out, "system: You are helpful.\nuser: hi\n");
}
#[test]
fn template_argument_is_ignored() {
let messages = vec![ChatMessage {
role: "user".to_string(),
content: "hi".to_string(),
}];
let with = apply_chat_template(Some("{% for m in messages %}{{ m.role }}: {{ m.content }}\n{% endfor %}"), &messages);
let without = apply_chat_template(None, &messages);
assert_eq!(with, without);
}
}