Skip to main content

tokenmeter_core/
lib.rs

1#![doc = include_str!("../README.md")]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4
5use std::collections::HashSet;
6use std::fmt;
7use std::sync::LazyLock;
8
9use rustc_hash::FxHashMap;
10use tiktoken_rs::{CoreBPE, ENDOFPROMPT, ENDOFTEXT, EncodeError, O200K_BASE_PAT_STR, Rank};
11use unicode_segmentation::UnicodeSegmentation;
12
13/// The name of the embedded encoding.
14pub const ENCODING: &str = "o200k_base";
15
16/// The largest accepted input, in UTF-8 bytes.
17pub const MAX_INPUT_BYTES: usize = 1_048_576;
18
19/// A failure to prepare the encoding or tokenize the input.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum Error {
22    /// The text exceeds [`MAX_INPUT_BYTES`].
23    InputTooLarge,
24    /// The tokenizer could not segment the input.
25    Tokenization,
26    /// The embedded encoding could not be initialized or returned inconsistent data.
27    Internal,
28}
29
30impl fmt::Display for Error {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        f.write_str(match self {
33            Self::InputTooLarge => "text exceeds the UTF-8 byte limit",
34            Self::Tokenization => "tokenization failed",
35            Self::Internal => "internal encoding error",
36        })
37    }
38}
39
40impl std::error::Error for Error {}
41
42/// One consecutive group of tokens spanning whole grapheme clusters.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct Group {
45    /// Exclusive UTF-8 byte offset in the original text.
46    pub end: usize,
47    /// Number of tokens in this group.
48    pub tokens: usize,
49}
50
51/// A preview of the start of a text, with its complete token count.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct Split {
54    /// Number of tokens in the entire input.
55    pub tokens: usize,
56    /// Consecutive groups starting at byte zero, in input order.
57    pub groups: Vec<Group>,
58    /// Whether any text remains after the last returned group.
59    pub truncated: bool,
60}
61
62static TABLE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/o200k_base.bin"));
63
64struct Encoding {
65    core: CoreBPE,
66    tokens: Vec<&'static [u8]>,
67}
68
69static ENCODING_TABLES: LazyLock<Result<Encoding, Error>> = LazyLock::new(|| {
70    let mut tokens = Vec::with_capacity(200_000);
71    let mut at = 0;
72
73    while at < TABLE.len() {
74        let end = at + 1 + usize::from(TABLE[at]);
75
76        tokens.push(&TABLE[at + 1..end]);
77        at = end;
78    }
79
80    let encoder: FxHashMap<Vec<u8>, Rank> =
81        tokens.iter().enumerate().map(|(rank, token)| (token.to_vec(), rank as Rank)).collect();
82    let special = [(ENDOFTEXT.to_owned(), 199_999), (ENDOFPROMPT.to_owned(), 200_018)].into_iter().collect();
83    let core = CoreBPE::new(encoder, special, O200K_BASE_PAT_STR).map_err(|_| Error::Internal)?;
84
85    Ok(Encoding { core, tokens })
86});
87
88fn encoding() -> Result<&'static Encoding, Error> {
89    ENCODING_TABLES.as_ref().map_err(|&error| error)
90}
91
92/// Initializes the shared encoding. Later calls reuse the result.
93///
94/// # Errors
95/// Returns [`Error::Internal`] if the encoding cannot be initialized.
96pub fn prepare() -> Result<(), Error> {
97    encoding().map(|_| ())
98}
99
100/// Counts tokens in the entire input using the same rules and errors as [`encode`].
101pub fn count(text: &str) -> Result<usize, Error> {
102    Ok(encode(text)?.len())
103}
104
105/// Returns the ordinary token IDs of `o200k_base`, including for literal special markers.
106///
107/// # Errors
108/// Returns [`Error::InputTooLarge`] before initialization or tokenization if the UTF-8 input
109/// exceeds [`MAX_INPUT_BYTES`], [`Error::Internal`] if initialization fails, and
110/// [`Error::Tokenization`] if the tokenizer cannot segment the input.
111pub fn encode(text: &str) -> Result<Vec<u32>, Error> {
112    if text.len() > MAX_INPUT_BYTES {
113        return Err(Error::InputTooLarge);
114    }
115    ordinary_ids(encoding()?.core.encode(text, &HashSet::new()))
116}
117
118fn ordinary_ids(result: Result<(Vec<Rank>, usize), EncodeError>) -> Result<Vec<Rank>, Error> {
119    result.map(|(ids, _)| ids).map_err(|_| Error::Tokenization)
120}
121
122/// Counts the entire text and returns up to `limit` groups ending on grapheme boundaries.
123/// A zero limit returns an empty preview and the full count.
124///
125/// # Errors
126/// Returns the errors described by [`encode`], or [`Error::Internal`] for inconsistent token offsets.
127pub fn split(text: &str, limit: usize) -> Result<Split, Error> {
128    let ids = encode(text)?;
129    let tokens = &encoding()?.tokens;
130    let mut graphemes = text.grapheme_indices(true).map(|(start, grapheme)| start + grapheme.len());
131    let mut boundary = 0;
132    let mut groups = Vec::new();
133    let mut offset = 0;
134    let mut pending = 0;
135
136    for &id in &ids {
137        if groups.len() == limit {
138            return Ok(Split { tokens: ids.len(), groups, truncated: true });
139        }
140        offset += tokens.get(id as usize).ok_or(Error::Internal)?.len();
141        pending += 1;
142
143        while boundary < offset {
144            boundary = graphemes.next().ok_or(Error::Internal)?;
145        }
146
147        if boundary == offset {
148            groups.push(Group { end: offset, tokens: pending });
149            pending = 0;
150        }
151    }
152
153    Ok(Split { tokens: ids.len(), groups, truncated: false })
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn counts_a_phrase_from_the_site() {
162        assert_eq!(count("Пользователи — это наше всё."), Ok(9));
163    }
164
165    #[test]
166    fn matcher_error_is_recoverable() {
167        let failure = EncodeError { message: "test".to_owned() };
168        assert_eq!(ordinary_ids(Err(failure)), Err(Error::Tokenization));
169        assert_eq!(count("a"), Ok(1));
170    }
171
172    #[test]
173    fn counts_special_tokens_as_text() -> Result<(), Error> {
174        for marker in [ENDOFTEXT, ENDOFPROMPT] {
175            let ids = encode(marker)?;
176            assert!(ids.len() > 1);
177            assert!(!ids.contains(&199_999) && !ids.contains(&200_018));
178        }
179        Ok(())
180    }
181
182    #[test]
183    fn counts_nothing_in_empty_text() {
184        assert_eq!(count(""), Ok(0));
185        assert_eq!(split("", 200), Ok(Split { tokens: 0, groups: vec![], truncated: false }));
186        assert_eq!(split("", 0), Ok(Split { tokens: 0, groups: vec![], truncated: false }));
187    }
188
189    #[test]
190    fn groups_cover_the_text() -> Result<(), Error> {
191        let text = "Съешь же ещё этих мягких французских булок, да выпей чаю.\n\n  fn main() {}";
192        let split = split(text, 200)?;
193
194        assert_eq!(split.groups.last().map(|group| group.end), Some(text.len()));
195        assert_eq!(split.groups.iter().map(|group| group.tokens).sum::<usize>(), split.tokens);
196        assert_eq!(split.tokens, count(text)?);
197        assert!(!split.truncated);
198        Ok(())
199    }
200
201    #[test]
202    fn keeps_graphemes_whole_at_every_limit() -> Result<(), Error> {
203        let text = "👩🏽‍💻\r\ne\u{301}🇷🇺 ไทย";
204        let ends: Vec<_> = text.grapheme_indices(true).map(|(start, grapheme)| start + grapheme.len()).collect();
205        let full = split(text, usize::MAX)?;
206        assert_eq!(full.groups.last().map(|group| group.end), Some(text.len()));
207        for group in &full.groups {
208            assert!(ends.contains(&group.end));
209        }
210        for limit in 0..=full.groups.len() + 1 {
211            let preview = split(text, limit)?;
212            assert_eq!(preview.groups, full.groups[..limit.min(full.groups.len())]);
213            assert_eq!(preview.tokens, full.tokens);
214            assert_eq!(preview.truncated, limit < full.groups.len());
215        }
216        Ok(())
217    }
218
219    #[test]
220    fn stops_at_the_limit_and_counts_the_rest() -> Result<(), Error> {
221        let text = "слово ".repeat(1000);
222        let split = split(&text, 200)?;
223
224        assert_eq!(split.groups.len(), 200);
225        assert!(split.truncated);
226        assert_eq!(split.tokens, count(&text)?);
227        Ok(())
228    }
229
230    #[test]
231    fn enforces_the_utf8_byte_limit() -> Result<(), Error> {
232        let mut text = "é ".repeat(MAX_INPUT_BYTES / 3);
233        text.push('a');
234        assert_eq!(text.len(), MAX_INPUT_BYTES);
235        let tokens = count(&text)?;
236        assert_eq!(encode(&text)?.len(), tokens);
237        assert_eq!(split(&text, 0)?, Split { tokens, groups: vec![], truncated: true });
238
239        text.push('b');
240        assert_eq!(count(&text), Err(Error::InputTooLarge));
241        assert_eq!(encode(&text), Err(Error::InputTooLarge));
242        assert_eq!(split(&text, 1), Err(Error::InputTooLarge));
243        Ok(())
244    }
245}