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.1112/// The token that opens a turn.13constSTART: &str = "<|im_start|>";14/// The token that closes a turn.15constEND: &str = "<|im_end|>";16/// The role that answers. It opens the reply and closes an assistant turn.17constASSISTANT: &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.21constNAME_SEPARATOR: char = ' ';2223/// Who wrote one message.24 #[derive(Clone, PartialEq, Eq, Debug)]25pubenumRole {26/// The instructions of the operator.27System,28/// The person or the program that asks.29User,30/// An answer of the model, earlier in the same conversation.31Assistant,32/// The result of a tool call. The name is the tool that produced it.33Tool {34/// The tool name that the plugin declared in the decision.35 name: String,36 },37 }3839implRole {40/// Appends the text that follows the start token.41fnwrite_tag(&self, out: &mutString) {42matchself {43Role::System => out.push_str("system"),44Role::User => out.push_str("user"),45Role::Assistant => out.push_str(ASSISTANT),46Role::Tool { name } => {47 out.push_str("tool");48 out.push(NAME_SEPARATOR);49 out.push_str(name);50 }51 }52 }53 }5455/// One turn of a conversation.56 #[derive(Clone, PartialEq, Eq, Debug)]57pubstructMessage {58/// Who wrote it.59pub 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.62pub content: String,63 }6465/// The chatml layout.66 #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]67pubstructChatMl;6869implChatMl {70/// The template that the catalogue names `chatml`.71pubfnnew() -> ChatMl {72ChatMl73 }7475/// 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.80pubfnrender(&self, messages: &[Message]) -> String {81letmut out = String::new();82for 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 }9697/// 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)]103pubenumTemplate {104/// The `<|im_start|>role` layout.105ChatMl,106/// The `<|start_header_id|>role` layout.107Header,108/// The `[INST]` layout.109Instruction,110/// The `<start_of_turn>role` layout.111Turn,112/// The `<|role|>` layout.113Pipe,114 }115116implTemplate {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.119pubfnfrom_name(name: &str) -> Option<Template> {120Some(match name {121"chatml" => Template::ChatMl,122"header" => Template::Header,123"instruction" => Template::Instruction,124"turn" => Template::Turn,125"pipe" => Template::Pipe,126 _ => returnNone,127 })128 }129130/// 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.136pubfnfrom_jinja(template: &str) -> Option<Template> {137if template.contains("<|start_header_id|>") {138Some(Template::Header)139 } elseif template.contains("<start_of_turn>") {140Some(Template::Turn)141 } elseif template.contains("<|im_start|>") {142Some(Template::ChatMl)143 } elseif template.contains("[INST]") {144Some(Template::Instruction)145 } elseif template.contains("<|user|>") && template.contains("<|assistant|>") {146Some(Template::Pipe)147 } else {148None149 }150 }151152/// The prompt that the model reads, ending where the reply begins.153pubfnrender(&self, messages: &[Message]) -> String {154matchself {155Template::ChatMl => ChatMl::new().render(messages),156Template::Header => render_header(messages),157Template::Instruction => render_instruction(messages),158Template::Turn => render_turn(messages),159Template::Pipe => render_pipe(messages),160 }161 }162 }163164/// The role word for a layout that has no separate tag writer.165fnrole_name(role: &Role) -> &str {166match role {167Role::System => "system",168Role::User => "user",169Role::Assistant => "assistant",170Role::Tool { .. } => "tool",171 }172 }173174/// A header before every turn.175fnrender_header(messages: &[Message]) -> String {176letmut out = String::from("<|begin_of_text|>");177for 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 }187188/// 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.190fnrender_instruction(messages: &[Message]) -> String {191letmut out = String::new();192letmut system: Option<&str> = None;193letmut open = false;194letmut closed = false;195for message in messages {196match &message.role {197Role::Systemif !open => system = Some(&message.content),198Role::System => {199if !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 }208Role::User => {209if open && !closed {210 out.push_str("</s>");211 }212 out.push_str("<s>[INST] ");213ifletSome(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 }223Role::Assistant => {224if !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 }233Role::Tool { name } => {234if 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 }250251/// A turn marker before every message.252fnrender_turn(messages: &[Message]) -> String {253letmut out = String::new();254for message in messages {255 out.push_str("<start_of_turn>");256if 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 }268269/// A pipe marker before every message.270fnrender_pipe(messages: &[Message]) -> String {271letmut out = String::new();272for 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 }