Skip to main content

TiktokenTokenCounter

Struct TiktokenTokenCounter 

Source
pub struct TiktokenTokenCounter { /* private fields */ }
Expand description

Accurate BPE-based token counter using OpenAI’s o200k_base encoding.

Uses tiktoken-rs with the vocabulary bundled at compile time — no runtime downloads. This is the recommended counter for production use.

Implementations§

Source§

impl TiktokenTokenCounter

Source

pub fn new(metadata_overhead: u32) -> TiktokenTokenCounter

Create with a custom metadata overhead.

Source

pub fn estimate_provider_visible_tool_segments<'a>( &self, segments: impl IntoIterator<Item = &'a str>, ) -> ProviderVisibleToolEstimate

Estimate already-lowered provider-visible tool segments exactly once.

segments must contain compact serialized JSON/text in the order the selected provider exposes it to the model. Each segment is one contiguous model position and is tokenized separately with the same counter used for prompt text; provider lowering must serialize adjacent content such as an initial tools array into one segment. This prevents BPE merges across positions separated by transcript content.

Repeated fragments at different model-visible positions remain repeated by design; callers must omit definitions that are not model-visible at that position. An empty slice returns an all-zero estimate.

Source

pub fn truncate_to_token_prefix(&self, text: &str, max_tokens: u32) -> String

Truncate text to at most max_tokens tokens, keeping the START.

Encodes the text once and decodes the first max_tokens tokens back to a string — O(N) (one encode + one decode), versus the O(N²) char-by-char re-tokenization the previous find_prefix_within_tokens performed (which called count_text(&text[..i]) on every char index).

§Semantics
  • max_tokens == 0 → empty string (exactly 0 tokens; never exceeds budget).
  • Text already within max_tokens → returned unchanged (fast path).
  • Otherwise the result is an exact prefix of text (its START preserved), is valid UTF-8, and re-counts to ≤ max_tokens.

If the o200k encoder is unavailable (the issue #25 fallback path), this degrades to a conservative char-based cut instead of panicking.

Source

pub fn truncate_to_token_suffix(&self, text: &str, max_tokens: u32) -> String

Truncate text to at most max_tokens tokens, keeping the END.

Symmetric to truncate_to_token_prefix: encodes once and decodes the last max_tokens tokens. Same budget / fast-path / fallback semantics; the result is a valid-UTF-8 exact suffix of text (its END preserved) that re-counts to ≤ max_tokens.

Trait Implementations§

Source§

impl Debug for TiktokenTokenCounter

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for TiktokenTokenCounter

Source§

fn default() -> TiktokenTokenCounter

Returns the “default value” for a type. Read more
Source§

impl TokenCounter for TiktokenTokenCounter

Source§

fn count_message(&self, message: &Message) -> u32

Count tokens in a single message.
Source§

fn count_text(&self, text: &str) -> u32

Count tokens in a plain text string.
Source§

fn count_messages(&self, messages: &[Message]) -> u32

Count tokens in multiple messages.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more