pub struct TokenCounter { /* private fields */ }Expand description
Token counter using tiktoken
Uses cl100k_base encoding (GPT-4, GPT-3.5-turbo, text-embedding-ada-002)
Implementations§
Source§impl TokenCounter
impl TokenCounter
Sourcepub fn new() -> Result<Self, TokenCounterError>
pub fn new() -> Result<Self, TokenCounterError>
Create a new token counter with cl100k_base encoding
Sourcepub fn count_message(&self, role: &str, content: &str) -> usize
pub fn count_message(&self, role: &str, content: &str) -> usize
Count tokens for a chat message (includes role overhead)
Approximates the token overhead for chat formatting:
- Each message has ~4 tokens overhead (role, separators)
- System messages have additional overhead
Sourcepub fn count_messages(&self, messages: &[(String, String)]) -> usize
pub fn count_messages(&self, messages: &[(String, String)]) -> usize
Count tokens for multiple messages
Sourcepub fn truncate(&self, text: &str, max_tokens: usize) -> (String, usize)
pub fn truncate(&self, text: &str, max_tokens: usize) -> (String, usize)
Truncate text to fit within a token limit
Returns the truncated text and the actual token count.
Trait Implementations§
Auto Trait Implementations§
impl Freeze for TokenCounter
impl RefUnwindSafe for TokenCounter
impl Send for TokenCounter
impl Sync for TokenCounter
impl Unpin for TokenCounter
impl UnsafeUnpin for TokenCounter
impl UnwindSafe for TokenCounter
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more