1use crate::ContextError;
2use std::collections::{HashMap, VecDeque};
3use std::sync::{Arc, Mutex};
4
5#[cfg(feature = "bpe")]
6mod ordinary;
7#[cfg(all(test, feature = "bpe"))]
8mod ordinary_patterns;
9#[cfg(feature = "bpe")]
10mod segmenter;
11#[cfg(feature = "bpe")]
12mod vocabulary;
13#[cfg(feature = "bpe")]
14mod vocabulary_hash;
15
16pub trait TokenCounter {
19 fn identity(&self) -> &str;
21 fn count(&self, text: &str) -> Result<usize, ContextError>;
23}
24
25#[derive(Clone, Copy, Debug)]
27pub struct TokenCacheLimits {
28 pub max_entries: usize,
30 pub max_text_bytes: usize,
32}
33
34impl Default for TokenCacheLimits {
35 fn default() -> Self {
36 Self {
37 max_entries: 2048,
38 max_text_bytes: 8 * 1024 * 1024,
39 }
40 }
41}
42
43#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
45pub struct TokenCacheStats {
46 pub hits: u64,
48 pub misses: u64,
50 pub entries: usize,
52 pub text_bytes: usize,
54}
55
56#[derive(Default)]
57struct Cache {
58 values: HashMap<Arc<str>, usize>,
59 order: VecDeque<Arc<str>>,
60 stats: TokenCacheStats,
61 generation: u64,
62}
63
64pub struct CachedTokenCounter<T> {
71 inner: T,
72 limits: TokenCacheLimits,
73 cache: Mutex<Cache>,
74}
75
76impl<T: TokenCounter> CachedTokenCounter<T> {
77 pub fn new(inner: T, limits: TokenCacheLimits) -> Self {
79 Self {
80 inner,
81 limits,
82 cache: Mutex::new(Cache::default()),
83 }
84 }
85
86 pub fn cache_stats(&self) -> Result<TokenCacheStats, ContextError> {
88 self.cache
89 .lock()
90 .map(|cache| cache.stats)
91 .map_err(|_| ContextError::Tokenizer)
92 }
93
94 pub fn clear_cache(&self) -> Result<(), ContextError> {
96 let mut cache = self.cache.lock().map_err(|_| ContextError::Tokenizer)?;
97 let generation = cache
98 .generation
99 .checked_add(1)
100 .ok_or(ContextError::LimitExceeded)?;
101 *cache = Cache {
102 generation,
103 ..Cache::default()
104 };
105 Ok(())
106 }
107}
108
109impl<T: TokenCounter> TokenCounter for CachedTokenCounter<T> {
110 fn identity(&self) -> &str {
111 self.inner.identity()
112 }
113
114 fn count(&self, text: &str) -> Result<usize, ContextError> {
115 let generation = {
116 let mut cache = self.cache.lock().map_err(|_| ContextError::Tokenizer)?;
117 if let Some(value) = cache.values.get(text).copied() {
118 cache.stats.hits = cache.stats.hits.saturating_add(1);
119 return Ok(value);
120 }
121 cache.stats.misses = cache.stats.misses.saturating_add(1);
122 cache.generation
123 };
124 let count = self.inner.count(text)?;
125 if self.limits.max_entries == 0
126 || text.len() > self.limits.max_text_bytes
127 || self.limits.max_text_bytes == 0
128 {
129 return Ok(count);
130 }
131 let mut cache = self.cache.lock().map_err(|_| ContextError::Tokenizer)?;
132 if cache.generation != generation || cache.values.contains_key(text) {
134 return Ok(count);
135 }
136 while cache.values.len() >= self.limits.max_entries
137 || cache.stats.text_bytes > self.limits.max_text_bytes - text.len()
138 {
139 if let Some(old) = cache.order.pop_front() {
140 cache.values.remove(old.as_ref());
141 cache.stats.text_bytes -= old.len();
142 } else {
143 break;
144 }
145 }
146 let key: Arc<str> = Arc::from(text);
147 cache.values.insert(Arc::clone(&key), count);
148 cache.order.push_back(key);
149 cache.stats.text_bytes += text.len();
150 cache.stats.entries = cache.values.len();
151 Ok(count)
152 }
153}
154
155#[derive(Clone, Copy, Debug, Default)]
157pub struct Utf8ByteCounter;
158
159impl TokenCounter for Utf8ByteCounter {
160 fn identity(&self) -> &str {
161 "cigar.utf8-bytes.v1"
162 }
163
164 fn count(&self, text: &str) -> Result<usize, ContextError> {
165 Ok(text.len())
166 }
167}
168
169#[cfg(feature = "bpe")]
172pub struct O200kTokenizer(CachedTokenCounter<RawO200kTokenizer>);
173
174#[cfg(feature = "bpe")]
175struct RawO200kTokenizer(ordinary::OrdinaryCounter);
176
177#[cfg(feature = "bpe")]
178impl O200kTokenizer {
179 pub fn new() -> Result<Self, ContextError> {
181 Self::with_cache_limits(TokenCacheLimits::default())
182 }
183
184 pub fn with_cache_limits(limits: TokenCacheLimits) -> Result<Self, ContextError> {
186 ordinary::OrdinaryCounter::new()
187 .map(|bpe| Self(CachedTokenCounter::new(RawO200kTokenizer(bpe), limits)))
188 .map_err(|_| ContextError::Tokenizer)
189 }
190
191 pub fn cache_stats(&self) -> Result<TokenCacheStats, ContextError> {
193 self.0.cache_stats()
194 }
195
196 pub fn clear_cache(&self) -> Result<(), ContextError> {
198 self.0.clear_cache()
199 }
200}
201
202#[cfg(feature = "bpe")]
203impl TokenCounter for O200kTokenizer {
204 fn identity(&self) -> &str {
205 self.0.identity()
206 }
207 fn count(&self, text: &str) -> Result<usize, ContextError> {
208 self.0.count(text)
209 }
210}
211
212#[cfg(feature = "bpe")]
213impl TokenCounter for RawO200kTokenizer {
214 fn identity(&self) -> &str {
215 "o200k_base.tiktoken-rs-0.12.0.ordinary"
216 }
217
218 fn count(&self, text: &str) -> Result<usize, ContextError> {
219 self.0.count(text)
220 }
221}