1 //! The stop strings, held back from the stream.2 //!3 //! A model ends a turn at a control string such as `<|im_end|>`, and a4 //! tokenizer can emit that string as `<|im`, then `_end`, then `|>`. A server5 //! that forwarded each piece as it arrived would put the first half of a6 //! control string in front of the client, and there is no way to take a text7 //! event back. `StopSet::feed` names the part that is safe to send and flags a8 //! tail that may still become a stop.9 10 /// What one feed found in the text.11 #[derive(Clone, PartialEq, Eq, Debug)]12 pub enum Stop {13 /// The text holds no stop and no tail of one. All of it may go out.14 Nothing,15 /// A stop string starts at byte `upto`. `text[..upto]` may go out.16 Matched {17 /// Bytes of text before the stop string.18 upto: usize,19 /// The stop string that matched.20 stop: String,21 },22 /// The tail of the text is the start of a stop string. The caller holds23 /// the text back until the next feed decides.24 Partial,25 }26 27 /// The stop strings that the model file declares.28 #[derive(Clone, PartialEq, Eq, Debug, Default)]29 pub struct StopSet {30 stops: Vec<String>,31 }32 33 impl StopSet {34 /// A set with no stop string. Every feed then gives [`Stop::Nothing`].35 pub fn new() -> StopSet {36 StopSet::default()37 }38 39 /// A set of the stop strings of one model.40 ///41 /// An empty string is dropped: it is a prefix of every position, so it42 /// would end the stream at its first feed.43 pub fn from(strings: impl IntoIterator<Item = impl Into<String>>) -> StopSet {44 StopSet {45 stops: strings46 .into_iter()47 .map(Into::into)48 .filter(|stop| !stop.is_empty())49 .collect(),50 }51 }52 53 /// What the text must hold back.54 ///55 /// A stop string that starts earlier wins. Two stop strings that start at56 /// the same byte are taken longest first, so a set that holds both `<|e`57 /// and `<|end|>` never stops at the shorter one.58 pub fn feed(&self, text: &str) -> Stop {59 let mut found: Option<(usize, &str)> = None;60 for stop in &self.stops {61 let Some(at) = text.find(stop.as_str()) else {62 continue;63 };64 let wins = match found {65 Some((best, earlier)) => at < best || (at == best && stop.len() > earlier.len()),66 None => true,67 };68 if wins {69 found = Some((at, stop));70 }71 }72 match found {73 Some((upto, stop)) => Stop::Matched {74 upto,75 stop: stop.to_string(),76 },77 None if self.ends_in_prefix(text) => Stop::Partial,78 None => Stop::Nothing,79 }80 }81 82 /// True when a tail of `text` is the start of some stop string.83 ///84 /// The comparison is by bytes. A text tail cannot end inside a character,85 /// so a byte prefix that is not a whole string never matches.86 fn ends_in_prefix(&self, text: &str) -> bool {87 let text = text.as_bytes();88 self.stops.iter().any(|stop| {89 let stop = stop.as_bytes();90 // A whole stop string would have matched in `feed`, so the tail is91 // always shorter than the stop string.92 (1..stop.len())93 .rev()94 .any(|len| len <= text.len() && text.ends_with(&stop[..len]))95 })96 }97 }