crates/format/text/src/template.rs 9.2 KiB 281 lines Raw
1 //! The chat layout that a model reads.2 //!3 //! A model was trained on one layout of the turns, and the same content in4 //! another layout is a different prompt. The template is therefore text that5 //! the model file names, not something a caller may rearrange.6 //!7 //! Five shapes cover the templates that a GGUF usually carries: ChatML, a8 //! header-per-turn layout, an instruction layout, a turn-marker layout, and a9 //! pipe layout. [`Template::from_jinja`] recognises the markers in a GGUF chat10 //! template, so a bundle can choose a shape without naming a model.11 12 /// The token that opens a turn.13 const START: &str = "<|im_start|>";14 /// The token that closes a turn.15 const END: &str = "<|im_end|>";16 /// The role that answers. It opens the reply and closes an assistant turn.17 const ASSISTANT: &str = "assistant";18 /// chatml has no field for a tool name, and a model that sees two tools cannot19 /// tell their results apart without one. The name follows the role, separated20 /// by one space.21 const NAME_SEPARATOR: char = ' ';22 23 /// Who wrote one message.24 #[derive(Clone, PartialEq, Eq, Debug)]25 pub enum Role {26     /// The instructions of the operator.27     System,28     /// The person or the program that asks.29     User,30     /// An answer of the model, earlier in the same conversation.31     Assistant,32     /// The result of a tool call. The name is the tool that produced it.33     Tool {34         /// The tool name that the plugin declared in the decision.35         name: String,36     },37 }38 39 impl Role {40     /// Appends the text that follows the start token.41     fn write_tag(&self, out: &mut String) {42         match self {43             Role::System => out.push_str("system"),44             Role::User => out.push_str("user"),45             Role::Assistant => out.push_str(ASSISTANT),46             Role::Tool { name } => {47                 out.push_str("tool");48                 out.push(NAME_SEPARATOR);49                 out.push_str(name);50             }51         }52     }53 }54 55 /// One turn of a conversation.56 #[derive(Clone, PartialEq, Eq, Debug)]57 pub struct Message {58     /// Who wrote it.59     pub role: Role,60     /// The text as the model must read it. A newline and a quote are text and61     /// are never escaped; the template is not JSON.62     pub content: String,63 }64 65 /// The chatml layout.66 #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]67 pub struct ChatMl;68 69 impl ChatMl {70     /// The template that the catalogue names `chatml`.71     pub fn new() -> ChatMl {72         ChatMl73     }74 75     /// The prompt that the model reads, ending where the reply begins.76     ///77     /// The reply is not part of the result: the model continues the text, and78     /// an assistant turn in `messages` is history that it must not repeat as79     /// an answer.80     pub fn render(&self, messages: &[Message]) -> String {81         let mut out = String::new();82         for message in messages {83             out.push_str(START);84             message.role.write_tag(&mut out);85             out.push('\n');86             out.push_str(&message.content);87             out.push_str(END);88             out.push('\n');89         }90         out.push_str(START);91         out.push_str(ASSISTANT);92         out.push('\n');93         out94     }95 }96 97 /// One of the turn layouts that a GGUF chat template usually follows.98 ///99 /// The names are shapes, not models. A caller that has the template text uses100 /// [`Template::from_jinja`]; a caller that has a name uses101 /// [`Template::from_name`].102 #[derive(Clone, Copy, PartialEq, Eq, Debug)]103 pub enum Template {104     /// The `<|im_start|>role` layout.105     ChatMl,106     /// The `<|start_header_id|>role` layout.107     Header,108     /// The `[INST]` layout.109     Instruction,110     /// The `<start_of_turn>role` layout.111     Turn,112     /// The `<|role|>` layout.113     Pipe,114 }115 116 impl Template {117     /// The shape named `name`, or `None` for a name that this crate does not118     /// know. The names are the shape words, not a model name.119     pub fn from_name(name: &str) -> Option<Template> {120         Some(match name {121             "chatml" => Template::ChatMl,122             "header" => Template::Header,123             "instruction" => Template::Instruction,124             "turn" => Template::Turn,125             "pipe" => Template::Pipe,126             _ => return None,127         })128     }129 130     /// The shape that a GGUF chat template uses.131     ///132     /// The marker is enough: a template that opens a turn with133     /// `<|start_header_id|>` is a header layout whatever its variable names134     /// are. A template with no marker that this crate knows returns `None`135     /// rather than guessing a layout that the model was not trained on.136     pub fn from_jinja(template: &str) -> Option<Template> {137         if template.contains("<|start_header_id|>") {138             Some(Template::Header)139         } else if template.contains("<start_of_turn>") {140             Some(Template::Turn)141         } else if template.contains("<|im_start|>") {142             Some(Template::ChatMl)143         } else if template.contains("[INST]") {144             Some(Template::Instruction)145         } else if template.contains("<|user|>") && template.contains("<|assistant|>") {146             Some(Template::Pipe)147         } else {148             None149         }150     }151 152     /// The prompt that the model reads, ending where the reply begins.153     pub fn render(&self, messages: &[Message]) -> String {154         match self {155             Template::ChatMl => ChatMl::new().render(messages),156             Template::Header => render_header(messages),157             Template::Instruction => render_instruction(messages),158             Template::Turn => render_turn(messages),159             Template::Pipe => render_pipe(messages),160         }161     }162 }163 164 /// The role word for a layout that has no separate tag writer.165 fn role_name(role: &Role) -> &str {166     match role {167         Role::System => "system",168         Role::User => "user",169         Role::Assistant => "assistant",170         Role::Tool { .. } => "tool",171     }172 }173 174 /// A header before every turn.175 fn render_header(messages: &[Message]) -> String {176     let mut out = String::from("<|begin_of_text|>");177     for message in messages {178         out.push_str("<|start_header_id|>");179         out.push_str(role_name(&message.role));180         out.push_str("<|end_header_id|>\n\n");181         out.push_str(&message.content);182         out.push_str("<|eot_id|>");183     }184     out.push_str("<|start_header_id|>assistant<|end_header_id|>\n\n");185     out186 }187 188 /// An instruction before a user turn. The first system message is the system189 /// block; a system message after the first turn is ordinary text in that turn.190 fn render_instruction(messages: &[Message]) -> String {191     let mut out = String::new();192     let mut system: Option<&str> = None;193     let mut open = false;194     let mut closed = false;195     for message in messages {196         match &message.role {197             Role::System if !open => system = Some(&message.content),198             Role::System => {199                 if !closed {200                     out.push_str("</s>");201                 }202                 out.push_str("<s>[INST] ");203                 out.push_str(&message.content);204                 out.push_str(" [/INST]");205                 open = true;206                 closed = false;207             }208             Role::User => {209                 if open && !closed {210                     out.push_str("</s>");211                 }212                 out.push_str("<s>[INST] ");213                 if let Some(system) = system.take() {214                     out.push_str("<<SYS>>\n");215                     out.push_str(system);216                     out.push_str("\n<</SYS>>\n\n");217                 }218                 out.push_str(&message.content);219                 out.push_str(" [/INST]");220                 open = true;221                 closed = false;222             }223             Role::Assistant => {224                 if !open {225                     out.push_str("<s>[INST] ");226                     open = true;227                 }228                 out.push(' ');229                 out.push_str(&message.content);230                 out.push_str(" </s>");231                 closed = true;232             }233             Role::Tool { name } => {234                 if open && !closed {235                     out.push_str("</s>");236                 }237                 out.push_str("<s>[INST] ");238                 out.push_str("tool ");239                 out.push_str(name);240                 out.push('\n');241                 out.push_str(&message.content);242                 out.push_str(" [/INST]");243                 open = true;244                 closed = false;245             }246         }247     }248     out249 }250 251 /// A turn marker before every message.252 fn render_turn(messages: &[Message]) -> String {253     let mut out = String::new();254     for message in messages {255         out.push_str("<start_of_turn>");256         if message.role == Role::Assistant {257             out.push_str("model");258         } else {259             out.push_str(role_name(&message.role));260         }261         out.push('\n');262         out.push_str(&message.content);263         out.push_str("<end_of_turn>\n");264     }265     out.push_str("<start_of_turn>model\n");266     out267 }268 269 /// A pipe marker before every message.270 fn render_pipe(messages: &[Message]) -> String {271     let mut out = String::new();272     for message in messages {273         out.push_str("<|");274         out.push_str(role_name(&message.role));275         out.push_str("|>\n");276         out.push_str(&message.content);277         out.push_str("<|end|>\n");278     }279     out.push_str("<|assistant|>\n");280     out281 }