Expand description
§tokenmeter-core
Count tokens and encode text with o200k_base. Special markers such as
<|endoftext|> are treated as ordinary text, matching tiktoken’s
encode_ordinary. The vocabulary is embedded and initialized once on first
use. Threads share the immutable vocabulary. Repeated calls to prepare()
reuse the first initialization result.
use tokenmeter_core::{Error, count, split};
fn main() -> Result<(), Error> {
let text = "Пользователи — это наше всё.";
assert_eq!(count(text)?, 9);
let preview = split(text, 1)?;
assert_eq!(preview.tokens, 9);
assert_eq!(&text[..preview.groups[0].end], "П");
assert!(preview.truncated);
Ok(())
}count, encode and split accept up to 1,048,576 UTF-8 bytes (1 MiB).
They return Error::InputTooLarge for longer text, Error::Tokenization
when tokenization fails and Error::Internal when initialization fails.
split(text, limit) counts the entire input and returns up to limit
groups from its start. Each group ends at a token boundary that is also a
grapheme boundary. Its end is an exclusive UTF-8 byte offset in the original
string. Use the preceding group’s end (or zero) as its start.
Structs§
- Group
- One consecutive group of tokens spanning whole grapheme clusters.
- Split
- A preview of the start of a text, with its complete token count.
Enums§
- Error
- A failure to prepare the encoding or tokenize the input.
Constants§
- ENCODING
- The name of the embedded encoding.
- MAX_
INPUT_ BYTES - The largest accepted input, in UTF-8 bytes.
Functions§
- count
- Counts tokens in the entire input using the same rules and errors as
encode. - encode
- Returns the ordinary token IDs of
o200k_base, including for literal special markers. - prepare
- Initializes the shared encoding. Later calls reuse the result.
- split
- Counts the entire text and returns up to
limitgroups ending on grapheme boundaries. A zero limit returns an empty preview and the full count.