troupekit-local 0.4.0

On-device models for the Troupekit LLM agent framework: the LocalModel trait, model catalog and llama.cpp.
Documentation
use super::Flow;

/// The text of one generation as it streams: decodes token bytes as
/// UTF-8, holds back a tail that could still start a stop string, and
/// hands each settled piece to the token callback.
/// Input: the stop strings. Output: the kept text, through `into_text`.
pub(crate) struct Gen<'a> {
    text: String,
    pending: Vec<u8>,
    emitted: usize,
    stops: &'a [String],
    hold: usize,
}

impl<'a> Gen<'a> {
    /// Starts an empty stream that holds back one byte less than the
    /// longest stop string. Input: the stop strings. Output: the stream.
    pub(crate) fn new(stops: &'a [String]) -> Self {
        let hold = stops
            .iter()
            .map(String::len)
            .max()
            .unwrap_or(0)
            .saturating_sub(1);
        Self {
            text: String::new(),
            pending: Vec::new(),
            emitted: 0,
            stops,
            hold,
        }
    }

    /// Adds one token's bytes and emits what can no longer change.
    /// Invalid bytes become U+FFFD; an incomplete trailing sequence waits
    /// for the next piece. Output: `Stop` on a stop string or when the
    /// callback stops, and then the kept text ends at what was emitted.
    pub(crate) fn push(&mut self, bytes: &[u8], on_token: &mut dyn FnMut(&str) -> Flow) -> Flow {
        self.pending.extend_from_slice(bytes);
        self.decode_pending();
        let mut search_from = self.emitted.saturating_sub(self.hold);
        while !self.text.is_char_boundary(search_from) {
            search_from -= 1;
        }
        let hit = self
            .stops
            .iter()
            .filter(|s| !s.is_empty())
            .filter_map(|s| {
                self.text[search_from..]
                    .find(s.as_str())
                    .map(|i| search_from + i)
            })
            .min();
        if let Some(at) = hit {
            self.text.truncate(at);
            self.pending.clear();
            self.emit_to(at, on_token);
            return Flow::Stop;
        }
        let mut safe = self.text.len().saturating_sub(self.hold);
        while !self.text.is_char_boundary(safe) {
            safe -= 1;
        }
        let flow = self.emit_to(safe, on_token);
        if flow == Flow::Stop {
            self.text.truncate(self.emitted);
            self.pending.clear();
        }
        flow
    }

    /// Emits the held tail at the end of the run; leftover incomplete
    /// bytes become U+FFFD. Output: the callback's `Flow` for that last
    /// piece, `Continue` when nothing was left to emit.
    pub(crate) fn finish(&mut self, on_token: &mut dyn FnMut(&str) -> Flow) -> Flow {
        if !self.pending.is_empty() {
            self.text.push_str(&String::from_utf8_lossy(&self.pending));
            self.pending.clear();
        }
        let end = self.text.len();
        self.emit_to(end, on_token)
    }

    /// Returns the kept text. Input: the stream. Output: the text.
    pub(crate) fn into_text(self) -> String {
        self.text
    }

    fn decode_pending(&mut self) {
        loop {
            match std::str::from_utf8(&self.pending) {
                Ok(s) => {
                    self.text.push_str(s);
                    self.pending.clear();
                    return;
                }
                Err(e) => {
                    let valid = e.valid_up_to();
                    let s = std::str::from_utf8(&self.pending[..valid]).expect("prefix is valid");
                    self.text.push_str(s);
                    let Some(bad) = e.error_len() else {
                        self.pending.drain(..valid);
                        assert!(
                            self.pending.len() < 4,
                            "an incomplete sequence is under 4 bytes"
                        );
                        return;
                    };
                    self.text.push(char::REPLACEMENT_CHARACTER);
                    self.pending.drain(..valid + bad);
                }
            }
        }
    }

    fn emit_to(&mut self, end: usize, on_token: &mut dyn FnMut(&str) -> Flow) -> Flow {
        if end <= self.emitted {
            return Flow::Continue;
        }
        let flow = on_token(&self.text[self.emitted..end]);
        self.emitted = end;
        flow
    }
}